System.register([], (function (exports, module) {
  'use strict';
  return {
    execute: (function () {

      exports({
        D: isUnicodeCJK,
        E: isUnicodeSpace,
        J: safeMeasureText,
        K: isEnglishWordPartAtFirst,
        N: isEnglishWordPartAtLast,
        P: getEnglishWordPartAtFirst,
        Q: getEnglishWordPartAtLast,
        W: fragmentText,
        aH: v2$1,
        aJ: v3,
        aL: v4,
        aN: quat$1,
        aQ: mat4,
        aT: size,
        aV: rect,
        aX: color,
        ap: sampleAnimationCurve,
        aq: computeRatioByType,
        as: getPathFromRoot,
        at: getWorldTransformUntilRoot,
        b$: log,
        b0: equals$1,
        b1: approx,
        b2: clamp$1,
        b3: clamp01,
        b4: lerp,
        b5: toRadian,
        b6: toDegree,
        b7: random,
        b8: setRandGenerator,
        b9: randomRange,
        bD: deprecateModuleExportedName,
        bE: __checkObsolete__,
        bF: __checkObsoleteInNamespace__,
        bG: WorldNode3DToLocalNodeUI,
        bH: WorldNode3DToWorldNodeUI,
        bK: CCClass,
        bL: isCCClassOrFastDefined,
        bV: getSerializationMetadata,
        bY: Eventify,
        b_: debug,
        ba: randomRangeInt,
        bb: pseudoRandom,
        bc: pseudoRandomRange,
        bd: pseudoRandomRangeInt,
        be: nextPow2,
        bf: repeat$2,
        bg: pingPong,
        bh: inverseLerp,
        bi: absMaxComponent,
        bj: absMax,
        bk: enumerableProps,
        bl: floatToHalf,
        bm: halfToFloat,
        bs: BitMask,
        bt: Enum,
        bu: ccenum,
        bz: setDefaultLogTimes,
        c: createCommonjsModule,
        c$: assertIsTrue,
        c0: error,
        c1: warn,
        c2: assert,
        c3: logID,
        c4: errorID,
        c5: warnID,
        c6: assertID,
        c7: isDisplayStats,
        c8: setDisplayStats,
        c9: getError,
        cI: formerlySerializedAs$4,
        cK: shift,
        cN: setPropertyEnumType,
        cO: setPropertyEnumTypeOnAttrs,
        cR: isCCObject,
        cS: isValid,
        cV: applyMixins,
        cW: _resetDebugSetting,
        cX: binarySearch,
        cY: binarySearchEpsilon,
        cZ: binarySearchBy,
        c_: assertIsNonNullable,
        cu: murmurhash2_32_gc,
        cv: bezier,
        cw: bezierByTime,
        d$: deserialize,
        d0: assertsArrayIndex,
        d1: flattenCodeArray,
        d8: createDefaultPipeline,
        dx: find,
        e1: instantiate,
        fg: tween,
        fh: tweenUtil,
        z: getBaselineOffset
      });

      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, _toPropertyKey(descriptor.key), descriptor);
        }
      }
      function _createClass(Constructor, protoProps, staticProps) {
        if (protoProps) _defineProperties(Constructor.prototype, protoProps);
        if (staticProps) _defineProperties(Constructor, staticProps);
        Object.defineProperty(Constructor, "prototype", {
          writable: false
        });
        return Constructor;
      }
      function _extends() {
        _extends = Object.assign ? Object.assign.bind() : 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);
      }
      function _inheritsLoose(subClass, superClass) {
        subClass.prototype = Object.create(superClass.prototype);
        subClass.prototype.constructor = subClass;
        _setPrototypeOf(subClass, superClass);
      }
      function _getPrototypeOf(o) {
        _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) {
          return o.__proto__ || Object.getPrototypeOf(o);
        };
        return _getPrototypeOf(o);
      }
      function _setPrototypeOf(o, p) {
        _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : 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 {
          Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {}));
          return true;
        } catch (e) {
          return false;
        }
      }
      function _construct(Parent, args, Class) {
        if (_isNativeReflectConstruct()) {
          _construct = Reflect.construct.bind();
        } 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 _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 _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;
      }
      function _assertThisInitialized(self) {
        if (self === void 0) {
          throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
        }
        return self;
      }
      function _unsupportedIterableToArray(o, minLen) {
        if (!o) return;
        if (typeof o === "string") return _arrayLikeToArray(o, minLen);
        var n = Object.prototype.toString.call(o).slice(8, -1);
        if (n === "Object" && o.constructor) n = o.constructor.name;
        if (n === "Map" || n === "Set") return Array.from(o);
        if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
      }
      function _arrayLikeToArray(arr, len) {
        if (len == null || len > arr.length) len = arr.length;
        for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
        return arr2;
      }
      function _createForOfIteratorHelperLoose(o, allowArrayLike) {
        var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"];
        if (it) return (it = it.call(o)).next.bind(it);
        if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") {
          if (it) o = it;
          var i = 0;
          return function () {
            if (i >= o.length) return {
              done: true
            };
            return {
              done: false,
              value: o[i++]
            };
          };
        }
        throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
      }
      function _toPrimitive(input, hint) {
        if (typeof input !== "object" || input === null) return input;
        var prim = input[Symbol.toPrimitive];
        if (prim !== undefined) {
          var res = prim.call(input, hint || "default");
          if (typeof res !== "object") return res;
          throw new TypeError("@@toPrimitive must return a primitive value.");
        }
        return (hint === "string" ? String : Number)(input);
      }
      function _toPropertyKey(arg) {
        var key = _toPrimitive(arg, "string");
        return typeof key === "symbol" ? key : String(key);
      }
      function _initializerDefineProperty(target, property, descriptor, context) {
        if (!descriptor) return;
        Object.defineProperty(target, property, {
          enumerable: descriptor.enumerable,
          configurable: descriptor.configurable,
          writable: descriptor.writable,
          value: descriptor.initializer ? descriptor.initializer.call(context) : void 0
        });
      }
      function _applyDecoratedDescriptor(target, property, decorators, descriptor, context) {
        var desc = {};
        Object.keys(descriptor).forEach(function (key) {
          desc[key] = descriptor[key];
        });
        desc.enumerable = !!desc.enumerable;
        desc.configurable = !!desc.configurable;
        if ('value' in desc || desc.initializer) {
          desc.writable = true;
        }
        desc = decorators.slice().reverse().reduce(function (desc, decorator) {
          return decorator(target, property, desc) || desc;
        }, desc);
        if (context && desc.initializer !== void 0) {
          desc.value = desc.initializer ? desc.initializer.call(context) : void 0;
          desc.initializer = undefined;
        }
        if (desc.initializer === void 0) {
          Object.defineProperty(target, property, desc);
          desc = null;
        }
        return desc;
      }

      function tryDefineGlobal (name, value) {
          const _global = typeof window === 'undefined' ? global : window;
          if (typeof _global[name] === 'undefined') {
              return (_global[name] = value);
          } else {
              // eslint-disable-next-line @typescript-eslint/no-unsafe-return
              return _global[name];
          }
      }

      const NATIVE = false;
      tryDefineGlobal('CC_WECHAT', false);

      const WECHAT_MINI_PROGRAM = false;
      tryDefineGlobal('CC_BAIDU', false);

      const XIAOMI = false;
      tryDefineGlobal('CC_XIAOMI', false);
      tryDefineGlobal('CC_ALIPAY', false);
      tryDefineGlobal('CC_BYTEDANCE', false);
      tryDefineGlobal('CC_OPPO', false);
      tryDefineGlobal('CC_VIVO', false);
      tryDefineGlobal('CC_HUAWEI', false);
      tryDefineGlobal('CC_COCOSPLAY', false);
      tryDefineGlobal('CC_QTT', false);
      tryDefineGlobal('CC_LINKSURE', false);

      const EDITOR = false;
      tryDefineGlobal('CC_EDITOR', false);

      const EDITOR_NOT_IN_PREVIEW = false;

      const PREVIEW = false;
      tryDefineGlobal('CC_PREVIEW', false);
      tryDefineGlobal('CC_BUILD', true);

      const TEST = false;
      tryDefineGlobal('CC_TEST', false);
      tryDefineGlobal('CC_DEBUG', true);
      tryDefineGlobal('CC_DEV', false);

      const MINIGAME = false;
      tryDefineGlobal('CC_MINIGAME', false);

      const RUNTIME_BASED = false;
      tryDefineGlobal('CC_RUNTIME_BASED', false);
      tryDefineGlobal('CC_SUPPORT_JIT', true);

      const JSB = false;
      tryDefineGlobal('CC_JSB', false);

      var _global = typeof window === 'undefined' ? global : window;
      var legacyCC = exports('aE', {
        _global: _global
      });
      legacyCC.internal = {};
      var engineVersion = exports('aD', '3.8.1');
      _global.CocosEngine = legacyCC.ENGINE_VERSION = engineVersion;
      _global.cc = legacyCC;
      var ccwindow = typeof globalThis.jsb !== 'undefined' ? typeof jsb.window !== 'undefined' ? jsb.window : globalThis : globalThis;
      _global.ccwindow = ccwindow;

      var INT_BITS = 32;
      var INT_MAX = 0x7fffffff;
      var INT_MIN = -1 << INT_BITS - 1;
      function sign$1(v) {
        return (v > 0) - (v < 0);
      }
      function abs$1(v) {
        var mask = v >> INT_BITS - 1;
        return (v ^ mask) - mask;
      }
      function min$3(x, y) {
        return y ^ (x ^ y) & -(x < y);
      }
      function max$4(x, y) {
        return x ^ (x ^ y) & -(x < y);
      }
      function isPow2(v) {
        return !(v & v - 1) && !!v;
      }
      function log2(v) {
        var r;
        var shift;
        r = (v > 0xFFFF) << 4;
        v >>>= r;
        shift = (v > 0xFF) << 3;
        v >>>= shift;
        r |= shift;
        shift = (v > 0xF) << 2;
        v >>>= shift;
        r |= shift;
        shift = (v > 0x3) << 1;
        v >>>= shift;
        r |= shift;
        return r | v >> 1;
      }
      function log10(v) {
        return v >= 1000000000 ? 9 : v >= 100000000 ? 8 : v >= 10000000 ? 7 : v >= 1000000 ? 6 : v >= 100000 ? 5 : v >= 10000 ? 4 : v >= 1000 ? 3 : v >= 100 ? 2 : v >= 10 ? 1 : 0;
      }
      function popCount(v) {
        v -= v >>> 1 & 0x55555555;
        v = (v & 0x33333333) + (v >>> 2 & 0x33333333);
        return (v + (v >>> 4) & 0xF0F0F0F) * 0x1010101 >>> 24;
      }
      function countTrailingZeros(v) {
        var c = 32;
        v &= -v;
        if (v) {
          c--;
        }
        if (v & 0x0000FFFF) {
          c -= 16;
        }
        if (v & 0x00FF00FF) {
          c -= 8;
        }
        if (v & 0x0F0F0F0F) {
          c -= 4;
        }
        if (v & 0x33333333) {
          c -= 2;
        }
        if (v & 0x55555555) {
          c -= 1;
        }
        return c;
      }
      function nextPow2$1(v) {
        --v;
        v |= v >>> 1;
        v |= v >>> 2;
        v |= v >>> 4;
        v |= v >>> 8;
        v |= v >>> 16;
        return v + 1;
      }
      function prevPow2(v) {
        v |= v >>> 1;
        v |= v >>> 2;
        v |= v >>> 4;
        v |= v >>> 8;
        v |= v >>> 16;
        return v - (v >>> 1);
      }
      function parity(v) {
        v ^= v >>> 16;
        v ^= v >>> 8;
        v ^= v >>> 4;
        v &= 0xf;
        return 0x6996 >>> v & 1;
      }
      var REVERSE_TABLE = new Array(256);
      (function (tab) {
        for (var i = 0; i < 256; ++i) {
          var v = i;
          var r = i;
          var s = 7;
          for (v >>>= 1; v; v >>>= 1) {
            r <<= 1;
            r |= v & 1;
            --s;
          }
          tab[i] = r << s & 0xff;
        }
      })(REVERSE_TABLE);
      function reverse(v) {
        return REVERSE_TABLE[v & 0xff] << 24 | REVERSE_TABLE[v >>> 8 & 0xff] << 16 | REVERSE_TABLE[v >>> 16 & 0xff] << 8 | REVERSE_TABLE[v >>> 24 & 0xff];
      }
      function interleave2(x, y) {
        x &= 0xFFFF;
        x = (x | x << 8) & 0x00FF00FF;
        x = (x | x << 4) & 0x0F0F0F0F;
        x = (x | x << 2) & 0x33333333;
        x = (x | x << 1) & 0x55555555;
        y &= 0xFFFF;
        y = (y | y << 8) & 0x00FF00FF;
        y = (y | y << 4) & 0x0F0F0F0F;
        y = (y | y << 2) & 0x33333333;
        y = (y | y << 1) & 0x55555555;
        return x | y << 1;
      }
      function deinterleave2(v, n) {
        v = v >>> n & 0x55555555;
        v = (v | v >>> 1) & 0x33333333;
        v = (v | v >>> 2) & 0x0F0F0F0F;
        v = (v | v >>> 4) & 0x00FF00FF;
        v = (v | v >>> 16) & 0x000FFFF;
        return v << 16 >> 16;
      }
      function interleave3(x, y, z) {
        x &= 0x3FF;
        x = (x | x << 16) & 4278190335;
        x = (x | x << 8) & 251719695;
        x = (x | x << 4) & 3272356035;
        x = (x | x << 2) & 1227133513;
        y &= 0x3FF;
        y = (y | y << 16) & 4278190335;
        y = (y | y << 8) & 251719695;
        y = (y | y << 4) & 3272356035;
        y = (y | y << 2) & 1227133513;
        x |= y << 1;
        z &= 0x3FF;
        z = (z | z << 16) & 4278190335;
        z = (z | z << 8) & 251719695;
        z = (z | z << 4) & 3272356035;
        z = (z | z << 2) & 1227133513;
        return x | z << 2;
      }
      function deinterleave3(v, n) {
        v = v >>> n & 1227133513;
        v = (v | v >>> 2) & 3272356035;
        v = (v | v >>> 4) & 251719695;
        v = (v | v >>> 8) & 4278190335;
        v = (v | v >>> 16) & 0x3FF;
        return v << 22 >> 22;
      }
      function nextCombination(v) {
        var t = v | v - 1;
        return t + 1 | (~t & -~t) - 1 >>> countTrailingZeros(v) + 1;
      }

      var bits = /*#__PURE__*/Object.freeze({
        __proto__: null,
        INT_BITS: INT_BITS,
        INT_MAX: INT_MAX,
        INT_MIN: INT_MIN,
        sign: sign$1,
        abs: abs$1,
        min: min$3,
        max: max$4,
        isPow2: isPow2,
        log2: log2,
        log10: log10,
        popCount: popCount,
        countTrailingZeros: countTrailingZeros,
        nextPow2: nextPow2$1,
        prevPow2: prevPow2,
        parity: parity,
        reverse: reverse,
        interleave2: interleave2,
        deinterleave2: deinterleave2,
        interleave3: interleave3,
        deinterleave3: deinterleave3,
        nextCombination: nextCombination
      });
      exports('aF', bits);

      var debugInfos = {
      	"1006": "[Action step]. override me",
      	"1007": "[Action update]. override me",
      	"1008": "[Action reverse]. override me",
      	"1100": "Expected 'data' dict, but not found. Config file: %s",
      	"1101": "Please load the resource first : %s",
      	"1102": "Effect settings not found, effects will not be imported.",
      	"1103": "Success to load scene: %s",
      	"1200": "cocos2d: Director: Error in gettimeofday",
      	"1204": "Running scene should not be null",
      	"1205": "The scene should not be null",
      	"1206": "loadScene: The scene index to load (%s) is out of range.",
      	"1207": "loadScene: Unknown name type to load: '%s'",
      	"1208": "loadScene: Failed to load scene '%s' because '%s' is already being loaded.",
      	"1209": "loadScene: Can not load the scene '%s' because it was not in the build settings before playing.",
      	"1210": "Failed to preload '%s', %s",
      	"1211": "loadScene: The scene index to load (%s) is out of range.",
      	"1212": "loadScene: Unknown name type to load: '%s'",
      	"1213": "loadScene: Failed to load scene '%s' because '%s' is already loading",
      	"1214": "loadScene: Can not load the scene '%s' because it was not in the build settings before playing.",
      	"1215": "Failed to preload '%s', %s",
      	"1216": "Director.runSceneImmediate: scene is not valid",
      	"1217": "Director._initOnEngineInitialized: renderer root initialization failed",
      	"1218": "Forward render pipeline initialized.",
      	"1219": "Deferred render pipeline initialized. Note that non-transparent materials with no lighting will not be rendered, such as builtin-unlit.",
      	"1220": "Failed to set shading scale, pipelineSceneData is invalid.",
      	"1221": "Setting orientation is not supported yet.",
      	"1300": "%s is not in the model pool and cannot be destroyed by destroyModel.",
      	"1400": "'%s' is deprecated, please use '%s' instead.",
      	"1404": "cc.spriteFrameCache is removed, please use cc.loader to load and cache sprite frames of atlas format.",
      	"1406": "'%s.%s' is removed",
      	"1408": "'%s' is removed",
      	"1409": "element type is wrong!",
      	"1502": "cc.scheduler.scheduleCallbackForTarget(): target should be non-null.",
      	"1503": "cc.Scheduler.pauseTarget():target should be non-null",
      	"1504": "cc.Scheduler.resumeTarget():target should be non-null",
      	"1505": "cc.Scheduler.isTargetPaused():target should be non-null",
      	"1506": "warning: you CANNOT change update priority in scheduled function",
      	"1507": "scheduler#scheduleSelector. Selector already scheduled. Updating interval from: %.4f to %.4f",
      	"1508": "Argument callback must not be empty",
      	"1509": "Argument target must be non-nullptr",
      	"1510": "cc.Scheduler: Illegal target which doesn't have id, you should do Scheduler.enableForTarget(target) before all scheduler API usage on target",
      	"1511": "cc.Scheduler: pause state of the scheduled task doesn't match the element pause state in Scheduler, the given paused state will be ignored.",
      	"1513": "cc.Scheduler: scheduler stopped using `__instanceId` as id since v2.0, you should do Scheduler.enableForTarget(target) before all scheduler API usage on target",
      	"1514": "since v3.8.0, `Scheduler.schedule(target, callback, interval)` is deprecated, please use `Scheduler.schedule(callback, target, interval)` instead.",
      	"1607": "removeFromParentAndCleanup is deprecated. Use removeFromParent instead",
      	"1619": "callback function must be non-null",
      	"1620": "interval must be positive",
      	"1623": "Set '%s' to normal node (not persist root node).",
      	"1624": "Replacing with the same sgNode",
      	"1625": "The replacement sgNode should not contain any child.",
      	"1626": "Should not set alpha via 'color', set 'opacity' please.",
      	"1627": "Not support for asynchronous creating node in SG",
      	"1632": "Node name can not include '/'.",
      	"1633": "Internal error, should not remove unknown node from parent.",
      	"1635": "reorderChild: this child is not in children list.",
      	"1636": "Node's zIndex value can't be greater than cc.macro.MAX_ZINDEX, setting to the maximum value",
      	"1637": "Node's zIndex value can't be smaller than cc.macro.MIN_ZINDEX, setting to the minimum value",
      	"1638": "Private node's zIndex can't be set, it will keep cc.macro.MIN_ZINDEX as its value",
      	"1800": "cc._EventListenerKeyboard.checkAvailable(): Invalid EventListenerKeyboard!",
      	"1801": "cc._EventListenerTouchOneByOne.checkAvailable(): Invalid EventListenerTouchOneByOne!",
      	"1802": "cc._EventListenerTouchAllAtOnce.checkAvailable(): Invalid EventListenerTouchAllAtOnce!",
      	"1803": "cc._EventListenerAcceleration.checkAvailable():_onAccelerationEvent must be non-nil",
      	"1900": "Invalid parameter.",
      	"2104": "Layer collision. The name of layer (%s) is collided with the name or value of some layer",
      	"2200": "Design resolution not valid",
      	"2201": "should set resolutionPolicy",
      	"2300": "The touches is more than MAX_TOUCHES, nUnusedIndex = %s",
      	"2402": "Forward pipeline startup failed!",
      	"3103": "cc.Texture.addImage(): path should be non-null",
      	"3119": "Lazy init texture with image element failed due to image loading failure: %s",
      	"3120": "Loading texture with unsupported type: '%s'. Add '%s' into 'cc.macro.SUPPORT_TEXTURE_FORMATS' please.",
      	"3121": "Can't find a texture format supported by the current platform! Please add a fallback format in the editor.",
      	"3122": "Error Texture in %s.",
      	"3123": "Set same texture %s.",
      	"3124": "Texture: setMipRange failed because base level is larger than max level",
      	"3300": "Rect width exceeds maximum margin: %s",
      	"3301": "Rect height exceeds maximum margin: %s",
      	"3500": "0 priority is forbidden for fixed priority since it's used for scene graph based priority.",
      	"3501": "Invalid listener type!",
      	"3502": "Can't set fixed priority with scene graph based listener.",
      	"3503": "Invalid parameters.",
      	"3504": "listener must be a cc.EventListener object when adding a fixed priority listener",
      	"3505": "The listener has been registered, please don't register it again.",
      	"3506": "Unsupported listener target.",
      	"3507": "Invalid scene graph priority!",
      	"3508": "If program goes here, there should be event in dispatch.",
      	"3509": "_inDispatch should be 1 here.",
      	"3510": "%s's scene graph node not contains in the parent's children",
      	"3511": "event is undefined",
      	"3512": "Event manager only support scene graph priority for ui nodes which contain UIComponent",
      	"3520": "Device Motion Event request permission: %s",
      	"3521": "Device Motion Event request permission failed: %s",
      	"3601": "The editor property 'playOnFocus' should be used with 'executeInEditMode' in class '%s'",
      	"3602": "Unknown editor property '%s' in class '%s'.",
      	"3603": "Use 'cc.Float' or 'cc.Integer' instead of 'cc.Number' please.",
      	"3604": "Can only indicate one type attribute for %s.",
      	"3605": "The default value of %s is not instance of %s.",
      	"3606": "No needs to indicate the '%s' attribute for %s, which its default value is type of %s.",
      	"3607": "The default value of %s must be an empty string.",
      	"3608": "The type of %s must be CCString, not String.",
      	"3609": "The type of %s must be CCBoolean, not Boolean.",
      	"3610": "The type of %s must be CCFloat or CCInteger, not Number.",
      	"3611": "Can not indicate the '%s' attribute for %s, which its default value is type of %s.",
      	"3612": "%s Just set the default value to 'new %s()' and it will be handled properly.",
      	"3613": "'No need to use 'serializable: false' or 'editorOnly: true' for the getter of '%s.%s', every getter is actually non-serialized.",
      	"3614": "Should not define constructor for cc.Component %s.",
      	"3615": "Each script can have at most one Component.",
      	"3616": "Should not specify class name %s for Component which defines in project.",
      	"3618": "ctor of '%s' can not be another CCClass",
      	"3623": "Can not use 'editor' attribute, '%s' not inherits from Components.",
      	"3625": "[isChildClassOf] superclass should be function type, not",
      	"3626": "Can't remove '%s' because '%s' depends on it.",
      	"3627": "Should not add renderer component (%s) to a Canvas node.",
      	"3628": "Should not add %s to a node which size is already used by its other component.",
      	"3633": "Properties function of '%s' should return an object!",
      	"3634": "Disallow to use '.' in property name",
      	"3637": "Can not declare %s.%s, it is already defined in the prototype of %s",
      	"3639": "Can not apply the specified attribute to the getter of '%s.%s', attribute index: %s",
      	"3640": "'%s': the setter of '%s' is already defined!",
      	"3641": "Can not construct %s because it contains object property.",
      	"3644": "Please define 'type' parameter of %s.%s as the actual constructor.",
      	"3645": "Please define 'type' parameter of %s.%s as the constructor of %s.",
      	"3646": "Unknown 'type' parameter of %s.%s：%s",
      	"3647": "The length of range array must be equal or greater than 2",
      	"3648": "Can not declare %s.%s method, it is already defined in the properties of %s.",
      	"3652": "Failed to `new %s()` under the hood, %s\nIt is used for getting default values declared in TypeScript in the first place.\nPlease ensure the constructor can be called during the script's initialization.",
      	"3653": "Please do not specifiy \"default\" attribute in decorator of \"%s\" property in \"%s\" class.\nDefault value must be initialized at their declaration:\n\n \n// Before:\n@property({\n  type: cc.SpriteFrame\n  default: null  // <--\n})\nmyProp;\n// After:\n@property({\n  type: cc.SpriteFrame\n})\nmyProp = null;   // <--",
      	"3654": "Please specifiy a default value for \"%s.%s\" property at its declaration:\n\n \n// Before:\n@property(...)\nmyProp;\n// After:\n@property(...)\nmyProp = 0;",
      	"3655": "Can not specifiy \"get\" or \"set\"  attribute in decorator for \"%s\" property in \"%s\" class.\nPlease use:\n\n \n@property(...)\nget %s () {\n    ...\n}\n@property\nset %s (value) {\n    ...\n}",
      	"3659": "Violation error: extending enumerations shall have non-overlaped member names or member values",
      	"3660": "You are explicitly specifying `undefined` type to cc property \"%s\" of cc class \"%s\".\nIs this intended? If not, this may indicate a circular reference.\nFor example:\n\n \n// foo.ts\nimport { _decorator } from 'cc';\nimport { Bar } from './bar';  // Given that './bar' also reference 'foo.ts'.\n                              // When importing './bar', execution of './bar' is hung on to wait execution of 'foo.ts',\n                              // the `Bar` imported here is `undefined` until './bar' finish its execution.\n                              // It leads to that\n@_decorator.ccclass           //  ↓\nexport class Foo {            //  ↓\n    @_decorator.type(Bar)     //  → is equivalent to `@_decorator.type(undefined)`\n    public bar: Bar;          // To eliminate this error, either:\n                              // - Refactor your module structure(recommended), or\n                              // - specify the type as cc class name: `@_decorator.type('Bar'/* or any name you specified for `Bar` */)`\n}",
      	"3700": "internal error: _prefab is undefined",
      	"3701": "Failed to load prefab asset for node '%s'",
      	"3800": "The target can not be made persist because it's not a cc.Node or it doesn't have _id property.",
      	"3801": "The node can not be made persist because it's not under root node.",
      	"3802": "The node can not be made persist because it's not in current scene.",
      	"3803": "The target can not be made persist because it's not a cc.Node or it doesn't have _id property.",
      	"3804": "getComponent: Type must be non-nil",
      	"3805": "Can't add component '%s' because %s already contains the same component.",
      	"3806": "Can't add component '%s' to %s because it conflicts with the existing '%s' derived component.",
      	"3807": "addComponent: Failed to get class '%s'",
      	"3808": "addComponent: Should not add component ('%s') when the scripts are still loading.",
      	"3809": "addComponent: The component to add must be a constructor",
      	"3810": "addComponent: The component to add must be child class of cc.Component",
      	"3811": "_addComponentAt: The component to add must be a constructor",
      	"3812": "_addComponentAt: Index out of range",
      	"3813": "removeComponent: Component must be non-nil",
      	"3814": "Argument must be non-nil",
      	"3815": "Component not owned by this entity",
      	"3816": "Node '%s' is already activating",
      	"3817": "Sorry, the component of '%s' which with an index of %s is corrupted! It has been removed.",
      	"3818": "Failed to read or parse project.json",
      	"3819": "Warning: target element is not a DIV or CANVAS",
      	"3820": "The renderer doesn't support the renderMode %s",
      	"3821": "Cannot change hierarchy while activating or deactivating the parent.",
      	"3822": "addComponent: Cannot add any component to the scene.",
      	"3823": "The enabled component (id: %s, name: %s) doesn't have a valid node",
      	"3900": "Invalid clip to add",
      	"3901": "Invalid clip to remove",
      	"3902": "clip is defaultClip, set force to true to force remove clip and animation state",
      	"3903": "animation state is playing, set force to true to force stop and remove clip and animation state",
      	"3904": "motion path of target [%s] in prop [%s] frame [%s] is not valid",
      	"3905": "sprite frames must be an Array.",
      	"3906": "Can't find easing type [%s]",
      	"3907": "Animation state is not playing or already removed",
      	"3912": "already-playing",
      	"3920": "Current context does not allow root motion.",
      	"3921": "You provided a ill-formed track path. The last component of track path should be property key, or the setter should not be empty.",
      	"3923": "Root motion is ignored since root bone could not be located in animation.",
      	"3924": "Root motion is ignored since the root bone could not be located in scene.",
      	"3925": "Target of hierarchy path should be of type Node.",
      	"3926": "Node \"%s\" has no path \"%s\".",
      	"3927": "Target of component path should be of type Node.",
      	"3928": "Node \"%s\" has no component \"%s\".",
      	"3929": "Target object has no property \"%s\".",
      	"3930": "Can not decide type for untyped track: runtime binding does not provide a getter.",
      	"3931": "Can not decide type for untyped track: got a unsupported value from runtime binding.",
      	"3932": "Common targets should only target Vectors/`Size`/`Color`.",
      	"3933": "Each curve that has common target should be numeric curve and targets string property.",
      	"3934": "Misconfigured legacy curve: the first keyframe value is number but others aren't.",
      	"3935": "We don't currently support conversion of \\`CubicSplineQuatValue\\`.",
      	"3936": "Instancing/Batching enabled for non-baked skinning model '%s', this may result in unexpected rendering artifacts. Consider turning it off in the material if you do not intend to do this.",
      	"3937": "Previous error occurred when instantiating animation clip %s on node %s.",
      	"3938": "'%s' is not found from '%s'. It's specified as the root node to play animation clip '%s'.",
      	"3940": "Error when animation attempted to bind material uniform target: target %s is not a material.",
      	"3941": "Error when animation attempted to bind material uniform target: material %s has no recorded pass %s.",
      	"3942": "Error when animation attempted to bind material uniform target: material %s at pass %s has no recorded uniform %s.",
      	"3943": "Error when animation attempted to bind material uniform target: material %s at pass %s's uniform %s has no recorded channel %s.",
      	"4003": "Label font size can't be shirnked less than 0!",
      	"4004": "force notify all fonts loaded!",
      	"4011": "Property spriteFrame of Font '%s' is invalid. Using system font instead.",
      	"4012": "The texture of Font '%s' must be already loaded on JSB. Using system font instead.",
      	"4013": "Sorry, lineHeight of system font not supported on JSB.",
      	"4200": "MaskType: IMAGE_STENCIL only support WebGL mode.",
      	"4201": "The alphaThreshold invalid in Canvas Mode.",
      	"4202": "The inverted invalid in Canvas Mode.",
      	"4300": "Can not found the %s page.",
      	"4301": "Can not add a page without UITransform.",
      	"4302": "Can not set the scroll view content when it hasn't UITransform or its parent hasn't UITransform.",
      	"4303": "The %s scrollBar on the '%s' node is not available, please check it.",
      	"4400": "Invalid RichText img tag! The sprite frame name can't be found in the ImageAtlas!",
      	"4500": "Graphics: There is no model in %s.",
      	"4600": "Script attached to '%s' is missing or invalid.",
      	"4601": "Failed to load wasm module, WebAssembly is not supported on this platform, but as a fallback Asm.js module is culled by mistake.",
      	"4700": "The dom control is not created!",
      	"4800": "unknown asset type",
      	"4901": "loadRes: should not specify the extname in %s %s",
      	"4902": "No need to release non-cached asset.",
      	"4914": "Resources url '%s' does not exist.",
      	"4915": "Pack indices and data do not match in size",
      	"4916": "Failed to download package for %s",
      	"4921": "Invalid pipe or invalid index provided!",
      	"4922": "The pipe to be inserted is already in the pipeline!",
      	"4923": "Uuid Loader: Parse asset [ %s ] failed : %s",
      	"4924": "JSON Loader: Input item doesn't contain string content",
      	"4925": "Uuid Loader: Deserialize asset [ %s ] failed : %s",
      	"4926": "Audio Downloader: no web audio context.",
      	"4927": "Audio Downloader: audio not supported on this browser!",
      	"4928": "Load %s failed!",
      	"4929": "Load Webp ( %s ) failed",
      	"4930": "Load image ( %s ) failed",
      	"4932": "Since v1.10, for any atlas (\"%s\") in the \"resources\" directory, it is not possible to find the contained SpriteFrames via `loadRes`, `getRes` or `releaseRes`. Load the SpriteAtlas first and then use `spriteAtlas.getSpriteFrame(name)` instead please.",
      	"4933": "Download Font [ %s ] failed, using Arial or system default font instead",
      	"4934": "Please assure that the full path of sub asset is correct!",
      	"4935": "Failed to skip prefab asset while deserializing PrefabInfo",
      	"5000": "You are trying to destroy a object twice or more.",
      	"5001": "object not yet destroyed",
      	"5100": "Not a plist file!",
      	"5200": "Warning: localStorage isn't enabled. Please confirm browser cookie or privacy option",
      	"5201": "browser don't support web audio",
      	"5202": "This feature supports WebGL render mode only.",
      	"5300": "Type of target to deserialize not matched with data: target is %s, data is %s",
      	"5301": "Can not find script '%s'",
      	"5302": "Can not find class '%s'",
      	"5303": "Failed to deserialize %s, missing _deserialize function.",
      	"5304": "Unable to deserialize version %s data.",
      	"5402": "cc.js.addon called on non-object:",
      	"5403": "cc.js.mixin: arguments must be type object:",
      	"5404": "The base class to extend from must be non-nil",
      	"5405": "The class to extend must be non-nil",
      	"5406": "Class should be extended before assigning any prototype members.",
      	"5500": "'notify' can not be used in 'get/set' !",
      	"5501": "'notify' must be used with 'default' !",
      	"5507": "The 'default' attribute of '%s.%s' must be an array",
      	"5508": "Invalid type of %s.%s",
      	"5510": "The 'type' attribute of '%s.%s' can not be 'Number', use cc.Float or cc.Integer instead please.",
      	"5511": "The 'type' attribute of '%s.%s' is undefined when loading script",
      	"5512": "Can not serialize '%s.%s' because the specified type is anonymous, please provide a class name or set the 'serializable' attribute of '%s.%s' to 'false'.",
      	"5513": "The 'default' value of '%s.%s' should not be used with a 'get' function.",
      	"5514": "The 'default' value of '%s.%s' should not be used with a 'set' function.",
      	"5515": "The 'default' value of '%s.%s' can not be an constructor. Set default to null please.",
      	"5517": "'%s.%s' hides inherited property '%s.%s'. To make the current property override that implementation, add the `override: true` attribute please.",
      	"5601": "Can not get current scene.",
      	"5602": "Scene is destroyed",
      	"5603": "reference node is destroyed",
      	"5700": "no %s or %s on %s",
      	"5800": "%s.lerp not yet implemented.",
      	"5801": "%s.clone not yet implemented.",
      	"5802": "%s.equals not yet implemented.",
      	"5900": "MotionStreak only support WebGL mode.",
      	"5901": "cc.MotionStreak.getOpacity has not been supported.",
      	"5902": "cc.MotionStreak.setOpacity has not been supported.",
      	"6000": "Custom should not be false if file is not specified.",
      	"6001": "The new %s must not be NaN",
      	"6017": "Incomplete or corrupt PNG file",
      	"6018": "Invalid filter algorithm: %s",
      	"6019": "Invalid byte order value.",
      	"6020": "You forgot your towel!",
      	"6021": "Unknown Field Tag: %s",
      	"6022": "Too many bits requested",
      	"6023": "No bits requested",
      	"6024": "Cannot recover from missing StripByteCounts",
      	"6025": "Cannot handle sub-byte bits per sample",
      	"6026": "Cannot handle sub-byte bits per pixel",
      	"6027": "Palette image missing color map",
      	"6028": "Unknown Photometric Interpretation: %s",
      	"6029": "Unkown error",
      	"6030": "cc.ParticleSystem: error decoding or ungzipping textureImageData",
      	"6031": "cc.ParticleSystem: unknown image format with Data",
      	"6032": "cc.ParticleSystem.initWithDictionary() : error loading the texture",
      	"6033": "cc.ParticleSystem: not allowing create to be invoked twice with different particle system",
      	"6034": "cc.ParticleSystem: shouldn't be initialized repetitively, otherwise there will be potential leak",
      	"6035": "cc.ParticleSystem: change material failed, please use proper particle material",
      	"6036": "cc.ParticleSystem: life time should bigger than 1 or buffer will be insufficient",
      	"6400": "asset.url is not usable in core process",
      	"6402": "AssetLibrary has already been initialized!",
      	"6500": "Widget target must be one of the parent nodes of it",
      	"6600": "collider not added or already removed",
      	"6601": "Can't find testFunc for (%s, $s).",
      	"6700": "Can't init canvas '%s' because it conflicts with the existing '%s', the scene should only have one active canvas at the same time.",
      	"6705": "Argument must be non-nil",
      	"6706": "Priority can't be set in RenderRoot2D node",
      	"6800": "Callback of event must be non-nil",
      	"6801": "The message must be provided",
      	"6900": "The thing you want to instantiate must be an object",
      	"6901": "The thing you want to instantiate is nil",
      	"6902": "The thing you want to instantiate is destroyed",
      	"6903": "The instantiate method for given asset do not implemented",
      	"6904": "Can not instantiate array",
      	"6905": "Can not instantiate DOM element",
      	"7100": "%s already defined in Enum.",
      	"7101": "Sorry, 'cc.Enum' not available on this platform, please report this error here: <https://github.com/cocos-creator/engine/issues/new>",
      	"7200": "Method 'initWithTMXFile' is no effect now, please set property 'tmxAsset' instead.",
      	"7201": "Method 'initWithXML' is no effect now, please set property 'tmxAsset' instead.",
      	"7202": "Add component TiledLayer into node failed.",
      	"7203": "Property 'mapLoaded' is unused now. Please write the logic to the callback 'start'.",
      	"7210": "TMX Hexa zOrder not supported",
      	"7211": "TMX invalid value",
      	"7215": "cocos2d: Warning: TMX Layer %s has no tiles",
      	"7216": "cocos2d: TMXFormat: Unsupported TMX version: %s",
      	"7217": "cocos2d: TMXFomat: Unsupported orientation: %s",
      	"7218": "cc.TMXMapInfo.parseXMLFile(): unsupported compression method",
      	"7219": "cc.TMXMapInfo.parseXMLFile(): Only base64 and/or gzip/zlib maps are supported",
      	"7221": "cc.TMXMapInfo.parseXMLFile(): Texture '%s' not found.",
      	"7222": "Parse %s failed.",
      	"7236": "cc.TMXLayer.getTileAt(): TMXLayer: the tiles map has been released",
      	"7237": "cc.TMXLayer.getTileGIDAt(): TMXLayer: the tiles map has been released",
      	"7238": "cc.TMXLayer.setTileGID(): TMXLayer: the tiles map has been released",
      	"7239": "cc.TMXLayer.setTileGID(): invalid gid: %s",
      	"7240": "cc.TMXLayer.getTileFlagsAt(): TMXLayer: the tiles map has been released",
      	"7241": "cc.TiledMap.initWithXML(): Map not found. Please check the filename.",
      	"7401": "Failed to set _defaultArmatureIndex for '%s' because the index is out of range.",
      	"7402": "Failed to set _animationIndex for '%s' because the index is out of range.",
      	"7501": "Failed to set _defaultSkinIndex for '%s' because the index is out of range.",
      	"7502": "Failed to set _animationIndex for '%s' because its skeletonData is invalid.",
      	"7503": "Failed to set _animationIndex for '%s' because the index is out of range.",
      	"7504": "Can not render dynamic created SkeletonData",
      	"7506": "Failed to load spine atlas '$s'",
      	"7507": "Please re-import '%s' because its textures is not initialized! (This workflow will be improved in the future.)",
      	"7508": "The atlas asset of '%s' is not exists!",
      	"7509": "Spine: Animation not found: %s",
      	"7510": "Spine: Animation not found: %s",
      	"7511": "Spine: Invalid input!",
      	"7600": "The context of RenderTexture is invalid.",
      	"7601": "cc.RenderTexture._initWithWidthAndHeightForWebGL() : only RGB and RGBA formats are valid for a render texture;",
      	"7602": "Could not attach texture to the framebuffer",
      	"7603": "clearDepth isn't supported on Cocos2d-Html5",
      	"7604": "saveToFile isn't supported on Cocos2d-Html5",
      	"7605": "newCCImage isn't supported on Cocos2d-Html5",
      	"7606": "GFXTexture is null",
      	"7607": "readPixels buffer size smaller than %d",
      	"7700": "On the web is always keep the aspect ratio",
      	"7701": "Can't know status",
      	"7702": "Video player's duration is not ready to get now!",
      	"7703": "Video Downloader: video not supported on this browser!",
      	"7800": "Web does not support loading",
      	"7801": "Web does not support query history",
      	"7802": "Web does not support query history",
      	"7803": "The current browser does not support the GoBack",
      	"7804": "The current browser does not support the GoForward",
      	"7805": "Web does not support zoom",
      	"7900": "cc.math.Matrix3.assign(): current matrix equals matIn",
      	"7901": "cc.math.mat4Assign(): pOut equals pIn",
      	"7902": "cc.mat.Matrix4.assignFrom(): mat4 equals current matrix",
      	"7903": "cc.math.Matrix4 equal: pMat1 and pMat2 are same object.",
      	"7904": "cc.math.Matrix4.extractPlane: Invalid plane index",
      	"7905": "cc.math.mat4Assign(): pOut equals pIn",
      	"7906": "cc.mat.Matrix4.assignFrom(): mat4 equals current matrix",
      	"7907": "cc.math.Matrix4 equals: pMat1 and pMat2 are same object.",
      	"7908": "Invalid matrix mode specified",
      	"7909": "current quaternion is an invalid value",
      	"8000": "Can't handle this field type or size",
      	"8001": "No bytes requested",
      	"8002": "Too many bytes requested",
      	"8003": "Missing StripByteCounts!",
      	"8100": "cocos2d: ERROR: Failed to compile shader:\n %s",
      	"8101": "cocos2d: ERROR: Failed to compile vertex shader",
      	"8102": "cocos2d: ERROR: Failed to compile fragment shader",
      	"8103": "cc.GLProgram.link(): Cannot link invalid program",
      	"8104": "cocos2d: ERROR: Failed to link program: %s",
      	"8105": "cocos2d: cc.shaderCache._loadDefaultShader, error shader type",
      	"8106": "Please load the resource firset : %s",
      	"8107": "cc.GLProgram.getUniformLocationForName(): uniform name should be non-null",
      	"8108": "cc.GLProgram.getUniformLocationForName(): Invalid operation. Cannot get uniform location when program is not initialized",
      	"8109": "modelView matrix is undefined.",
      	"8200": "Please set node's active instead of rigidbody's enabled.",
      	"8300": "Should only one camera exists, please check your project.",
      	"8301": "Camera does not support Canvas Mode.",
      	"8302": "Camera.viewport is deprecated, please use setViewportInOrientedSpace instead.",
      	"8400": "Wrong type arguments, 'filePath' must be a String.",
      	"9000": "Stencil manager does not support level bigger than %d in this device.",
      	"9001": "Stencil manager is already empty, cannot pop any mask",
      	"9002": "Failed to request any buffer from a mesh buffer without accessor",
      	"9003": "The internal state of LinearBufferAccessor have severe issue and irreversible, please check the reason",
      	"9004": "Failed to allocate chunk in StaticVBAccessor, the requested buffer might be too large: %d bytes",
      	"9005": "BATCHER2D_MEM_INCREMENT is too large, the Max value for BATCHER2D_MEM_INCREMENT is 2303KB (smaller than 65536 *9* 4 / 1024 = 2304KB)",
      	"9006": "QuadRenderData is removed, please use MeshRenderData instead.",
      	"9007": "Since v3.6, Because mask changes the inheritance relationship, you can directly manipulate the rendering components under the same node to complete the operation.",
      	"9100": "texture size exceeds current device limits %d/%d",
      	"9101": "The length of the TypedArrayBuffer must be an integer.",
      	"9201": "Cannot access game frame or container.",
      	"9202": "Setting window size is not supported.",
      	"9300": "The current buffer beyond the limit in ui static component, please reduce the amount",
      	"9301": "The UI has not been initialized",
      	"9302": "Can't getGFXSampler with out device",
      	"9600": "[Physics]: please check to see if physics modules are included",
      	"9610": "[Physics]: cannon.js physics system doesn't support capsule collider",
      	"9611": "[Physics]: builtin physics system doesn't support mesh collider",
      	"9612": "[Physics]: builtin physics system doesn't support cylinder collider",
      	"9613": "[Physics]: cannon.js physics system doesn't support hinge drive and angular limit",
      	"9620": "[Physics][Ammo]: changing the mesh is not supported after the initialization is completed",
      	"9630": "[Physics]: A dynamic rigid body can not have the following collider shapes: Terrain, Plane and Non-convex Mesh. Node name: %s",
      	"9640": "[Physics][builtin]: sweep functions are not supported in builtin",
      	"9641": "[Physics][cannon.js]: sweep functions are not supported in cannon.js",
      	"10001": "The sub-mesh contains %d vertices, which beyonds the capability (%d vertices most) of renderer of your platform.",
      	"10002": "Sub-mesh may include at most %d morph targets, but you specified %d.",
      	"11000": "WebGL context lost.",
      	"12001": "BlendFactors are disabled when using custom material, please modify the blend state in the material instead.",
      	"12002": "Can't add renderable component to this node because it already have one.",
      	"12004": "SubModel can only support %d passes.",
      	"12005": "Material already initialized, request aborted.",
      	"12006": "Pass already destroyed.",
      	"12007": "This is old usage, please swap the parameters.",
      	"12008": "GeometryRenderer: too many lines.",
      	"12009": "GeometryRenderer: too many triangles.",
      	"12010": "PassUtils: illegal uniform handle, accessing uniform at offset %d",
      	"12011": "Pass: setUniform is invoked with incompatible uniform data type for binding %d, expected type is %s",
      	"12012": "Can't set a material instance to a sharedMaterial slot",
      	"12100": "The font size is too big to be fitted into texture atlas. Please switch to other label cache modes or choose a smaller font size.",
      	"12101": "The asset %s has been destroyed!",
      	"12102": "Base pass cannot override states, please use pass instance instead.",
      	"12103": "Custom pipeline create shader %s failed. Please restart editor.",
      	"12104": "Create shader %s failed.",
      	"12105": "Pass resources incomplete.",
      	"12106": "Cannot patch non-builtin macros.",
      	"12107": "Custom pipeline invalid render pass, program: %s. Please restart editor.",
      	"12108": "Custom pipeline invalid render phase, program: %s. Please restart editor.",
      	"13100": "Incorrect CCON magic.",
      	"13101": "Unknown CCON version number: %d.",
      	"13102": "CCON Format error.",
      	"13103": "Can not encode CCON binary: lack of text encoder.",
      	"13104": "Can not decode CCON binary: lack of text decoder.",
      	"14000": "State machine matched too many transitions(greater than %s) during this frame: %s.",
      	"14100": "Pool.destroy no longer take a function as parameter, Please specify destruct function in the construction of Pool instead",
      	"14200": "Can not update a static mesh.",
      	"14201": "The primitiveIndex is out of range.",
      	"14202": "meshopt asm decoder initialized",
      	"14203": "meshopt wasm decoder initialized",
      	"14204": "meshopt decoder error: %d",
      	"14300": "Can not keep world transform due to the zero scaling of parent node",
      	"14400": "Spline error: less than 2 knots.",
      	"14401": "Spline error: less than 4 knots or not a multiple of 4.\n\n<!-- Rendering algorithm reserved: 15000 - 16000 -->",
      	"15000": "Can not find corresponding diffuse map for environment lighting, use hemisphere diffuse instead, change environment lighting type to regenerate diffuse map",
      	"15001": "Can not find environment map, disable IBL lighting",
      	"15002": "Diffuse map resource is missing, please change environment lighting type to regenerate resource",
      	"15003": "The shadow visible distance is so small that CSM stratification is not effective, Please change the value of shadowDistance so that it is 10 times greater than 0.1",
      	"15004": "The native folder may be generated from older versions, please refer https://docs.cocos.com/creator/manual/en/release-notes/ to upgrade.",
      	"15100": "Camera '%s' clear flag is skybox, but skybox is disabled,  may cause strange background effect, please set camera clear flag to solid color.",
      	"16000": "'%s' is deprecated since v%s.",
      	"16001": "'%s' is deprecated since v%s, please use '%s' instead.",
      	"16002": "'%s' is removed since v%s.",
      	"16003": "'%s' is removed since v%s, please use '%s' instead.",
      	"16101": "The effect('%s') you are looking for does not exist, please confirm the effect name in the editor. NOTE: Since 3.6, the name of the built-in effect has been changed to its name in the editor, please check it out. More information please refer to https://docs.cocos.com/creator/manual/en/shader/effect-inspector.html",
      	"16201": "The asset replacing failed, can not found override asset('%s') for '%s'",
      	"16301": "node '%s' doesn't have any ModelRenderer component, this component will not work. please add ModelRenderer component first",
      	"16302": "There is no reflection probe in the scene or no probe is near the current object. No reflection probe will take effect on this object. Please create a new reflection probe or move existing ones closer.",
      	"16303": "Skin material needs floating-point render target, please check ENABLE_FLOAT_OUTPUT define in Project Settings--Macro",
      	"16304": "Skin material may need more accurate calculations, please select a head model of standard size, check the isGlobalStandardSkinObject option in the MeshRender component.",
      	"0100": "%s not yet implemented.",
      	"0200": "You should specify a valid DOM canvas element."
      };

      var ccdocument$3 = ccwindow.document;
      var logList = null;
      var ccLog = console.log.bind(console);
      var ccWarn = ccLog;
      var ccError = ccLog;
      var ccAssert = function ccAssert(condition, message) {
        if (!condition) {
          for (var _len = arguments.length, optionalParams = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
            optionalParams[_key - 2] = arguments[_key];
          }
          console.log("ASSERT: " + formatString.apply(void 0, [message].concat(optionalParams)));
        }
      };
      var ccDebug = ccLog;
      function formatString() {
        for (var _len2 = arguments.length, data = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
          data[_key2] = arguments[_key2];
        }
        return legacyCC.js.formatStr.apply(null, data);
      }
      function log() {
        return ccLog.apply(void 0, arguments);
      }
      function warn() {
        return ccWarn.apply(void 0, arguments);
      }
      function error() {
        return ccError.apply(void 0, arguments);
      }
      function assert(condition, message) {
        for (var _len3 = arguments.length, optionalParams = new Array(_len3 > 2 ? _len3 - 2 : 0), _key3 = 2; _key3 < _len3; _key3++) {
          optionalParams[_key3 - 2] = arguments[_key3];
        }
        return ccAssert.apply(void 0, [condition, message].concat(optionalParams));
      }
      function debug() {
        return ccDebug.apply(void 0, arguments);
      }
      function _resetDebugSetting(mode) {
        ccLog = ccWarn = ccError = ccAssert = ccDebug = function ccDebug() {};
        if (mode === DebugMode.NONE) {
          return;
        }
        if (mode > DebugMode.ERROR) {
          var logToWebPage = function logToWebPage(msg) {
            if (!legacyCC.game.canvas) {
              return;
            }
            if (!logList) {
              var logDiv = ccdocument$3.createElement('Div');
              logDiv.setAttribute('id', 'logInfoDiv');
              logDiv.setAttribute('width', '200');
              logDiv.setAttribute('height', legacyCC.game.canvas.height);
              var logDivStyle = logDiv.style;
              logDivStyle.zIndex = '99999';
              logDivStyle.position = 'absolute';
              logDivStyle.top = logDivStyle.left = '0';
              logList = ccdocument$3.createElement('textarea');
              logList.setAttribute('rows', '20');
              logList.setAttribute('cols', '30');
              logList.setAttribute('disabled', 'true');
              var logListStyle = logList.style;
              logListStyle.backgroundColor = 'transparent';
              logListStyle.borderBottom = '1px solid #cccccc';
              logListStyle.borderTopWidth = logListStyle.borderLeftWidth = logListStyle.borderRightWidth = '0px';
              logListStyle.borderTopStyle = logListStyle.borderLeftStyle = logListStyle.borderRightStyle = 'none';
              logListStyle.padding = '0px';
              logListStyle.margin = '0px';
              logDiv.appendChild(logList);
              legacyCC.game.canvas.parentNode.appendChild(logDiv);
            }
            logList.value = logList.value + msg + "\r\n";
            logList.scrollTop = logList.scrollHeight;
          };
          ccError = function ccError() {
            logToWebPage("ERROR :  " + formatString.apply(void 0, arguments));
          };
          ccAssert = function ccAssert(condition, message) {
            if (!condition) {
              for (var _len4 = arguments.length, optionalParams = new Array(_len4 > 2 ? _len4 - 2 : 0), _key4 = 2; _key4 < _len4; _key4++) {
                optionalParams[_key4 - 2] = arguments[_key4];
              }
              logToWebPage("ASSERT: " + formatString.apply(void 0, [message].concat(optionalParams)));
            }
          };
          if (mode !== DebugMode.ERROR_FOR_WEB_PAGE) {
            ccWarn = function ccWarn() {
              logToWebPage("WARN :  " + formatString.apply(void 0, arguments));
            };
          }
          if (mode === DebugMode.INFO_FOR_WEB_PAGE) {
            ccLog = function ccLog() {
              logToWebPage(formatString.apply(void 0, arguments));
            };
          }
        } else if (console) {
          if (!console.error) {
            console.error = console.log;
          }
          if (!console.warn) {
            console.warn = console.log;
          }
          if (console.error.bind) {
            ccError = console.error.bind(console);
          } else {
            ccError = function () {
              for (var _len5 = arguments.length, data = new Array(_len5), _key5 = 0; _key5 < _len5; _key5++) {
                data[_key5] = arguments[_key5];
              }
              return console.error.apply(console, data);
            };
          }
          ccAssert = function ccAssert(condition, message) {
            if (!condition) {
              for (var _len6 = arguments.length, optionalParams = new Array(_len6 > 2 ? _len6 - 2 : 0), _key6 = 2; _key6 < _len6; _key6++) {
                optionalParams[_key6 - 2] = arguments[_key6];
              }
              var errorText = formatString.apply(void 0, [message].concat(optionalParams));
              {
                throw new Error(errorText);
              }
            }
          };
        }
        if (mode !== DebugMode.ERROR) {
          if (console.warn.bind) {
            ccWarn = console.warn.bind(console);
          } else {
            ccWarn = function () {
              for (var _len7 = arguments.length, data = new Array(_len7), _key7 = 0; _key7 < _len7; _key7++) {
                data[_key7] = arguments[_key7];
              }
              return console.warn.apply(console, data);
            };
          }
        }
        if (mode <= DebugMode.INFO) {
          if (console.log.bind) {
            ccLog = console.log.bind(console);
          } else {
            ccLog = function ccLog() {
              for (var _len8 = arguments.length, data = new Array(_len8), _key8 = 0; _key8 < _len8; _key8++) {
                data[_key8] = arguments[_key8];
              }
              return console.log.apply(console, data);
            };
          }
        }
        if (mode <= DebugMode.VERBOSE) {
          if (typeof console.debug === 'function') {
            var vendorDebug = console.debug.bind(console);
            ccDebug = function ccDebug() {
              return vendorDebug.apply(void 0, arguments);
            };
          }
        }
      }
      function _throw(error_) {
        {
          var stack = error_.stack;
          if (stack) {
            error(stack);
          } else {
            error(error_);
          }
          return undefined;
        }
      }
      function getTypedFormatter(type) {
        return function (id) {
          var msg = debugInfos[id] || 'unknown id' ;
          for (var _len9 = arguments.length, args = new Array(_len9 > 1 ? _len9 - 1 : 0), _key9 = 1; _key9 < _len9; _key9++) {
            args[_key9 - 1] = arguments[_key9];
          }
          if (args.length === 0) {
            return msg;
          }
          return formatString.apply(void 0, [msg].concat(args)) ;
        };
      }
      var logFormatter = getTypedFormatter();
      function logID(id) {
        for (var _len10 = arguments.length, optionalParams = new Array(_len10 > 1 ? _len10 - 1 : 0), _key10 = 1; _key10 < _len10; _key10++) {
          optionalParams[_key10 - 1] = arguments[_key10];
        }
        log(logFormatter.apply(void 0, [id].concat(optionalParams)));
      }
      var warnFormatter = getTypedFormatter();
      function warnID(id) {
        for (var _len11 = arguments.length, optionalParams = new Array(_len11 > 1 ? _len11 - 1 : 0), _key11 = 1; _key11 < _len11; _key11++) {
          optionalParams[_key11 - 1] = arguments[_key11];
        }
        warn(warnFormatter.apply(void 0, [id].concat(optionalParams)));
      }
      var errorFormatter = getTypedFormatter();
      function errorID(id) {
        for (var _len12 = arguments.length, optionalParams = new Array(_len12 > 1 ? _len12 - 1 : 0), _key12 = 1; _key12 < _len12; _key12++) {
          optionalParams[_key12 - 1] = arguments[_key12];
        }
        error(errorFormatter.apply(void 0, [id].concat(optionalParams)));
      }
      var assertFormatter = getTypedFormatter();
      function assertID(condition, id) {
        if (condition) {
          return;
        }
        for (var _len13 = arguments.length, optionalParams = new Array(_len13 > 2 ? _len13 - 2 : 0), _key13 = 2; _key13 < _len13; _key13++) {
          optionalParams[_key13 - 2] = arguments[_key13];
        }
        assert(false, assertFormatter.apply(void 0, [id].concat(optionalParams)));
      }
      var DebugMode; exports('ca', DebugMode);
      (function (DebugMode) {
        DebugMode[DebugMode["NONE"] = 0] = "NONE";
        DebugMode[DebugMode["VERBOSE"] = 1] = "VERBOSE";
        DebugMode[DebugMode["INFO"] = 2] = "INFO";
        DebugMode[DebugMode["WARN"] = 3] = "WARN";
        DebugMode[DebugMode["ERROR"] = 4] = "ERROR";
        DebugMode[DebugMode["INFO_FOR_WEB_PAGE"] = 5] = "INFO_FOR_WEB_PAGE";
        DebugMode[DebugMode["WARN_FOR_WEB_PAGE"] = 6] = "WARN_FOR_WEB_PAGE";
        DebugMode[DebugMode["ERROR_FOR_WEB_PAGE"] = 7] = "ERROR_FOR_WEB_PAGE";
      })(DebugMode || (exports('ca', DebugMode = {})));
      function getError(errorId) {
        for (var _len14 = arguments.length, param = new Array(_len14 > 1 ? _len14 - 1 : 0), _key14 = 1; _key14 < _len14; _key14++) {
          param[_key14 - 1] = arguments[_key14];
        }
        return errorFormatter.apply(void 0, [errorId].concat(param));
      }
      function isDisplayStats() {
        return legacyCC.profiler ? legacyCC.profiler.isShowingStats() : false;
      }
      function setDisplayStats(displayStats) {
        if (legacyCC.profiler) {
          displayStats ? legacyCC.profiler.showStats() : legacyCC.profiler.hideStats();
        }
      }

      var debug$1 = /*#__PURE__*/Object.freeze({
        __proto__: null,
        log: log,
        warn: warn,
        error: error,
        assert: assert,
        debug: debug,
        _resetDebugSetting: _resetDebugSetting,
        _throw: _throw,
        logID: logID,
        warnID: warnID,
        errorID: errorID,
        assertID: assertID,
        get DebugMode () { return DebugMode; },
        getError: getError,
        isDisplayStats: isDisplayStats,
        setDisplayStats: setDisplayStats
      });

      var _class$3b;
      var NonUuidMark = '.';
      var IDGenerator = function () {
        function IDGenerator(category) {
          this.id = void 0;
          this.prefix = void 0;
          this.id = 0 | Math.random() * 998;
          this.prefix = category ? category + NonUuidMark : '';
        }
        var _proto = IDGenerator.prototype;
        _proto.getNewId = function getNewId() {
          return this.prefix + (++this.id).toString();
        };
        return IDGenerator;
      }();
      _class$3b = IDGenerator;
      IDGenerator.global = new _class$3b('global');

      var tempCIDGenerator = new IDGenerator('TmpCId.');
      var aliasesTag = typeof Symbol === 'undefined' ? '__aliases__' : Symbol('[[Aliases]]');
      var classNameTag = '__classname__';
      var classIdTag = '__cid__';
      function isNumber(object) {
        return typeof object === 'number' || object instanceof Number;
      }
      function isString(object) {
        return typeof object === 'string' || object instanceof String;
      }
      function isEmptyObject(obj) {
        for (var key in obj) {
          return false;
        }
        return true;
      }
      var value = function () {
        var descriptor = {
          value: undefined,
          enumerable: false,
          writable: false,
          configurable: true
        };
        return function (object, propertyName, value_, writable, enumerable) {
          descriptor.value = value_;
          descriptor.writable = writable;
          descriptor.enumerable = enumerable;
          Object.defineProperty(object, propertyName, descriptor);
          descriptor.value = undefined;
        };
      }();
      var getset = function () {
        var descriptor = {
          get: undefined,
          set: undefined,
          enumerable: false
        };
        return function (object, propertyName, getter, setter, enumerable, configurable) {
          if (enumerable === void 0) {
            enumerable = false;
          }
          if (configurable === void 0) {
            configurable = false;
          }
          if (typeof setter === 'boolean') {
            console.log('Set `setter` to boolean is deprecated. Please don not use like this again.');
            enumerable = setter;
            setter = undefined;
          }
          descriptor.get = getter;
          descriptor.set = setter;
          descriptor.enumerable = enumerable;
          descriptor.configurable = configurable;
          Object.defineProperty(object, propertyName, descriptor);
          descriptor.get = undefined;
          descriptor.set = undefined;
        };
      }();
      var get = function () {
        var descriptor = {
          get: undefined,
          enumerable: false,
          configurable: false
        };
        return function (object, propertyName, getter, enumerable, configurable) {
          descriptor.get = getter;
          descriptor.enumerable = enumerable;
          descriptor.configurable = configurable;
          Object.defineProperty(object, propertyName, descriptor);
          descriptor.get = undefined;
        };
      }();
      var set = function () {
        var descriptor = {
          set: undefined,
          enumerable: false,
          configurable: false
        };
        return function (object, propertyName, setter, enumerable, configurable) {
          descriptor.set = setter;
          descriptor.enumerable = enumerable;
          descriptor.configurable = configurable;
          Object.defineProperty(object, propertyName, descriptor);
          descriptor.set = undefined;
        };
      }();
      function createMap(forceDictMode) {
        var map = Object.create(null);
        if (forceDictMode) {
          var INVALID_IDENTIFIER_1 = '.';
          var INVALID_IDENTIFIER_2 = '/';
          map[INVALID_IDENTIFIER_1] = 1;
          map[INVALID_IDENTIFIER_2] = 1;
          delete map[INVALID_IDENTIFIER_1];
          delete map[INVALID_IDENTIFIER_2];
        }
        return map;
      }
      function getClassName(objOrCtor) {
        if (typeof objOrCtor === 'function') {
          var prototype = objOrCtor.prototype;
          if (prototype && prototype.hasOwnProperty(classNameTag) && prototype[classNameTag]) {
            return prototype[classNameTag];
          }
          var ret = '';
          if (objOrCtor.name) {
            ret = objOrCtor.name;
          }
          if (objOrCtor.toString) {
            var arr;
            var str = objOrCtor.toString();
            if (str.charAt(0) === '[') {
              arr = /\[\w+\s*(\w+)\]/.exec(str);
            } else {
              arr = /function\s*(\w+)/.exec(str);
            }
            if (arr && arr.length === 2) {
              ret = arr[1];
            }
          }
          return ret !== 'Object' ? ret : '';
        } else if (objOrCtor && objOrCtor.constructor) {
          return getClassName(objOrCtor.constructor);
        }
        return '';
      }
      function obsolete(object, obsoleted, newExpr, writable) {
        var extractPropName = /([^.]+)$/;
        var oldProp = extractPropName.exec(obsoleted)[0];
        var newProp = extractPropName.exec(newExpr)[0];
        function getter() {
          return this[newProp];
        }
        function setter(value_) {
          this[newProp] = value_;
        }
        if (writable) {
          getset(object, oldProp, getter, setter);
        } else {
          get(object, oldProp, getter);
        }
      }
      function obsoletes(obj, objName, props, writable) {
        for (var obsoleted in props) {
          var newName = props[obsoleted];
          obsolete(obj, objName + "." + obsoleted, newName, writable);
        }
      }
      var REGEXP_NUM_OR_STR = /(%d)|(%s)/;
      var REGEXP_STR = /%s/;
      function formatStr(msg) {
        for (var _len = arguments.length, subst = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
          subst[_key - 1] = arguments[_key];
        }
        if (arguments.length === 0) {
          return '';
        }
        if (subst.length === 0) {
          return "" + msg;
        }
        var hasSubstitution = typeof msg === 'string' && REGEXP_NUM_OR_STR.test(msg);
        if (hasSubstitution) {
          for (var _iterator = _createForOfIteratorHelperLoose(subst), _step; !(_step = _iterator()).done;) {
            var arg = _step.value;
            var regExpToTest = typeof arg === 'number' ? REGEXP_NUM_OR_STR : REGEXP_STR;
            if (regExpToTest.test(msg)) {
              var notReplaceFunction = "" + arg;
              msg = msg.replace(regExpToTest, notReplaceFunction);
            } else {
              msg += " " + arg;
            }
          }
        } else {
          for (var _iterator2 = _createForOfIteratorHelperLoose(subst), _step2; !(_step2 = _iterator2()).done;) {
            var _arg = _step2.value;
            msg += " " + _arg;
          }
        }
        return msg;
      }
      function shiftArguments() {
        var len = arguments.length - 1;
        var args = new Array(len);
        for (var i = 0; i < len; ++i) {
          args[i] = arguments[i + 1];
        }
        return args;
      }
      function getPropertyDescriptor(object, propertyName) {
        while (object) {
          var pd = Object.getOwnPropertyDescriptor(object, propertyName);
          if (pd) {
            return pd;
          }
          object = Object.getPrototypeOf(object);
        }
        return null;
      }
      function _copyProp(name, source, target) {
        var pd = getPropertyDescriptor(source, name);
        if (pd) {
          Object.defineProperty(target, name, pd);
        }
      }
      function copyAllProperties(source, target, excepts) {
        var propertyNames = Object.getOwnPropertyNames(source);
        for (var i = 0, len = propertyNames.length; i < len; ++i) {
          var _propertyName = propertyNames[i];
          if (excepts.indexOf(_propertyName) !== -1) {
            continue;
          }
          _copyProp(_propertyName, source, target);
        }
      }
      function addon(object) {
        object = object || {};
        for (var _len2 = arguments.length, sources = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
          sources[_key2 - 1] = arguments[_key2];
        }
        for (var _i = 0, _sources = sources; _i < _sources.length; _i++) {
          var source = _sources[_i];
          if (source) {
            if (typeof source !== 'object') {
              errorID(5402, source);
              continue;
            }
            for (var name in source) {
              if (!(name in object)) {
                _copyProp(name, source, object);
              }
            }
          }
        }
        return object;
      }
      function mixin(object) {
        object = object || {};
        for (var _len3 = arguments.length, sources = new Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) {
          sources[_key3 - 1] = arguments[_key3];
        }
        for (var _i2 = 0, _sources2 = sources; _i2 < _sources2.length; _i2++) {
          var source = _sources2[_i2];
          if (source) {
            if (typeof source !== 'object') {
              errorID(5403, source);
              continue;
            }
            for (var name in source) {
              _copyProp(name, source, object);
            }
          }
        }
        return object;
      }
      function extend(cls, base) {
        for (var p in base) {
          if (base.hasOwnProperty(p)) {
            cls[p] = base[p];
          }
        }
        cls.prototype = Object.create(base.prototype, {
          constructor: {
            value: cls,
            writable: true,
            configurable: true
          }
        });
        return cls;
      }
      function getSuper(constructor) {
        var proto = constructor.prototype;
        var dunderProto = proto && Object.getPrototypeOf(proto);
        return dunderProto && dunderProto.constructor;
      }
      function isChildClassOf(subclass, superclass) {
        if (subclass && superclass) {
          if (typeof subclass !== 'function') {
            return false;
          }
          if (typeof superclass !== 'function') {
            return false;
          }
          if (subclass === superclass) {
            return true;
          }
          for (;;) {
            subclass = getSuper(subclass);
            if (!subclass) {
              return false;
            }
            if (subclass === superclass) {
              return true;
            }
          }
        }
        return false;
      }
      function clear$1(object) {
        for (var _i3 = 0, _Object$keys = Object.keys(object); _i3 < _Object$keys.length; _i3++) {
          var key = _Object$keys[_i3];
          delete object[key];
        }
      }
      function isTempClassId(id) {
        return typeof id !== 'string' || id.startsWith(tempCIDGenerator.prefix);
      }
      var _idToClass = createMap(true);
      var _nameToClass = createMap(true);
      function setup(tag, table, allowExist) {
        return function (id, constructor) {
          if (constructor.prototype.hasOwnProperty(tag)) {
            delete table[constructor.prototype[tag]];
          }
          value(constructor.prototype, tag, id);
          if (id) {
            var registered = table[id];
            if (!allowExist && registered && registered !== constructor) {
              var err = "A Class already exists with the same " + tag + " : \"" + id + "\".";
              error(err);
            } else {
              table[id] = constructor;
            }
          }
        };
      }
      var _setClassId = setup('__cid__', _idToClass, false);
      var doSetClassName = setup('__classname__', _nameToClass, true);
      function setClassName(className, constructor) {
        doSetClassName(className, constructor);
        if (!constructor.prototype.hasOwnProperty(classIdTag)) {
          var _id = className || tempCIDGenerator.getNewId();
          if (_id) {
            _setClassId(_id, constructor);
          }
        }
      }
      function setClassAlias(target, alias) {
        var nameRegistry = _nameToClass[alias];
        var idRegistry = _idToClass[alias];
        var ok = true;
        if (nameRegistry && nameRegistry !== target) {
          error("\"" + alias + "\" has already been set as name or alias of another class.");
          ok = false;
        }
        if (idRegistry && idRegistry !== target) {
          error("\"" + alias + "\" has already been set as id or alias of another class.");
          ok = false;
        }
        if (ok) {
          var classAliases = target[aliasesTag];
          if (!classAliases) {
            classAliases = [];
            target[aliasesTag] = classAliases;
          }
          classAliases.push(alias);
          _nameToClass[alias] = target;
          _idToClass[alias] = target;
        }
      }
      function unregisterClass() {
        for (var _len4 = arguments.length, constructors = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
          constructors[_key4] = arguments[_key4];
        }
        for (var _i4 = 0, _constructors = constructors; _i4 < _constructors.length; _i4++) {
          var _constructor = _constructors[_i4];
          var p = _constructor.prototype;
          var classId = p[classIdTag];
          if (classId) {
            delete _idToClass[classId];
          }
          var classname = p[classNameTag];
          if (classname) {
            delete _nameToClass[classname];
          }
          var aliases = p[aliasesTag];
          if (aliases) {
            for (var iAlias = 0; iAlias < aliases.length; ++iAlias) {
              var alias = aliases[iAlias];
              delete _nameToClass[alias];
              delete _idToClass[alias];
            }
          }
        }
      }
      function _getClassById(classId) {
        return getClassById(classId);
      }
      function getClassById(classId) {
        return _idToClass[classId];
      }
      function getClassByName(classname) {
        return _nameToClass[classname];
      }
      function _getClassId(obj, allowTempId) {
        return getClassId(obj, allowTempId);
      }
      function getClassId(obj, allowTempId) {
        allowTempId = typeof allowTempId !== 'undefined' ? allowTempId : true;
        var res;
        if (typeof obj === 'function' && obj.prototype.hasOwnProperty(classIdTag)) {
          res = obj.prototype[classIdTag];
          if (!allowTempId && (EDITOR) && isTempClassId(res)) {
            return '';
          }
          return res;
        }
        if (obj && obj.constructor) {
          var prototype = obj.constructor.prototype;
          if (prototype && prototype.hasOwnProperty(classIdTag)) {
            res = obj[classIdTag];
            if (!allowTempId && (EDITOR) && isTempClassId(res)) {
              return '';
            }
            return res;
          }
        }
        return '';
      }

      var Pool$1 = function () {
        var _proto = Pool.prototype;
        _proto.get = function get() {
          return this._get();
        };
        function Pool(_0, _1) {
          this.count = void 0;
          this._pool = void 0;
          this._cleanup = void 0;
          var size = _1 === undefined ? _0 : _1;
          var cleanupFunc = _1 === undefined ? null : _0;
          this.count = 0;
          this._pool = new Array(size);
          this._cleanup = cleanupFunc;
        }
        _proto._get = function _get() {
          if (this.count > 0) {
            --this.count;
            var cache = this._pool[this.count];
            this._pool[this.count] = null;
            return cache;
          }
          return null;
        };
        _proto.put = function put(obj) {
          var pool = this._pool;
          if (this.count < pool.length) {
            if (this._cleanup && this._cleanup(obj) === false) {
              return;
            }
            pool[this.count] = obj;
            ++this.count;
          }
        };
        _proto.resize = function resize(length) {
          if (length >= 0) {
            this._pool.length = length;
            if (this.count > length) {
              this.count = length;
            }
          }
        };
        return Pool;
      }();

      var MutableForwardIterator = function () {
        function MutableForwardIterator(array) {
          this.i = 0;
          this.array = array;
        }
        var _proto = MutableForwardIterator.prototype;
        _proto.remove = function remove(value) {
          var index = this.array.indexOf(value);
          if (index >= 0) {
            this.removeAt(index);
          }
        };
        _proto.removeAt = function removeAt(i) {
          this.array.splice(i, 1);
          if (i <= this.i) {
            --this.i;
          }
        };
        _proto.fastRemove = function fastRemove(value) {
          var index = this.array.indexOf(value);
          if (index >= 0) {
            this.fastRemoveAt(index);
          }
        };
        _proto.fastRemoveAt = function fastRemoveAt(i) {
          var array = this.array;
          array[i] = array[array.length - 1];
          --array.length;
          if (i <= this.i) {
            --this.i;
          }
        };
        _proto.push = function push(item) {
          this.array.push(item);
        };
        _createClass(MutableForwardIterator, [{
          key: "length",
          get: function get() {
            return this.array.length;
          },
          set: function set(value) {
            this.array.length = value;
            if (this.i >= value) {
              this.i = value - 1;
            }
          }
        }]);
        return MutableForwardIterator;
      }();

      function removeAt(array, index) {
        array.splice(index, 1);
      }
      function fastRemoveAt$2(array, index) {
        var length = array.length;
        if (index < 0 || index >= length) {
          return;
        }
        array[index] = array[length - 1];
        array.length = length - 1;
      }
      function remove(array, value) {
        var index = array.indexOf(value);
        if (index >= 0) {
          removeAt(array, index);
          return true;
        } else {
          return false;
        }
      }
      function fastRemove(array, value) {
        var index = array.indexOf(value);
        if (index >= 0) {
          array[index] = array[array.length - 1];
          --array.length;
        }
      }
      function removeIf(array, predicate) {
        var index = array.findIndex(predicate);
        if (index >= 0) {
          var _value = array[index];
          removeAt(array, index);
          return _value;
        }
      }
      function verifyType(array, type) {
        if (array && array.length > 0) {
          for (var _iterator = _createForOfIteratorHelperLoose(array), _step; !(_step = _iterator()).done;) {
            var item = _step.value;
            if (!(item instanceof type)) {
              logID(1300);
              return false;
            }
          }
        }
        return true;
      }
      function removeArray(array, removals) {
        for (var i = 0, l = removals.length; i < l; i++) {
          remove(array, removals[i]);
        }
      }
      function appendObjectsAt(array, objects, index) {
        array.splice.apply(array, [index, 0].concat(objects));
        return array;
      }
      function contains$2(array, value) {
        return array.indexOf(value) >= 0;
      }
      function copy(array) {
        var len = array.length;
        var cloned = new Array(len);
        for (var i = 0; i < len; i += 1) {
          cloned[i] = array[i];
        }
        return cloned;
      }

      var array = /*#__PURE__*/Object.freeze({
        __proto__: null,
        removeAt: removeAt,
        fastRemoveAt: fastRemoveAt$2,
        remove: remove,
        fastRemove: fastRemove,
        removeIf: removeIf,
        verifyType: verifyType,
        removeArray: removeArray,
        appendObjectsAt: appendObjectsAt,
        contains: contains$2,
        copy: copy,
        MutableForwardIterator: MutableForwardIterator
      });

      var js = {
        IDGenerator: IDGenerator,
        Pool: Pool$1,
        array: array,
        isNumber: isNumber,
        isString: isString,
        isEmptyObject: isEmptyObject,
        getPropertyDescriptor: getPropertyDescriptor,
        addon: addon,
        mixin: mixin,
        extend: extend,
        getSuper: getSuper,
        isChildClassOf: isChildClassOf,
        clear: clear$1,
        value: value,
        getset: getset,
        get: get,
        set: set,
        unregisterClass: unregisterClass,
        getClassName: getClassName,
        setClassName: setClassName,
        setClassAlias: setClassAlias,
        getClassByName: getClassByName,
        getClassById: getClassById,
        get _registeredClassNames() {
          return _extends({}, _nameToClass);
        },
        set _registeredClassNames(value) {
          clear$1(_nameToClass);
          Object.assign(_nameToClass, value);
        },
        get _registeredClassIds() {
          return _extends({}, _idToClass);
        },
        set _registeredClassIds(value) {
          clear$1(_idToClass);
          Object.assign(_idToClass, value);
        },
        _getClassId: _getClassId,
        getClassId: getClassId,
        _setClassId: _setClassId,
        _getClassById: _getClassById,
        obsolete: obsolete,
        obsoletes: obsoletes,
        formatStr: formatStr,
        shiftArguments: shiftArguments,
        createMap: createMap
      };
      legacyCC.js = js;

      var js$1 = /*#__PURE__*/Object.freeze({
        __proto__: null,
        array: array,
        js: js,
        IDGenerator: IDGenerator,
        Pool: Pool$1,
        isNumber: isNumber,
        isString: isString,
        isEmptyObject: isEmptyObject,
        value: value,
        getset: getset,
        get: get,
        set: set,
        createMap: createMap,
        getClassName: getClassName,
        obsolete: obsolete,
        obsoletes: obsoletes,
        formatStr: formatStr,
        shiftArguments: shiftArguments,
        getPropertyDescriptor: getPropertyDescriptor,
        copyAllProperties: copyAllProperties,
        addon: addon,
        mixin: mixin,
        extend: extend,
        getSuper: getSuper,
        isChildClassOf: isChildClassOf,
        clear: clear$1,
        _idToClass: _idToClass,
        _nameToClass: _nameToClass,
        _setClassId: _setClassId,
        setClassName: setClassName,
        setClassAlias: setClassAlias,
        unregisterClass: unregisterClass,
        _getClassById: _getClassById,
        getClassById: getClassById,
        getClassByName: getClassByName,
        _getClassId: _getClassId,
        getClassId: getClassId
      });
      exports('bw', js$1);

      function BitMask(obj) {
        if ('__bitmask__' in obj) {
          return obj;
        }
        value(obj, '__bitmask__', null, true);
        var lastIndex = -1;
        var keys = Object.keys(obj);
        for (var i = 0; i < keys.length; i++) {
          var key = keys[i];
          var val = obj[key];
          if (val === -1) {
            val = ++lastIndex;
            obj[key] = val;
          } else if (typeof val === 'number') {
            lastIndex = val;
          } else if (typeof val === 'string' && Number.isInteger(parseFloat(key))) {
            continue;
          }
          var reverseKey = "" + val;
          if (key !== reverseKey) {
            value(obj, reverseKey, key);
          }
        }
        return obj;
      }
      BitMask.isBitMask = function (BitMaskType) {
        return BitMaskType && BitMaskType.hasOwnProperty('__bitmask__');
      };
      BitMask.getList = function (BitMaskDef) {
        if (BitMaskDef.__bitmask__) {
          return BitMaskDef.__bitmask__;
        }
        return BitMask.update(BitMaskDef);
      };
      BitMask.update = function (BitMaskDef) {
        if (!Array.isArray(BitMaskDef.__bitmask__)) {
          BitMaskDef.__bitmask__ = [];
        }
        var bitList = BitMaskDef.__bitmask__;
        bitList.length = 0;
        for (var name in BitMaskDef) {
          var v = BitMaskDef[name];
          if (Number.isInteger(v)) {
            bitList.push({
              name: name,
              value: v
            });
          }
        }
        bitList.sort(function (a, b) {
          return a.value - b.value;
        });
        return bitList;
      };
      legacyCC.BitMask = BitMask;

      function assertIsNonNullable(expr, message) {
        assertIsTrue(!(expr === null || expr === undefined), message);
      }
      function assertIsTrue(expr, message) {
        if (!expr) {
          throw new Error("Assertion failed: " + (message !== null && message !== void 0 ? message : '<no-message>'));
        }
      }
      function assertsArrayIndex(array, index) {
        assertIsTrue(index >= 0 && index < array.length, "Array index " + index + " out of bounds: [0, " + array.length + ")");
      }

      function Enum(obj) {
        if ('__enums__' in obj) {
          return obj;
        }
        value(obj, '__enums__', null, true);
        return Enum.update(obj);
      }
      Enum.update = function (obj) {
        var lastIndex = -1;
        var keys = Object.keys(obj);
        for (var i = 0; i < keys.length; i++) {
          var key = keys[i];
          var val = obj[key];
          if (val === -1) {
            val = ++lastIndex;
            obj[key] = val;
          } else if (typeof val === 'number') {
            lastIndex = val;
          } else if (typeof val === 'string' && Number.isInteger(parseFloat(key))) {
            continue;
          }
          var reverseKey = "" + val;
          if (key !== reverseKey) {
            value(obj, reverseKey, key);
          }
        }
        if (Array.isArray(obj.__enums__)) {
          updateList(obj);
        }
        return obj;
      };
      (function (_Enum) {})(Enum || (exports('bt', Enum = {})));
      Enum.isEnum = function (enumType) {
        return enumType && enumType.hasOwnProperty('__enums__');
      };
      function assertIsEnum(enumType) {
        assertIsTrue(enumType.hasOwnProperty('__enums__'));
      }
      Enum.getList = function (enumType) {
        assertIsEnum(enumType);
        if (enumType.__enums__) {
          return enumType.__enums__;
        }
        return updateList(enumType);
      };
      function updateList(enumType) {
        assertIsEnum(enumType);
        var enums = enumType.__enums__ || [];
        enums.length = 0;
        for (var name in enumType) {
          var v = enumType[name];
          if (Number.isInteger(v)) {
            enums.push({
              name: name,
              value: v
            });
          }
        }
        enums.sort(function (a, b) {
          return a.value - b.value;
        });
        enumType.__enums__ = enums;
        return enums;
      }
      Enum.sortList = function (enumType, compareFn) {
        assertIsEnum(enumType);
        if (!Array.isArray(enumType.__enums__)) {
          return;
        }
        enumType.__enums__.sort(compareFn);
      };
      function ccenum(enumType) {
        if (!('__enums__' in enumType)) {
          value(enumType, '__enums__', null, true);
        }
      }
      legacyCC.Enum = Enum;

      var ValueType = exports('bv', function () {
        function ValueType() {}
        var _proto = ValueType.prototype;
        _proto.clone = function clone() {
          errorID(100, getClassName(this) + ".clone");
          return this;
        };
        _proto.equals = function equals(other) {
          return false;
        };
        _proto.set = function set(other) {
          errorID(100, getClassName(this) + ".set");
        };
        _proto.toString = function toString() {
          return "";
        };
        return ValueType;
      }());
      setClassName('cc.ValueType', ValueType);
      legacyCC.ValueType = ValueType;

      var Category;
      (function (Category) {
        Category["PATH"] = "path";
        Category["ENGINE"] = "engine";
        Category["ASSETS"] = "assets";
        Category["SCRIPTING"] = "scripting";
        Category["PHYSICS"] = "physics";
        Category["RENDERING"] = "rendering";
        Category["LAUNCH"] = "launch";
        Category["SCREEN"] = "screen";
        Category["SPLASH_SCREEN"] = "splashScreen";
        Category["ANIMATION"] = "animation";
        Category["PROFILING"] = "profiling";
        Category["PLUGINS"] = "plugins";
        Category["XR"] = "xr";
      })(Category || (Category = {}));
      var Settings = exports('cq', function () {
        function Settings() {
          this._settings = {};
          this._override = {};
        }
        var _proto = Settings.prototype;
        _proto.init = function init(path, overrides) {
          var _this = this;
          if (path === void 0) {
            path = '';
          }
          if (overrides === void 0) {
            overrides = {};
          }
          for (var categoryName in overrides) {
            var category = overrides[categoryName];
            if (category) {
              for (var name in category) {
                this.overrideSettings(categoryName, name, category[name]);
              }
            }
          }
          if (!path) return Promise.resolve();
          if (window.oh) {
            return new Promise(function (resolve, reject) {
              var settingsModule = '../settings.js';
              module.import(settingsModule).then(function (res) {
                _this._settings = res["default"];
                resolve();
              })["catch"](function (e) {
                return reject(e);
              });
            });
          }
          return new Promise(function (resolve, reject) {
            {
              var xhr = new XMLHttpRequest();
              xhr.open('GET', path);
              xhr.responseType = 'text';
              xhr.onload = function () {
                _this._settings = JSON.parse(xhr.response);
                resolve();
              };
              xhr.onerror = function () {
                reject(new Error('request settings failed!'));
              };
              xhr.send(null);
            }
          });
        };
        _proto.overrideSettings = function overrideSettings(category, name, value) {
          if (!(category in this._override)) {
            this._override[category] = {};
          }
          this._override[category][name] = value;
        };
        _proto.querySettings = function querySettings(category, name) {
          if (category in this._override) {
            var categorySettings = this._override[category];
            if (categorySettings && name in categorySettings) {
              return categorySettings[name];
            }
          }
          if (category in this._settings) {
            var _categorySettings = this._settings[category];
            if (_categorySettings && name in _categorySettings) {
              return _categorySettings[name];
            }
          }
          return null;
        };
        return Settings;
      }());
      Settings.Category = Category;
      var settings = exports('cr', new Settings());
      legacyCC.settings = settings;

      var SUPPORT_TEXTURE_FORMATS = ['.astc', '.pkm', '.pvr', '.webp', '.jpg', '.jpeg', '.bmp', '.png'];
      var KEY = {
        none: 0,
        back: 6,
        menu: 18,
        backspace: 8,
        tab: 9,
        enter: 13,
        shift: 16,
        ctrl: 17,
        alt: 18,
        pause: 19,
        capslock: 20,
        escape: 27,
        space: 32,
        pageup: 33,
        pagedown: 34,
        end: 35,
        home: 36,
        left: 37,
        up: 38,
        right: 39,
        down: 40,
        select: 41,
        insert: 45,
        Delete: 46,
        0: 48,
        1: 49,
        2: 50,
        3: 51,
        4: 52,
        5: 53,
        6: 54,
        7: 55,
        8: 56,
        9: 57,
        a: 65,
        b: 66,
        c: 67,
        d: 68,
        e: 69,
        f: 70,
        g: 71,
        h: 72,
        i: 73,
        j: 74,
        k: 75,
        l: 76,
        m: 77,
        n: 78,
        o: 79,
        p: 80,
        q: 81,
        r: 82,
        s: 83,
        t: 84,
        u: 85,
        v: 86,
        w: 87,
        x: 88,
        y: 89,
        z: 90,
        num0: 96,
        num1: 97,
        num2: 98,
        num3: 99,
        num4: 100,
        num5: 101,
        num6: 102,
        num7: 103,
        num8: 104,
        num9: 105,
        '*': 106,
        '+': 107,
        '-': 109,
        numdel: 110,
        '/': 111,
        f1: 112,
        f2: 113,
        f3: 114,
        f4: 115,
        f5: 116,
        f6: 117,
        f7: 118,
        f8: 119,
        f9: 120,
        f10: 121,
        f11: 122,
        f12: 123,
        numlock: 144,
        scrolllock: 145,
        ';': 186,
        semicolon: 186,
        equal: 187,
        '=': 187,
        ',': 188,
        comma: 188,
        dash: 189,
        '.': 190,
        period: 190,
        forwardslash: 191,
        grave: 192,
        '[': 219,
        openbracket: 219,
        backslash: 220,
        ']': 221,
        closebracket: 221,
        quote: 222,
        dpadLeft: 1000,
        dpadRight: 1001,
        dpadUp: 1003,
        dpadDown: 1004,
        dpadCenter: 1005
      };
      var macro = exports('cd', {
        SUPPORT_TEXTURE_FORMATS: SUPPORT_TEXTURE_FORMATS,
        KEY: KEY,
        RAD: Math.PI / 180,
        DEG: 180 / Math.PI,
        REPEAT_FOREVER: Number.MAX_VALUE - 1,
        FLT_EPSILON: 0.0000001192092896,
        ORIENTATION_PORTRAIT: 1,
        ORIENTATION_LANDSCAPE: 2,
        ORIENTATION_AUTO: 3,
        ENABLE_TILEDMAP_CULLING: true,
        TOUCH_TIMEOUT: 5000,
        ENABLE_TRANSPARENT_CANVAS: false,
        ENABLE_WEBGL_ANTIALIAS: true,
        ENABLE_FLOAT_OUTPUT: false,
        CLEANUP_IMAGE_CACHE: false,
        ENABLE_MULTI_TOUCH: true,
        MAX_LABEL_CANVAS_POOL_SIZE: 20,
        ENABLE_WEBGL_HIGHP_STRUCT_VALUES: false,
        BATCHER2D_MEM_INCREMENT: 144,
        CUSTOM_PIPELINE_NAME: '',
        init: function init() {
          var defaultValues = settings.querySettings(Settings.Category.ENGINE, 'macros');
          if (defaultValues) {
            for (var key in defaultValues) {
              macro[key] = defaultValues[key];
            }
          }
        }
      });
      legacyCC.macro = macro;

      function setTimeoutRAF(callback, delay) {
        var _globalThis$__globalX;
        for (var _len = arguments.length, args = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
          args[_key - 2] = arguments[_key];
        }
        var start = performance.now();
        var raf = requestAnimationFrame || window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame;
        if (raf === undefined || (_globalThis$__globalX = globalThis.__globalXR) !== null && _globalThis$__globalX !== void 0 && _globalThis$__globalX.isWebXR) {
          return setTimeout.apply(void 0, [callback, delay].concat(args));
        }
        var handleRAF = function handleRAF() {
          if (performance.now() - start < delay) {
            raf(handleRAF);
          } else {
            callback.apply(void 0, args);
          }
        };
        return raf(handleRAF);
      }

      var BUILTIN_CLASSID_RE = /^(?:cc|dragonBones|sp|ccsg)\..+/;
      var BASE64_KEYS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
      var values = new Array(123);
      for (var i$2 = 0; i$2 < 123; ++i$2) {
        values[i$2] = 64;
      }
      for (var _i = 0; _i < 64; ++_i) {
        values[BASE64_KEYS.charCodeAt(_i)] = _i;
      }
      var BASE64_VALUES = values;
      function propertyDefine(ctor, sameNameGetSets, diffNameGetSets) {
        function define(np, propName, getter, setter) {
          var pd = Object.getOwnPropertyDescriptor(np, propName);
          if (pd) {
            if (pd.get) {
              np[getter] = pd.get;
            }
            if (pd.set && setter) {
              np[setter] = pd.set;
            }
          } else {
            var getterFunc = np[getter];
            {
              getset(np, propName, getterFunc, np[setter]);
            }
          }
        }
        var propName;
        var np = ctor.prototype;
        for (var _i2 = 0; _i2 < sameNameGetSets.length; _i2++) {
          propName = sameNameGetSets[_i2];
          var suffix = propName[0].toUpperCase() + propName.slice(1);
          define(np, propName, "get" + suffix, "set" + suffix);
        }
        for (propName in diffNameGetSets) {
          var gs = diffNameGetSets[propName];
          define(np, propName, gs[0], gs[1]);
        }
      }
      function pushToMap(map, key, value, pushFront) {
        var exists = map[key];
        if (exists) {
          if (Array.isArray(exists)) {
            if (pushFront) {
              exists.push(exists[0]);
              exists[0] = value;
            } else {
              exists.push(value);
            }
          } else {
            map[key] = pushFront ? [value, exists] : [exists, value];
          }
        } else {
          map[key] = value;
        }
      }
      function contains$1(refNode, otherNode) {
        if (typeof refNode.contains === 'function') {
          return refNode.contains(otherNode);
        } else if (typeof refNode.compareDocumentPosition === 'function') {
          return !!(refNode.compareDocumentPosition(otherNode) & 16);
        } else {
          var node = otherNode.parentNode;
          if (node) {
            do {
              if (node === refNode) {
                return true;
              } else {
                node = node.parentNode;
              }
            } while (node !== null);
          }
          return false;
        }
      }
      function isDomNode(node) {
        if (typeof window === 'object' && typeof Node === 'function') {
          return node instanceof Node;
        } else {
          return !!node && typeof node === 'object' && typeof node.nodeType === 'number' && typeof node.nodeName === 'string';
        }
      }
      function callInNextTick(callback, p1, p2) {
        if (callback) {
          setTimeoutRAF(function () {
            callback(p1, p2);
          }, 0);
        }
      }
      function tryCatchFunctor_EDITOR(funcName) {
        return Function('target', "" + ('try {\n' + '  target.') + funcName + "();\n" + "}\n" + "catch (e) {\n" + "  cc._throw(e);\n" + "}");
      }
      function isPlainEmptyObj_DEV(obj) {
        if (!obj || obj.constructor !== Object) {
          return false;
        }
        return isEmptyObject(obj);
      }
      function clampf(value, min_inclusive, max_inclusive) {
        if (min_inclusive > max_inclusive) {
          var temp = min_inclusive;
          min_inclusive = max_inclusive;
          max_inclusive = temp;
        }
        return value < min_inclusive ? min_inclusive : value < max_inclusive ? value : max_inclusive;
      }
      function degreesToRadians(angle) {
        return angle * macro.RAD;
      }
      function radiansToDegrees(angle) {
        return angle * macro.DEG;
      }
      legacyCC.misc = {
        BUILTIN_CLASSID_RE: BUILTIN_CLASSID_RE,
        BASE64_VALUES: BASE64_VALUES,
        propertyDefine: propertyDefine,
        pushToMap: pushToMap,
        contains: contains$1,
        isDomNode: isDomNode,
        callInNextTick: callInNextTick,
        isPlainEmptyObj_DEV: isPlainEmptyObj_DEV,
        clampf: clampf,
        degreesToRadians: degreesToRadians,
        radiansToDegrees: radiansToDegrees
      };

      var misc = /*#__PURE__*/Object.freeze({
        __proto__: null,
        BUILTIN_CLASSID_RE: BUILTIN_CLASSID_RE,
        BASE64_VALUES: BASE64_VALUES,
        propertyDefine: propertyDefine,
        pushToMap: pushToMap,
        contains: contains$1,
        isDomNode: isDomNode,
        callInNextTick: callInNextTick,
        tryCatchFunctor_EDITOR: tryCatchFunctor_EDITOR,
        isPlainEmptyObj_DEV: isPlainEmptyObj_DEV,
        clampf: clampf,
        degreesToRadians: degreesToRadians,
        radiansToDegrees: radiansToDegrees
      });
      exports('bx', misc);

      var DELIMETER$1 = '$_$';
      function createAttrsSingle(owner, superAttrs) {
        var attrs = superAttrs ? Object.create(superAttrs) : {};
        value(owner, '__attrs__', attrs);
        return attrs;
      }
      function createAttrs(subclass) {
        if (typeof subclass !== 'function') {
          var instance = subclass;
          return createAttrsSingle(instance, getClassAttrs(instance.constructor));
        }
        var superClass;
        var chains = legacyCC.Class.getInheritanceChain(subclass);
        for (var i = chains.length - 1; i >= 0; i--) {
          var cls = chains[i];
          var attrs = cls.hasOwnProperty('__attrs__') && cls.__attrs__;
          if (!attrs) {
            superClass = chains[i + 1];
            createAttrsSingle(cls, superClass && superClass.__attrs__);
          }
        }
        superClass = chains[0];
        createAttrsSingle(subclass, superClass && superClass.__attrs__);
        return subclass.__attrs__;
      }
      function attr(constructor, propertyName) {
        var attrs = getClassAttrs(constructor);
        var prefix = propertyName + DELIMETER$1;
        var ret = {};
        for (var key in attrs) {
          if (key.startsWith(prefix)) {
            ret[key.slice(prefix.length)] = attrs[key];
          }
        }
        return ret;
      }
      function getClassAttrs(constructor) {
        return constructor.hasOwnProperty('__attrs__') && constructor.__attrs__ || createAttrs(constructor);
      }
      function setClassAttr(ctor, propName, key, value) {
        getClassAttrs(ctor)[propName + DELIMETER$1 + key] = value;
      }
      var PrimitiveType$1 = function () {
        function PrimitiveType(name, defaultValue) {
          this.name = void 0;
          this["default"] = void 0;
          this.name = name;
          this["default"] = defaultValue;
        }
        var _proto = PrimitiveType.prototype;
        _proto.toString = function toString() {
          return this.name;
        };
        return PrimitiveType;
      }();
      var CCInteger = exports('bN', new PrimitiveType$1('Integer', 0));
      legacyCC.Integer = CCInteger;
      legacyCC.CCInteger = CCInteger;
      var CCFloat = exports('bO', new PrimitiveType$1('Float', 0.0));
      legacyCC.Float = CCFloat;
      legacyCC.CCFloat = CCFloat;
      var CCBoolean = exports('bP', new PrimitiveType$1('Boolean', false));
      legacyCC.Boolean = CCBoolean;
      legacyCC.CCBoolean = CCBoolean;
      var CCString = exports('bQ', new PrimitiveType$1('String', ''));
      legacyCC.String = CCString;
      legacyCC.CCString = CCString;
      function getTypeChecker_ET(type, attributeName) {
        return function (constructor, mainPropertyName) {
          var propInfo = "\"" + getClassName(constructor) + "." + mainPropertyName + "\"";
          var mainPropAttrs = attr(constructor, mainPropertyName);
          var mainPropAttrsType = mainPropAttrs.type;
          if (mainPropAttrsType === CCInteger || mainPropAttrsType === CCFloat) {
            mainPropAttrsType = 'Number';
          } else if (mainPropAttrsType === CCString || mainPropAttrsType === CCBoolean) {
            mainPropAttrsType = "" + mainPropAttrsType;
          }
          if (mainPropAttrsType !== type) {
            warnID(3604, propInfo);
            return;
          }
          if (!mainPropAttrs.hasOwnProperty('default')) {
            return;
          }
          var defaultVal = mainPropAttrs["default"];
          if (typeof defaultVal === 'undefined') {
            return;
          }
          var isContainer = Array.isArray(defaultVal) || isPlainEmptyObj_DEV(defaultVal);
          if (isContainer) {
            return;
          }
          var defaultType = typeof defaultVal;
          var type_lowerCase = type.toLowerCase();
          if (defaultType === type_lowerCase) {
            if (type_lowerCase === 'object') {
              if (defaultVal && !(defaultVal instanceof mainPropAttrs.ctor)) {
                warnID(3605, propInfo, getClassName(mainPropAttrs.ctor));
              } else {
                return;
              }
            } else if (type !== 'Number') {
              warnID(3606, attributeName, propInfo, type);
            }
          } else if (defaultType !== 'function') {
            if (type === CCString["default"] && defaultVal == null) {
              warnID(3607, propInfo);
            } else {
              warnID(3611, attributeName, propInfo, defaultType);
            }
          } else {
            return;
          }
          delete mainPropAttrs.type;
        };
      }
      function getObjTypeChecker_ET(typeCtor) {
        return function (classCtor, mainPropName) {
          getTypeChecker_ET('Object', 'type')(classCtor, mainPropName);
          var defaultDef = getClassAttrs(classCtor)[mainPropName + DELIMETER$1 + "default"];
          var defaultVal = legacyCC.Class.getDefault(defaultDef);
          if (!Array.isArray(defaultVal) && isChildClassOf(typeCtor, legacyCC.ValueType)) {
            var typename = getClassName(typeCtor);
            var info = formatStr('No need to specify the "type" of "%s.%s" because %s is a child class of ValueType.', getClassName(classCtor), mainPropName, typename);
            if (defaultDef) {
              log(info);
            } else {
              warnID(3612, info, typename, getClassName(classCtor), mainPropName, typename);
            }
          }
        };
      }

      var attributeUtils = /*#__PURE__*/Object.freeze({
        __proto__: null,
        DELIMETER: DELIMETER$1,
        createAttrsSingle: createAttrsSingle,
        createAttrs: createAttrs,
        attr: attr,
        getClassAttrs: getClassAttrs,
        setClassAttr: setClassAttr,
        PrimitiveType: PrimitiveType$1,
        CCInteger: CCInteger,
        CCFloat: CCFloat,
        CCBoolean: CCBoolean,
        CCString: CCString,
        getTypeChecker_ET: getTypeChecker_ET,
        getObjTypeChecker_ET: getObjTypeChecker_ET
      });

      var SerializableAttrs = {
        "default": {},
        serializable: {},
        editorOnly: {},
        formerlySerializedAs: {}
      };
      function parseNotify(val, propName, notify, properties) {
        if (val.get || val.set) {
          return;
        }
        if (val.hasOwnProperty('default')) {
          var newKey = "_N$" + propName;
          val.get = function () {
            return this[newKey];
          };
          val.set = function (value) {
            var oldValue = this[newKey];
            this[newKey] = value;
            notify.call(this, oldValue);
          };
          var newValue = {};
          properties[newKey] = newValue;
          for (var attr in SerializableAttrs) {
            var v = SerializableAttrs[attr];
            if (val.hasOwnProperty(attr)) {
              newValue[attr] = val[attr];
              if (!v.canUsedInGet) {
                delete val[attr];
              }
            }
          }
        }
      }
      function parseType(val, type, className, propName) {
        if (Array.isArray(type)) {
          if (type.length > 0) {
            val.type = type = type[0];
          } else {
            return errorID(5508, className, propName);
          }
        }
        if (typeof type === 'function') {
          if (type === String) {
            val.type = legacyCC.String;
          } else if (type === Boolean) {
            val.type = legacyCC.Boolean;
          } else if (type === Number) {
            val.type = legacyCC.Float;
          }
        }
      }
      function _wrapOptions(isGetset, _default, type) {
        var res = isGetset || typeof _default === 'undefined' ? {
          _short: true
        } : {
          _short: true,
          "default": _default
        };
        if (type) {
          res.type = type;
        }
        return res;
      }
      function getFullFormOfProperty(options, isGetset) {
        var isLiteral = options && options.constructor === Object;
        if (!isLiteral) {
          if (Array.isArray(options) && options.length > 0) {
            return _wrapOptions(isGetset, [], options);
          } else if (typeof options === 'function') {
            var type = options;
            return _wrapOptions(isGetset, isChildClassOf(type, legacyCC.ValueType) ? new type() : null, type);
          } else if (options instanceof PrimitiveType$1) {
            return _wrapOptions(isGetset, undefined, options);
          } else {
            return _wrapOptions(isGetset, options);
          }
        }
        return null;
      }
      function preprocessAttrs(properties, className, cls) {
        for (var propName in properties) {
          var val = properties[propName];
          var fullForm = getFullFormOfProperty(val, false);
          if (fullForm) {
            val = properties[propName] = fullForm;
          }
          if (val) {
            var notify = val.notify;
            if (notify) {
              {
                parseNotify(val, propName, notify, properties);
              }
            }
            if ('type' in val) {
              parseType(val, val.type, className, propName);
            }
          }
        }
      }

      var requiringFrames = [];
      function push(module, uuid, script, importMeta) {
        if (script === undefined) {
          script = uuid;
          uuid = '';
        }
        requiringFrames.push({
          uuid: uuid,
          script: script,
          module: module,
          exports: module.exports,
          beh: null,
          importMeta: importMeta
        });
      }
      function pop() {
        var frameInfo = requiringFrames.pop();
        var module = frameInfo.module;
        var exports = module.exports;
        if (exports === frameInfo.exports) {
          for (var anykey in exports) {
            return;
          }
          module.exports = exports = frameInfo.cls;
        }
      }
      function peek() {
        return requiringFrames[requiringFrames.length - 1];
      }
      legacyCC._RF = {
        push: push,
        pop: pop,
        peek: peek
      };

      var PropertyStashInternalFlag;
      (function (PropertyStashInternalFlag) {
        PropertyStashInternalFlag[PropertyStashInternalFlag["STANDALONE"] = 1] = "STANDALONE";
        PropertyStashInternalFlag[PropertyStashInternalFlag["IMPLICIT_VISIBLE"] = 2] = "IMPLICIT_VISIBLE";
        PropertyStashInternalFlag[PropertyStashInternalFlag["IMPLICIT_SERIALIZABLE"] = 4] = "IMPLICIT_SERIALIZABLE";
      })(PropertyStashInternalFlag || (PropertyStashInternalFlag = {}));

      function setPropertyEnumType(objectOrConstructor, propertyName, enumType) {
        setPropertyEnumTypeOnAttrs(getClassAttrs(objectOrConstructor), propertyName, enumType);
      }
      function setPropertyEnumTypeOnAttrs(attrs, propertyName, enumType) {
        attrs["" + propertyName + DELIMETER$1 + "type"] = 'Enum';
        attrs["" + propertyName + DELIMETER$1 + "enumList"] = Enum.getList(enumType);
      }

      var DELIMETER = DELIMETER$1;
      var CCCLASS_TAG = '__ctors__';
      var ENUM_TAG = exports('cP', 'Enum');
      var BITMASK_TAG = exports('cQ', 'BitMask');
      function pushUnique(array, item) {
        if (array.indexOf(item) < 0) {
          array.push(item);
        }
      }
      function appendProp(cls, name) {
        pushUnique(cls.__props__, name);
      }
      function defineProp(cls, className, propName, val) {
        appendProp(cls, propName);
        parseAttributes(cls, val, className, propName);
      }
      function defineGetSet(cls, name, propName, val) {
        var getter = val.get;
        val.set;
        if (getter) {
          parseAttributes(cls, val, name, propName);
          setClassAttr(cls, propName, 'serializable', false);
        }
      }
      function getDefault(defaultVal) {
        if (typeof defaultVal === 'function') {
          {
            return defaultVal();
          }
        }
        return defaultVal;
      }
      function doDefine(className, baseClass, options) {
        var ctor = options.ctor;
        value(ctor, CCCLASS_TAG, true, true);
        ctor.prototype;
        if (baseClass) {
          ctor.$super = baseClass;
        }
        setClassName(className, ctor);
        return ctor;
      }
      function define$1(className, baseClass, options) {
        var Component = legacyCC.Component;
        var frame = peek();
        if (frame && isChildClassOf(baseClass, Component)) {
          if (isChildClassOf(frame.cls, Component)) {
            errorID(3615);
            return null;
          }
          className = className || frame.script;
        }
        var cls = doDefine(className, baseClass, options);
        if (frame) {
          if (isChildClassOf(baseClass, Component)) {
            var uuid = frame.uuid;
            if (uuid) {
              _setClassId(uuid, cls);
            }
            frame.cls = cls;
          } else if (!isChildClassOf(frame.cls, Component)) {
            frame.cls = cls;
          }
        }
        return cls;
      }
      function getNewValueTypeCodeJit(value) {
        var clsName = getClassName(value);
        var type = value.constructor;
        var res = "new " + clsName + "(";
        for (var i = 0; i < type.__props__.length; i++) {
          var prop = type.__props__[i];
          var propVal = value[prop];
          res += propVal;
          if (i < type.__props__.length - 1) {
            res += ',';
          }
        }
        return res + ")";
      }
      function escapeForJS$1(s) {
        return JSON.stringify(s).replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029");
      }
      var IDENTIFIER_RE$1 = /^[A-Za-z_$][0-9A-Za-z_$]*$/;
      function declareProperties(cls, className, properties, baseClass) {
        cls.__props__ = [];
        if (baseClass && baseClass.__props__) {
          cls.__props__ = baseClass.__props__.slice();
        }
        if (properties) {
          preprocessAttrs(properties, className);
          for (var propName in properties) {
            var val = properties[propName];
            if (!val.get && !val.set) {
              defineProp(cls, className, propName, val);
            } else {
              defineGetSet(cls, className, propName, val);
            }
          }
        }
        var attrs = getClassAttrs(cls);
        cls.__values__ = cls.__props__.filter(function (prop) {
          return attrs["" + prop + DELIMETER + "serializable"] !== false;
        });
      }
      function CCClass(options) {
        var name = options.name;
        var base = options["extends"];
        var cls = define$1(name, base, options);
        if (!name) {
          name = legacyCC.js.getClassName(cls);
        }
        cls._sealed = true;
        if (base) {
          base._sealed = false;
        }
        var properties = options.properties;
        declareProperties(cls, name, properties, base);
        var editor = options.editor;
        if (editor) {
          if (isChildClassOf(base, legacyCC.Component)) {
            legacyCC.Component._registerEditorProps(cls, editor);
          }
        }
        return cls;
      }
      CCClass._isCCClass = function isCCClass(constructor) {
        var _constructor$hasOwnPr;
        return constructor === null || constructor === void 0 ? void 0 : (_constructor$hasOwnPr = constructor.hasOwnProperty) === null || _constructor$hasOwnPr === void 0 ? void 0 : _constructor$hasOwnPr.call(constructor, CCCLASS_TAG);
      };
      CCClass.fastDefine = function (className, constructor, serializableFields) {
        setClassName(className, constructor);
        var props = constructor.__props__ = constructor.__values__ = Object.keys(serializableFields);
        var attrs = getClassAttrs(constructor);
        for (var i = 0; i < props.length; i++) {
          var key = props[i];
          attrs[key + DELIMETER + "visible"] = false;
          attrs[key + DELIMETER + "default"] = serializableFields[key];
        }
      };
      CCClass.Attr = attributeUtils;
      CCClass.attr = attr;
      function isCCClassOrFastDefined(constructor) {
        var _constructor$hasOwnPr2;
        return constructor === null || constructor === void 0 ? void 0 : (_constructor$hasOwnPr2 = constructor.hasOwnProperty) === null || _constructor$hasOwnPr2 === void 0 ? void 0 : _constructor$hasOwnPr2.call(constructor, '__values__');
      }
      CCClass.isCCClassOrFastDefined = isCCClassOrFastDefined;
      function getInheritanceChain(constructor) {
        var chain = [];
        for (;;) {
          constructor = getSuper(constructor);
          if (!constructor) {
            break;
          }
          if (constructor !== Object) {
            chain.push(constructor);
          }
        }
        return chain;
      }
      CCClass.getInheritanceChain = getInheritanceChain;
      var PrimitiveTypes = {
        Integer: 'Number',
        Float: 'Number',
        Boolean: 'Boolean',
        String: 'String'
      };
      function parseAttributes(constructor, attributes, className, propertyName, usedInGetter) {
        var attrs = null;
        var propertyNamePrefix = '';
        function initAttrs() {
          propertyNamePrefix = propertyName + DELIMETER;
          return attrs = getClassAttrs(constructor);
        }
        if ('type' in attributes && typeof attributes.type === 'undefined') {
          warnID(3660, propertyName, className);
        }
        var type = attributes.type;
        if (type) {
          var primitiveType = PrimitiveTypes[type];
          if (primitiveType) {
            (attrs || initAttrs())[propertyNamePrefix + "type"] = type;
          } else if (type === 'Object') ; else if (typeof type === 'object') {
            if (Enum.isEnum(type)) {
              setPropertyEnumTypeOnAttrs(attrs || initAttrs(), propertyName, type);
            } else if (BitMask.isBitMask(type)) {
              (attrs || initAttrs())[propertyNamePrefix + "type"] = BITMASK_TAG;
              attrs[propertyNamePrefix + "bitmaskList"] = BitMask.getList(type);
            } else ;
          } else if (typeof type === 'function') {
            (attrs || initAttrs())[propertyNamePrefix + "type"] = 'Object';
            attrs[propertyNamePrefix + "ctor"] = type;
          } else ;
        }
        if ('default' in attributes) {
          (attrs || initAttrs())[propertyNamePrefix + "default"] = attributes["default"];
        }
        var parseSimpleAttribute = function parseSimpleAttribute(attributeName, expectType) {
          if (attributeName in attributes) {
            var val = attributes[attributeName];
            if (typeof val === expectType) {
              (attrs || initAttrs())[propertyNamePrefix + attributeName] = val;
            }
          }
        };
        if (attributes.editorOnly) {
          {
            (attrs || initAttrs())[propertyNamePrefix + "editorOnly"] = true;
          }
        }
        var isStandaloneMode = attributes.__internalFlags & PropertyStashInternalFlag.STANDALONE;
        var normalizedSerializable;
        if (isStandaloneMode) {
          normalizedSerializable = attributes.serializable === true || (attributes.__internalFlags & PropertyStashInternalFlag.IMPLICIT_SERIALIZABLE) !== 0;
        } else if (attributes.serializable === false) {
          normalizedSerializable = false;
        }
        if (typeof normalizedSerializable !== 'undefined') {
          (attrs || initAttrs())[propertyNamePrefix + "serializable"] = normalizedSerializable;
        }
        parseSimpleAttribute('formerlySerializedAs', 'string');
        var range = attributes.range;
        if (range) {
          if (Array.isArray(range)) {
            if (range.length >= 2) {
              (attrs || initAttrs())[propertyNamePrefix + "min"] = range[0];
              attrs[propertyNamePrefix + "max"] = range[1];
              if (range.length > 2) {
                attrs[propertyNamePrefix + "step"] = range[2];
              }
            }
          }
        }
        parseSimpleAttribute('min', 'number');
        parseSimpleAttribute('max', 'number');
        parseSimpleAttribute('step', 'number');
      }
      CCClass.isArray = function (defaultVal) {
        defaultVal = getDefault(defaultVal);
        return Array.isArray(defaultVal);
      };
      CCClass.getDefault = getDefault;
      CCClass.escapeForJS = escapeForJS$1;
      CCClass.IDENTIFIER_RE = IDENTIFIER_RE$1;
      CCClass.getNewValueTypeCode = getNewValueTypeCodeJit;
      legacyCC.Class = CCClass;

      var _d2r = Math.PI / 180.0;
      var _r2d = 180.0 / Math.PI;
      var _random = Math.random;
      var HALF_PI = exports('aZ', Math.PI * 0.5);
      var TWO_PI = exports('a_', Math.PI * 2.0);
      var EPSILON$3 = exports('a$', 0.000001);
      function equals$1(a, b) {
        return Math.abs(a - b) <= EPSILON$3 * Math.max(1.0, Math.abs(a), Math.abs(b));
      }
      function approx(a, b, maxDiff) {
        maxDiff = maxDiff || EPSILON$3;
        return Math.abs(a - b) <= maxDiff;
      }
      function clamp$1(val, min, max) {
        if (min > max) {
          var temp = min;
          min = max;
          max = temp;
        }
        return val < min ? min : val > max ? max : val;
      }
      function clamp01(val) {
        return val < 0 ? 0 : val > 1 ? 1 : val;
      }
      function lerp(from, to, ratio) {
        return from + (to - from) * ratio;
      }
      function toRadian(a) {
        return a * _d2r;
      }
      function toDegree(a) {
        return a * _r2d;
      }
      function random() {
        return _random();
      }
      function setRandGenerator(func) {
        _random = func;
      }
      function randomRange(min, max) {
        return random() * (max - min) + min;
      }
      function randomRangeInt(min, max) {
        return Math.floor(randomRange(min, max));
      }
      function pseudoRandom(seed) {
        seed = (seed * 9301 + 49297) % 233280;
        return seed / 233280.0;
      }
      function pseudoRandomRange(seed, min, max) {
        return pseudoRandom(seed) * (max - min) + min;
      }
      function pseudoRandomRangeInt(seed, min, max) {
        return Math.floor(pseudoRandomRange(seed, min, max));
      }
      function nextPow2(val) {
        return nextPow2$1(val);
      }
      function repeat$2(t, length) {
        return t - Math.floor(t / length) * length;
      }
      function pingPong(t, length) {
        t = repeat$2(t, length * 2);
        t = length - Math.abs(t - length);
        return t;
      }
      function inverseLerp(from, to, value) {
        return (value - from) / (to - from);
      }
      function absMaxComponent(v) {
        if (Math.abs(v.x) > Math.abs(v.y)) {
          if (Math.abs(v.x) > Math.abs(v.z)) {
            return v.x;
          } else {
            return v.z;
          }
        } else if (Math.abs(v.y) > Math.abs(v.z)) {
          return v.y;
        } else {
          return v.z;
        }
      }
      function absMax(a, b) {
        if (Math.abs(a) > Math.abs(b)) {
          return a;
        } else {
          return b;
        }
      }
      function enumerableProps(prototype, attrs) {
        attrs.forEach(function (key) {
          Object.defineProperty(prototype, key, {
            enumerable: true
          });
        });
      }
      var toHalf = function () {
        var floatView = new Float32Array(1);
        var int32View = new Int32Array(floatView.buffer);
        return function toHalf(fval) {
          floatView[0] = fval;
          var fbits = int32View[0];
          var s = fbits >> 16 & 0x8000;
          var em = fbits & 0x7fffffff;
          var h = em - (112 << 23) + (1 << 12) >> 13;
          h = em < 113 << 23 ? 0 : h;
          h = em >= 143 << 23 ? 0x7c00 : h;
          h = em > 255 << 23 ? 0x7e00 : h;
          int32View[0] = s | h;
          return int32View[0];
        };
      }();
      var fromHalf = function () {
        var floatView = new Float32Array(1);
        var int32View = new Int32Array(floatView.buffer);
        return function fromHalf(hval) {
          var s = hval >> 15 & 0x00000001;
          var em = hval & 0x00007fff;
          var h = em << 13;
          var fbits = 0;
          if (h !== 0x7c00) {
            h += 112 << 23;
            if (em === 0) {
              h = (h & 0xfffff) >> 1;
            } else if (em === 0x7fff) {
              h = 0x7fffffff;
            }
          } else {
            h = 0x7f800000;
          }
          fbits = s << 31 | h;
          int32View[0] = fbits;
          return floatView[0];
        };
      }();
      function floatToHalf(val) {
        return toHalf(val);
      }
      function halfToFloat(val) {
        return fromHalf(val);
      }

      var _class$3a;
      var Vec3 = exports('aI', function (_ValueType) {
        _inheritsLoose(Vec3, _ValueType);
        Vec3.zero = function zero(out) {
          out.x = 0;
          out.y = 0;
          out.z = 0;
          return out;
        };
        Vec3.clone = function clone(a) {
          return new Vec3(a.x, a.y, a.z);
        };
        Vec3.copy = function copy(out, a) {
          out.x = a.x;
          out.y = a.y;
          out.z = a.z;
          return out;
        };
        Vec3.set = function set(out, x, y, z) {
          out.x = x;
          out.y = y;
          out.z = z;
          return out;
        };
        Vec3.add = function add(out, a, b) {
          out.x = a.x + b.x;
          out.y = a.y + b.y;
          out.z = a.z + b.z;
          return out;
        };
        Vec3.subtract = function subtract(out, a, b) {
          out.x = a.x - b.x;
          out.y = a.y - b.y;
          out.z = a.z - b.z;
          return out;
        };
        Vec3.multiply = function multiply(out, a, b) {
          out.x = a.x * b.x;
          out.y = a.y * b.y;
          out.z = a.z * b.z;
          return out;
        };
        Vec3.divide = function divide(out, a, b) {
          out.x = a.x / b.x;
          out.y = a.y / b.y;
          out.z = a.z / b.z;
          return out;
        };
        Vec3.ceil = function ceil(out, a) {
          out.x = Math.ceil(a.x);
          out.y = Math.ceil(a.y);
          out.z = Math.ceil(a.z);
          return out;
        };
        Vec3.floor = function floor(out, a) {
          out.x = Math.floor(a.x);
          out.y = Math.floor(a.y);
          out.z = Math.floor(a.z);
          return out;
        };
        Vec3.min = function min(out, a, b) {
          out.x = Math.min(a.x, b.x);
          out.y = Math.min(a.y, b.y);
          out.z = Math.min(a.z, b.z);
          return out;
        };
        Vec3.max = function max(out, a, b) {
          out.x = Math.max(a.x, b.x);
          out.y = Math.max(a.y, b.y);
          out.z = Math.max(a.z, b.z);
          return out;
        };
        Vec3.round = function round(out, a) {
          out.x = Math.round(a.x);
          out.y = Math.round(a.y);
          out.z = Math.round(a.z);
          return out;
        };
        Vec3.multiplyScalar = function multiplyScalar(out, a, b) {
          out.x = a.x * b;
          out.y = a.y * b;
          out.z = a.z * b;
          return out;
        };
        Vec3.scaleAndAdd = function scaleAndAdd(out, a, b, scale) {
          out.x = a.x + b.x * scale;
          out.y = a.y + b.y * scale;
          out.z = a.z + b.z * scale;
          return out;
        };
        Vec3.distance = function distance(a, b) {
          var x = b.x - a.x;
          var y = b.y - a.y;
          var z = b.z - a.z;
          return Math.sqrt(x * x + y * y + z * z);
        };
        Vec3.squaredDistance = function squaredDistance(a, b) {
          var x = b.x - a.x;
          var y = b.y - a.y;
          var z = b.z - a.z;
          return x * x + y * y + z * z;
        };
        Vec3.len = function len(a) {
          var x = a.x;
          var y = a.y;
          var z = a.z;
          return Math.sqrt(x * x + y * y + z * z);
        };
        Vec3.lengthSqr = function lengthSqr(a) {
          var x = a.x;
          var y = a.y;
          var z = a.z;
          return x * x + y * y + z * z;
        };
        Vec3.negate = function negate(out, a) {
          out.x = -a.x;
          out.y = -a.y;
          out.z = -a.z;
          return out;
        };
        Vec3.invert = function invert(out, a) {
          out.x = 1.0 / a.x;
          out.y = 1.0 / a.y;
          out.z = 1.0 / a.z;
          return out;
        };
        Vec3.invertSafe = function invertSafe(out, a) {
          var x = a.x;
          var y = a.y;
          var z = a.z;
          if (Math.abs(x) < EPSILON$3) {
            out.x = 0;
          } else {
            out.x = 1.0 / x;
          }
          if (Math.abs(y) < EPSILON$3) {
            out.y = 0;
          } else {
            out.y = 1.0 / y;
          }
          if (Math.abs(z) < EPSILON$3) {
            out.z = 0;
          } else {
            out.z = 1.0 / z;
          }
          return out;
        };
        Vec3.normalize = function normalize(out, a) {
          var x = a.x;
          var y = a.y;
          var z = a.z;
          var len = x * x + y * y + z * z;
          if (len > 0) {
            len = 1 / Math.sqrt(len);
            out.x = x * len;
            out.y = y * len;
            out.z = z * len;
          } else {
            out.x = 0;
            out.y = 0;
            out.z = 0;
          }
          return out;
        };
        Vec3.dot = function dot(a, b) {
          return a.x * b.x + a.y * b.y + a.z * b.z;
        };
        Vec3.cross = function cross(out, a, b) {
          var ax = a.x,
            ay = a.y,
            az = a.z;
          var bx = b.x,
            by = b.y,
            bz = b.z;
          out.x = ay * bz - az * by;
          out.y = az * bx - ax * bz;
          out.z = ax * by - ay * bx;
          return out;
        };
        Vec3.lerp = function lerp(out, a, b, t) {
          out.x = a.x + t * (b.x - a.x);
          out.y = a.y + t * (b.y - a.y);
          out.z = a.z + t * (b.z - a.z);
          return out;
        };
        Vec3.random = function random$1(out, scale) {
          scale = scale || 1.0;
          var phi = random() * 2.0 * Math.PI;
          var cosTheta = random() * 2 - 1;
          var sinTheta = Math.sqrt(1 - cosTheta * cosTheta);
          out.x = sinTheta * Math.cos(phi) * scale;
          out.y = sinTheta * Math.sin(phi) * scale;
          out.z = cosTheta * scale;
          return out;
        };
        Vec3.transformMat4 = function transformMat4(out, a, m) {
          var x = a.x;
          var y = a.y;
          var z = a.z;
          var rhw = m.m03 * x + m.m07 * y + m.m11 * z + m.m15;
          rhw = rhw ? 1 / rhw : 1;
          out.x = (m.m00 * x + m.m04 * y + m.m08 * z + m.m12) * rhw;
          out.y = (m.m01 * x + m.m05 * y + m.m09 * z + m.m13) * rhw;
          out.z = (m.m02 * x + m.m06 * y + m.m10 * z + m.m14) * rhw;
          return out;
        };
        Vec3.transformMat4Normal = function transformMat4Normal(out, a, m) {
          var x = a.x;
          var y = a.y;
          var z = a.z;
          var rhw = m.m03 * x + m.m07 * y + m.m11 * z;
          rhw = rhw ? 1 / rhw : 1;
          out.x = (m.m00 * x + m.m04 * y + m.m08 * z) * rhw;
          out.y = (m.m01 * x + m.m05 * y + m.m09 * z) * rhw;
          out.z = (m.m02 * x + m.m06 * y + m.m10 * z) * rhw;
          return out;
        };
        Vec3.transformMat3 = function transformMat3(out, a, m) {
          var x = a.x;
          var y = a.y;
          var z = a.z;
          out.x = x * m.m00 + y * m.m03 + z * m.m06;
          out.y = x * m.m01 + y * m.m04 + z * m.m07;
          out.z = x * m.m02 + y * m.m05 + z * m.m08;
          return out;
        };
        Vec3.transformAffine = function transformAffine(out, v, m) {
          var x = v.x;
          var y = v.y;
          var z = v.z;
          out.x = m.m00 * x + m.m04 * y + m.m08 * z + m.m12;
          out.y = m.m01 * x + m.m05 * y + m.m09 * z + m.m13;
          out.z = m.m02 * x + m.m06 * y + m.m10 * z + m.m14;
          return out;
        };
        Vec3.transformQuat = function transformQuat(out, a, q) {
          var ix = q.w * a.x + q.y * a.z - q.z * a.y;
          var iy = q.w * a.y + q.z * a.x - q.x * a.z;
          var iz = q.w * a.z + q.x * a.y - q.y * a.x;
          var iw = -q.x * a.x - q.y * a.y - q.z * a.z;
          out.x = ix * q.w + iw * -q.x + iy * -q.z - iz * -q.y;
          out.y = iy * q.w + iw * -q.y + iz * -q.x - ix * -q.z;
          out.z = iz * q.w + iw * -q.z + ix * -q.y - iy * -q.x;
          return out;
        };
        Vec3.transformRTS = function transformRTS(out, a, r, t, s) {
          var x = a.x * s.x;
          var y = a.y * s.y;
          var z = a.z * s.z;
          var ix = r.w * x + r.y * z - r.z * y;
          var iy = r.w * y + r.z * x - r.x * z;
          var iz = r.w * z + r.x * y - r.y * x;
          var iw = -r.x * x - r.y * y - r.z * z;
          out.x = ix * r.w + iw * -r.x + iy * -r.z - iz * -r.y + t.x;
          out.y = iy * r.w + iw * -r.y + iz * -r.x - ix * -r.z + t.y;
          out.z = iz * r.w + iw * -r.z + ix * -r.y - iy * -r.x + t.z;
          return out;
        };
        Vec3.transformInverseRTS = function transformInverseRTS(out, a, r, t, s) {
          var x = a.x - t.x;
          var y = a.y - t.y;
          var z = a.z - t.z;
          var ix = r.w * x - r.y * z + r.z * y;
          var iy = r.w * y - r.z * x + r.x * z;
          var iz = r.w * z - r.x * y + r.y * x;
          var iw = r.x * x + r.y * y + r.z * z;
          out.x = (ix * r.w + iw * r.x + iy * r.z - iz * r.y) / s.x;
          out.y = (iy * r.w + iw * r.y + iz * r.x - ix * r.z) / s.y;
          out.z = (iz * r.w + iw * r.z + ix * r.y - iy * r.x) / s.z;
          return out;
        };
        Vec3.rotateX = function rotateX(out, v, o, a) {
          var x = v.x - o.x;
          var y = v.y - o.y;
          var z = v.z - o.z;
          var cos = Math.cos(a);
          var sin = Math.sin(a);
          var rx = x;
          var ry = y * cos - z * sin;
          var rz = y * sin + z * cos;
          out.x = rx + o.x;
          out.y = ry + o.y;
          out.z = rz + o.z;
          return out;
        };
        Vec3.rotateY = function rotateY(out, v, o, a) {
          var x = v.x - o.x;
          var y = v.y - o.y;
          var z = v.z - o.z;
          var cos = Math.cos(a);
          var sin = Math.sin(a);
          var rx = z * sin + x * cos;
          var ry = y;
          var rz = z * cos - x * sin;
          out.x = rx + o.x;
          out.y = ry + o.y;
          out.z = rz + o.z;
          return out;
        };
        Vec3.rotateZ = function rotateZ(out, v, o, a) {
          var x = v.x - o.x;
          var y = v.y - o.y;
          var z = v.z - o.z;
          var cos = Math.cos(a);
          var sin = Math.sin(a);
          var rx = x * cos - y * sin;
          var ry = x * sin + y * cos;
          var rz = z;
          out.x = rx + o.x;
          out.y = ry + o.y;
          out.z = rz + o.z;
          return out;
        };
        Vec3.rotateN = function rotateN(out, v, o, n, a) {
          var x = v.x - o.x;
          var y = v.y - o.y;
          var z = v.z - o.z;
          var nx = n.x;
          var ny = n.y;
          var nz = n.z;
          var cos = Math.cos(a);
          var sin = Math.sin(a);
          var rx = x * (nx * nx * (1.0 - cos) + cos) + y * (nx * ny * (1.0 - cos) - nx * sin) + z * (nx * nz * (1.0 - cos) + ny * sin);
          var ry = x * (nx * ny * (1.0 - cos) + nz * sin) + y * (ny * ny * (1.0 - cos) + cos) + z * (ny * nz * (1.0 - cos) - nx * sin);
          var rz = x * (nx * nz * (1.0 - cos) - ny * sin) + y * (ny * nz * (1.0 - cos) + nx * sin) + z * (nz * nz * (1.0 - cos) + cos);
          out.x = rx + o.x;
          out.y = ry + o.y;
          out.z = rz + o.z;
          return out;
        };
        Vec3.toArray = function toArray(out, v, ofs) {
          if (ofs === void 0) {
            ofs = 0;
          }
          out[ofs + 0] = v.x;
          out[ofs + 1] = v.y;
          out[ofs + 2] = v.z;
          return out;
        };
        Vec3.fromArray = function fromArray(out, arr, ofs) {
          if (ofs === void 0) {
            ofs = 0;
          }
          out.x = arr[ofs + 0];
          out.y = arr[ofs + 1];
          out.z = arr[ofs + 2];
          return out;
        };
        Vec3.strictEquals = function strictEquals(a, b) {
          return a.x === b.x && a.y === b.y && a.z === b.z;
        };
        Vec3.equals = function equals(a, b, epsilon) {
          if (epsilon === void 0) {
            epsilon = EPSILON$3;
          }
          var a0 = a.x,
            a1 = a.y,
            a2 = a.z;
          var b0 = b.x,
            b1 = b.y,
            b2 = b.z;
          return Math.abs(a0 - b0) <= epsilon * Math.max(1.0, Math.abs(a0), Math.abs(b0)) && Math.abs(a1 - b1) <= epsilon * Math.max(1.0, Math.abs(a1), Math.abs(b1)) && Math.abs(a2 - b2) <= epsilon * Math.max(1.0, Math.abs(a2), Math.abs(b2));
        };
        Vec3.angle = function angle(a, b) {
          var magSqr1 = a.x * a.x + a.y * a.y + a.z * a.z;
          var magSqr2 = b.x * b.x + b.y * b.y + b.z * b.z;
          if (magSqr1 === 0 || magSqr2 === 0) {
            return 0.0;
          }
          var dot = a.x * b.x + a.y * b.y + a.z * b.z;
          var cosine = dot / Math.sqrt(magSqr1 * magSqr2);
          cosine = clamp$1(cosine, -1.0, 1.0);
          return Math.acos(cosine);
        };
        Vec3.projectOnPlane = function projectOnPlane(out, a, n) {
          return Vec3.subtract(out, a, Vec3.project(out, a, n));
        };
        Vec3.project = function project(out, a, b) {
          var sqrLen = Vec3.lengthSqr(b);
          if (sqrLen < 0.000001) {
            return Vec3.set(out, 0, 0, 0);
          } else {
            return Vec3.multiplyScalar(out, b, Vec3.dot(a, b) / sqrLen);
          }
        };
        Vec3.moveTowards = function moveTowards(out, current, target, maxStep) {
          var deltaX = target.x - current.x;
          var deltaY = target.y - current.y;
          var deltaZ = target.z - current.z;
          var distanceSqr = deltaX * deltaX + deltaY * deltaY + deltaZ * deltaZ;
          if (distanceSqr === 0 || maxStep >= 0 && distanceSqr < maxStep * maxStep) {
            out.x = target.x;
            out.y = target.y;
            out.z = target.z;
            return out;
          }
          var distance = Math.sqrt(distanceSqr);
          var scale = maxStep / distance;
          out.x = current.x + deltaX * scale;
          out.y = current.y + deltaY * scale;
          out.z = current.z + deltaZ * scale;
          return out;
        };
        Vec3.generateOrthogonal = function generateOrthogonal(out, n) {
          var x = n.x,
            y = n.y,
            z = n.z;
          var absX = Math.abs(x);
          var absY = Math.abs(y);
          var absZ = Math.abs(z);
          if (absX < absY && absX < absZ) {
            Vec3.set(out, 0.0, z, -y);
          } else if (absY < absZ) {
            Vec3.set(out, z, 0.0, -x);
          } else {
            Vec3.set(out, y, -x, 0.0);
          }
          return Vec3.normalize(out, out);
        };
        function Vec3(x, y, z) {
          var _this;
          _this = _ValueType.call(this) || this;
          if (typeof x === 'object') {
            _this.x = x.x;
            _this.y = x.y;
            _this.z = x.z;
          } else {
            _this.x = x || 0;
            _this.y = y || 0;
            _this.z = z || 0;
          }
          return _this;
        }
        var _proto = Vec3.prototype;
        _proto.clone = function clone() {
          return new Vec3(this.x, this.y, this.z);
        };
        _proto.set = function set(x, y, z) {
          if (typeof x === 'object') {
            this.x = x.x;
            this.y = x.y;
            this.z = x.z;
          } else {
            this.x = x || 0;
            this.y = y || 0;
            this.z = z || 0;
          }
          return this;
        };
        _proto.equals = function equals(other, epsilon) {
          if (epsilon === void 0) {
            epsilon = EPSILON$3;
          }
          return Math.abs(this.x - other.x) <= epsilon && Math.abs(this.y - other.y) <= epsilon && Math.abs(this.z - other.z) <= epsilon;
        };
        _proto.equals3f = function equals3f(x, y, z, epsilon) {
          if (epsilon === void 0) {
            epsilon = EPSILON$3;
          }
          return Math.abs(this.x - x) <= epsilon && Math.abs(this.y - y) <= epsilon && Math.abs(this.z - z) <= epsilon;
        };
        _proto.strictEquals = function strictEquals(other) {
          return this.x === other.x && this.y === other.y && this.z === other.z;
        };
        _proto.strictEquals3f = function strictEquals3f(x, y, z) {
          return this.x === x && this.y === y && this.z === z;
        };
        _proto.toString = function toString() {
          return "(" + this.x.toFixed(2) + ", " + this.y.toFixed(2) + ", " + this.z.toFixed(2) + ")";
        };
        _proto.lerp = function lerp(to, ratio) {
          this.x += ratio * (to.x - this.x);
          this.y += ratio * (to.y - this.y);
          this.z += ratio * (to.z - this.z);
          return this;
        };
        _proto.add = function add(other) {
          this.x += other.x;
          this.y += other.y;
          this.z += other.z;
          return this;
        };
        _proto.add3f = function add3f(x, y, z) {
          this.x += x;
          this.y += y;
          this.z += z;
          return this;
        };
        _proto.subtract = function subtract(other) {
          this.x -= other.x;
          this.y -= other.y;
          this.z -= other.z;
          return this;
        };
        _proto.subtract3f = function subtract3f(x, y, z) {
          this.x -= x;
          this.y -= y;
          this.z -= z;
          return this;
        };
        _proto.multiplyScalar = function multiplyScalar(scalar) {
          if (typeof scalar === 'object') {
            console.warn('should use Vec3.multiply for vector * vector operation');
          }
          this.x *= scalar;
          this.y *= scalar;
          this.z *= scalar;
          return this;
        };
        _proto.multiply = function multiply(other) {
          if (typeof other !== 'object') {
            console.warn('should use Vec3.scale for vector * scalar operation');
          }
          this.x *= other.x;
          this.y *= other.y;
          this.z *= other.z;
          return this;
        };
        _proto.multiply3f = function multiply3f(x, y, z) {
          this.x *= x;
          this.y *= y;
          this.z *= z;
          return this;
        };
        _proto.divide = function divide(other) {
          this.x /= other.x;
          this.y /= other.y;
          this.z /= other.z;
          return this;
        };
        _proto.divide3f = function divide3f(x, y, z) {
          this.x /= x;
          this.y /= y;
          this.z /= z;
          return this;
        };
        _proto.negative = function negative() {
          this.x = -this.x;
          this.y = -this.y;
          this.z = -this.z;
          return this;
        };
        _proto.clampf = function clampf(minInclusive, maxInclusive) {
          this.x = clamp$1(this.x, minInclusive.x, maxInclusive.x);
          this.y = clamp$1(this.y, minInclusive.y, maxInclusive.y);
          this.z = clamp$1(this.z, minInclusive.z, maxInclusive.z);
          return this;
        };
        _proto.dot = function dot(other) {
          return this.x * other.x + this.y * other.y + this.z * other.z;
        };
        _proto.cross = function cross(other) {
          var ax = this.x,
            ay = this.y,
            az = this.z;
          var bx = other.x,
            by = other.y,
            bz = other.z;
          this.x = ay * bz - az * by;
          this.y = az * bx - ax * bz;
          this.z = ax * by - ay * bx;
          return this;
        };
        _proto.length = function length() {
          return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
        };
        _proto.lengthSqr = function lengthSqr() {
          return this.x * this.x + this.y * this.y + this.z * this.z;
        };
        _proto.normalize = function normalize() {
          var x = this.x;
          var y = this.y;
          var z = this.z;
          var len = x * x + y * y + z * z;
          if (len > 0) {
            len = 1 / Math.sqrt(len);
            this.x = x * len;
            this.y = y * len;
            this.z = z * len;
          }
          return this;
        };
        _proto.transformMat4 = function transformMat4(matrix) {
          var x = this.x;
          var y = this.y;
          var z = this.z;
          var rhw = matrix.m03 * x + matrix.m07 * y + matrix.m11 * z + matrix.m15;
          rhw = rhw ? 1 / rhw : 1;
          this.x = (matrix.m00 * x + matrix.m04 * y + matrix.m08 * z + matrix.m12) * rhw;
          this.y = (matrix.m01 * x + matrix.m05 * y + matrix.m09 * z + matrix.m13) * rhw;
          this.z = (matrix.m02 * x + matrix.m06 * y + matrix.m10 * z + matrix.m14) * rhw;
          return this;
        };
        return Vec3;
      }(ValueType));
      _class$3a = Vec3;
      Vec3.UNIT_X = Object.freeze(new _class$3a(1, 0, 0));
      Vec3.UNIT_Y = Object.freeze(new _class$3a(0, 1, 0));
      Vec3.UNIT_Z = Object.freeze(new _class$3a(0, 0, 1));
      Vec3.RIGHT = Object.freeze(new _class$3a(1, 0, 0));
      Vec3.UP = Object.freeze(new _class$3a(0, 1, 0));
      Vec3.FORWARD = Object.freeze(new _class$3a(0, 0, -1));
      Vec3.ZERO = Object.freeze(new _class$3a(0, 0, 0));
      Vec3.ONE = Object.freeze(new _class$3a(1, 1, 1));
      Vec3.NEG_ONE = Object.freeze(new _class$3a(-1, -1, -1));
      Vec3.slerp = function () {
        var cacheV1 = new _class$3a();
        var cacheV2 = new _class$3a();
        var cacheV3 = new _class$3a();
        return function (out, from, to, t) {
          var EPSILON = 1e-5;
          var lenFrom = _class$3a.len(from);
          var lenTo = _class$3a.len(to);
          if (lenFrom < EPSILON || lenTo < EPSILON) {
            return _class$3a.lerp(out, from, to, t);
          }
          var lenLerped = lerp(lenFrom, lenTo, t);
          var dot = _class$3a.dot(from, to) / (lenFrom * lenTo);
          if (dot > 1.0 - EPSILON) {
            return _class$3a.lerp(out, from, to, t);
          } else if (dot < -1.0 + EPSILON) {
            var fromNormalized = _class$3a.multiplyScalar(cacheV1, from, 1.0 / lenFrom);
            var _axis = _class$3a.generateOrthogonal(cacheV2, fromNormalized);
            var _angle = Math.PI * t;
            rotateAxisAngle(cacheV3, fromNormalized, _axis, _angle);
            _class$3a.multiplyScalar(out, cacheV3, lenLerped);
            return out;
          } else {
            var dotClamped = dot;
            var theta = Math.acos(dotClamped) * t;
            var _fromNormalized = _class$3a.multiplyScalar(cacheV1, from, 1.0 / lenFrom);
            var toNormalized = _class$3a.multiplyScalar(cacheV2, to, 1.0 / lenTo);
            _class$3a.scaleAndAdd(cacheV3, toNormalized, _fromNormalized, -dotClamped);
            _class$3a.normalize(cacheV3, cacheV3);
            _class$3a.multiplyScalar(cacheV3, cacheV3, Math.sin(theta));
            _class$3a.scaleAndAdd(cacheV3, cacheV3, _fromNormalized, Math.cos(theta));
            _class$3a.multiplyScalar(out, cacheV3, lenLerped);
            return out;
          }
        };
      }();
      CCClass.fastDefine('cc.Vec3', Vec3, {
        x: 0,
        y: 0,
        z: 0
      });
      legacyCC.Vec3 = Vec3;
      function v3(x, y, z) {
        return new Vec3(x, y, z);
      }
      var rotateAxisAngle = function () {
        var cacheQ = {
          x: 0.0,
          y: 0.0,
          z: 0.0,
          w: 0.0
        };
        return function (out, input, axis, angle) {
          var rad = angle * 0.5;
          var s = Math.sin(rad);
          cacheQ.x = s * axis.x;
          cacheQ.y = s * axis.y;
          cacheQ.z = s * axis.z;
          cacheQ.w = Math.cos(rad);
          Vec3.transformQuat(out, input, cacheQ);
          return out;
        };
      }();
      legacyCC.v3 = v3;

      var _class$39;
      var Mat3 = exports('aO', function (_ValueType) {
        _inheritsLoose(Mat3, _ValueType);
        Mat3.clone = function clone(a) {
          return new Mat3(a.m00, a.m01, a.m02, a.m03, a.m04, a.m05, a.m06, a.m07, a.m08);
        };
        Mat3.copy = function copy(out, a) {
          out.m00 = a.m00;
          out.m01 = a.m01;
          out.m02 = a.m02;
          out.m03 = a.m03;
          out.m04 = a.m04;
          out.m05 = a.m05;
          out.m06 = a.m06;
          out.m07 = a.m07;
          out.m08 = a.m08;
          return out;
        };
        Mat3.set = function set(out, m00, m01, m02, m03, m04, m05, m06, m07, m08) {
          out.m00 = m00;
          out.m01 = m01;
          out.m02 = m02;
          out.m03 = m03;
          out.m04 = m04;
          out.m05 = m05;
          out.m06 = m06;
          out.m07 = m07;
          out.m08 = m08;
          return out;
        };
        Mat3.identity = function identity(out) {
          out.m00 = 1;
          out.m01 = 0;
          out.m02 = 0;
          out.m03 = 0;
          out.m04 = 1;
          out.m05 = 0;
          out.m06 = 0;
          out.m07 = 0;
          out.m08 = 1;
          return out;
        };
        Mat3.transpose = function transpose(out, a) {
          if (out === a) {
            var a01 = a.m01;
            var a02 = a.m02;
            var a12 = a.m05;
            out.m01 = a.m03;
            out.m02 = a.m06;
            out.m03 = a01;
            out.m05 = a.m07;
            out.m06 = a02;
            out.m07 = a12;
          } else {
            out.m00 = a.m00;
            out.m01 = a.m03;
            out.m02 = a.m06;
            out.m03 = a.m01;
            out.m04 = a.m04;
            out.m05 = a.m07;
            out.m06 = a.m02;
            out.m07 = a.m05;
            out.m08 = a.m08;
          }
          return out;
        };
        Mat3.invert = function invert(out, a) {
          var a00 = a.m00;
          var a01 = a.m01;
          var a02 = a.m02;
          var a10 = a.m03;
          var a11 = a.m04;
          var a12 = a.m05;
          var a20 = a.m06;
          var a21 = a.m07;
          var a22 = a.m08;
          var b01 = a22 * a11 - a12 * a21;
          var b11 = -a22 * a10 + a12 * a20;
          var b21 = a21 * a10 - a11 * a20;
          var det = a00 * b01 + a01 * b11 + a02 * b21;
          if (det === 0) {
            out.m00 = 0;
            out.m01 = 0;
            out.m02 = 0;
            out.m03 = 0;
            out.m04 = 0;
            out.m05 = 0;
            out.m06 = 0;
            out.m07 = 0;
            out.m08 = 0;
            return out;
          }
          det = 1.0 / det;
          out.m00 = b01 * det;
          out.m01 = (-a22 * a01 + a02 * a21) * det;
          out.m02 = (a12 * a01 - a02 * a11) * det;
          out.m03 = b11 * det;
          out.m04 = (a22 * a00 - a02 * a20) * det;
          out.m05 = (-a12 * a00 + a02 * a10) * det;
          out.m06 = b21 * det;
          out.m07 = (-a21 * a00 + a01 * a20) * det;
          out.m08 = (a11 * a00 - a01 * a10) * det;
          return out;
        };
        Mat3.determinant = function determinant(a) {
          var a00 = a.m00;
          var a01 = a.m01;
          var a02 = a.m02;
          var a10 = a.m03;
          var a11 = a.m04;
          var a12 = a.m05;
          var a20 = a.m06;
          var a21 = a.m07;
          var a22 = a.m08;
          return a00 * (a22 * a11 - a12 * a21) + a01 * (-a22 * a10 + a12 * a20) + a02 * (a21 * a10 - a11 * a20);
        };
        Mat3.multiply = function multiply(out, a, b) {
          var a00 = a.m00;
          var a01 = a.m01;
          var a02 = a.m02;
          var a10 = a.m03;
          var a11 = a.m04;
          var a12 = a.m05;
          var a20 = a.m06;
          var a21 = a.m07;
          var a22 = a.m08;
          var b00 = b.m00;
          var b01 = b.m01;
          var b02 = b.m02;
          var b10 = b.m03;
          var b11 = b.m04;
          var b12 = b.m05;
          var b20 = b.m06;
          var b21 = b.m07;
          var b22 = b.m08;
          out.m00 = b00 * a00 + b01 * a10 + b02 * a20;
          out.m01 = b00 * a01 + b01 * a11 + b02 * a21;
          out.m02 = b00 * a02 + b01 * a12 + b02 * a22;
          out.m03 = b10 * a00 + b11 * a10 + b12 * a20;
          out.m04 = b10 * a01 + b11 * a11 + b12 * a21;
          out.m05 = b10 * a02 + b11 * a12 + b12 * a22;
          out.m06 = b20 * a00 + b21 * a10 + b22 * a20;
          out.m07 = b20 * a01 + b21 * a11 + b22 * a21;
          out.m08 = b20 * a02 + b21 * a12 + b22 * a22;
          return out;
        };
        Mat3.multiplyMat4 = function multiplyMat4(out, a, b) {
          var a00 = a.m00;
          var a01 = a.m01;
          var a02 = a.m02;
          var a10 = a.m03;
          var a11 = a.m04;
          var a12 = a.m05;
          var a20 = a.m06;
          var a21 = a.m07;
          var a22 = a.m08;
          var b00 = b.m00;
          var b01 = b.m01;
          var b02 = b.m02;
          var b10 = b.m04;
          var b11 = b.m05;
          var b12 = b.m06;
          var b20 = b.m08;
          var b21 = b.m09;
          var b22 = b.m10;
          out.m00 = b00 * a00 + b01 * a10 + b02 * a20;
          out.m01 = b00 * a01 + b01 * a11 + b02 * a21;
          out.m02 = b00 * a02 + b01 * a12 + b02 * a22;
          out.m03 = b10 * a00 + b11 * a10 + b12 * a20;
          out.m04 = b10 * a01 + b11 * a11 + b12 * a21;
          out.m05 = b10 * a02 + b11 * a12 + b12 * a22;
          out.m06 = b20 * a00 + b21 * a10 + b22 * a20;
          out.m07 = b20 * a01 + b21 * a11 + b22 * a21;
          out.m08 = b20 * a02 + b21 * a12 + b22 * a22;
          return out;
        };
        Mat3.transform = function transform(out, a, v) {
          this.translate(out, a, v);
        };
        Mat3.translate = function translate(out, a, v) {
          var a00 = a.m00;
          var a01 = a.m01;
          var a02 = a.m02;
          var a10 = a.m03;
          var a11 = a.m04;
          var a12 = a.m05;
          var a20 = a.m06;
          var a21 = a.m07;
          var a22 = a.m08;
          var x = v.x;
          var y = v.y;
          out.m00 = a00;
          out.m01 = a01;
          out.m02 = a02;
          out.m03 = a10;
          out.m04 = a11;
          out.m05 = a12;
          out.m06 = x * a00 + y * a10 + a20;
          out.m07 = x * a01 + y * a11 + a21;
          out.m08 = x * a02 + y * a12 + a22;
          return out;
        };
        Mat3.scale = function scale(out, a, v) {
          var x = v.x;
          var y = v.y;
          out.m00 = x * a.m00;
          out.m01 = x * a.m01;
          out.m02 = x * a.m02;
          out.m03 = y * a.m03;
          out.m04 = y * a.m04;
          out.m05 = y * a.m05;
          out.m06 = a.m06;
          out.m07 = a.m07;
          out.m08 = a.m08;
          return out;
        };
        Mat3.rotate = function rotate(out, a, rad) {
          var a00 = a.m00;
          var a01 = a.m01;
          var a02 = a.m02;
          var a10 = a.m03;
          var a11 = a.m04;
          var a12 = a.m05;
          var a20 = a.m06;
          var a21 = a.m07;
          var a22 = a.m08;
          var s = Math.sin(rad);
          var c = Math.cos(rad);
          out.m00 = c * a00 + s * a10;
          out.m01 = c * a01 + s * a11;
          out.m02 = c * a02 + s * a12;
          out.m03 = c * a10 - s * a00;
          out.m04 = c * a11 - s * a01;
          out.m05 = c * a12 - s * a02;
          out.m06 = a20;
          out.m07 = a21;
          out.m08 = a22;
          return out;
        };
        Mat3.fromMat4 = function fromMat4(out, a) {
          out.m00 = a.m00;
          out.m01 = a.m01;
          out.m02 = a.m02;
          out.m03 = a.m04;
          out.m04 = a.m05;
          out.m05 = a.m06;
          out.m06 = a.m08;
          out.m07 = a.m09;
          out.m08 = a.m10;
          return out;
        };
        Mat3.fromViewUp = function fromViewUp(out, view, up) {
          if (Vec3.lengthSqr(view) < EPSILON$3 * EPSILON$3) {
            Mat3.identity(out);
            return out;
          }
          up = up || Vec3.UNIT_Y;
          Vec3.normalize(v3_1$7, Vec3.cross(v3_1$7, up, view));
          if (Vec3.lengthSqr(v3_1$7) < EPSILON$3 * EPSILON$3) {
            Mat3.identity(out);
            return out;
          }
          Vec3.cross(v3_2$2, view, v3_1$7);
          Mat3.set(out, v3_1$7.x, v3_1$7.y, v3_1$7.z, v3_2$2.x, v3_2$2.y, v3_2$2.z, view.x, view.y, view.z);
          return out;
        };
        Mat3.fromTranslation = function fromTranslation(out, v) {
          out.m00 = 1;
          out.m01 = 0;
          out.m02 = 0;
          out.m03 = 0;
          out.m04 = 1;
          out.m05 = 0;
          out.m06 = v.x;
          out.m07 = v.y;
          out.m08 = 1;
          return out;
        };
        Mat3.fromScaling = function fromScaling(out, v) {
          out.m00 = v.x;
          out.m01 = 0;
          out.m02 = 0;
          out.m03 = 0;
          out.m04 = v.y;
          out.m05 = 0;
          out.m06 = 0;
          out.m07 = 0;
          out.m08 = 1;
          return out;
        };
        Mat3.fromRotation = function fromRotation(out, rad) {
          var s = Math.sin(rad);
          var c = Math.cos(rad);
          out.m00 = c;
          out.m01 = s;
          out.m02 = 0;
          out.m03 = -s;
          out.m04 = c;
          out.m05 = 0;
          out.m06 = 0;
          out.m07 = 0;
          out.m08 = 1;
          return out;
        };
        Mat3.fromQuat = function fromQuat(out, q) {
          var x = q.x;
          var y = q.y;
          var z = q.z;
          var w = q.w;
          var x2 = x + x;
          var y2 = y + y;
          var z2 = z + z;
          var xx = x * x2;
          var yx = y * x2;
          var yy = y * y2;
          var zx = z * x2;
          var zy = z * y2;
          var zz = z * z2;
          var wx = w * x2;
          var wy = w * y2;
          var wz = w * z2;
          out.m00 = 1 - yy - zz;
          out.m03 = yx - wz;
          out.m06 = zx + wy;
          out.m01 = yx + wz;
          out.m04 = 1 - xx - zz;
          out.m07 = zy - wx;
          out.m02 = zx - wy;
          out.m05 = zy + wx;
          out.m08 = 1 - xx - yy;
          return out;
        };
        Mat3.inverseTransposeMat4 = function inverseTransposeMat4(out, a) {
          var a00 = a.m00;
          var a01 = a.m01;
          var a02 = a.m02;
          var a03 = a.m03;
          var a10 = a.m04;
          var a11 = a.m05;
          var a12 = a.m06;
          var a13 = a.m07;
          var a20 = a.m08;
          var a21 = a.m09;
          var a22 = a.m10;
          var a23 = a.m11;
          var a30 = a.m12;
          var a31 = a.m13;
          var a32 = a.m14;
          var a33 = a.m15;
          var b00 = a00 * a11 - a01 * a10;
          var b01 = a00 * a12 - a02 * a10;
          var b02 = a00 * a13 - a03 * a10;
          var b03 = a01 * a12 - a02 * a11;
          var b04 = a01 * a13 - a03 * a11;
          var b05 = a02 * a13 - a03 * a12;
          var b06 = a20 * a31 - a21 * a30;
          var b07 = a20 * a32 - a22 * a30;
          var b08 = a20 * a33 - a23 * a30;
          var b09 = a21 * a32 - a22 * a31;
          var b10 = a21 * a33 - a23 * a31;
          var b11 = a22 * a33 - a23 * a32;
          var det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;
          if (!det) {
            return null;
          }
          det = 1.0 / det;
          out.m00 = (a11 * b11 - a12 * b10 + a13 * b09) * det;
          out.m01 = (a12 * b08 - a10 * b11 - a13 * b07) * det;
          out.m02 = (a10 * b10 - a11 * b08 + a13 * b06) * det;
          out.m03 = (a02 * b10 - a01 * b11 - a03 * b09) * det;
          out.m04 = (a00 * b11 - a02 * b08 + a03 * b07) * det;
          out.m05 = (a01 * b08 - a00 * b10 - a03 * b06) * det;
          out.m06 = (a31 * b05 - a32 * b04 + a33 * b03) * det;
          out.m07 = (a32 * b02 - a30 * b05 - a33 * b01) * det;
          out.m08 = (a30 * b04 - a31 * b02 + a33 * b00) * det;
          return out;
        };
        Mat3.toArray = function toArray(out, m, ofs) {
          if (ofs === void 0) {
            ofs = 0;
          }
          out[ofs + 0] = m.m00;
          out[ofs + 1] = m.m01;
          out[ofs + 2] = m.m02;
          out[ofs + 3] = m.m03;
          out[ofs + 4] = m.m04;
          out[ofs + 5] = m.m05;
          out[ofs + 6] = m.m06;
          out[ofs + 7] = m.m07;
          out[ofs + 8] = m.m08;
          return out;
        };
        Mat3.fromArray = function fromArray(out, arr, ofs) {
          if (ofs === void 0) {
            ofs = 0;
          }
          out.m00 = arr[ofs + 0];
          out.m01 = arr[ofs + 1];
          out.m02 = arr[ofs + 2];
          out.m03 = arr[ofs + 3];
          out.m04 = arr[ofs + 4];
          out.m05 = arr[ofs + 5];
          out.m06 = arr[ofs + 6];
          out.m07 = arr[ofs + 7];
          out.m08 = arr[ofs + 8];
          return out;
        };
        Mat3.add = function add(out, a, b) {
          out.m00 = a.m00 + b.m00;
          out.m01 = a.m01 + b.m01;
          out.m02 = a.m02 + b.m02;
          out.m03 = a.m03 + b.m03;
          out.m04 = a.m04 + b.m04;
          out.m05 = a.m05 + b.m05;
          out.m06 = a.m06 + b.m06;
          out.m07 = a.m07 + b.m07;
          out.m08 = a.m08 + b.m08;
          return out;
        };
        Mat3.subtract = function subtract(out, a, b) {
          out.m00 = a.m00 - b.m00;
          out.m01 = a.m01 - b.m01;
          out.m02 = a.m02 - b.m02;
          out.m03 = a.m03 - b.m03;
          out.m04 = a.m04 - b.m04;
          out.m05 = a.m05 - b.m05;
          out.m06 = a.m06 - b.m06;
          out.m07 = a.m07 - b.m07;
          out.m08 = a.m08 - b.m08;
          return out;
        };
        Mat3.multiplyScalar = function multiplyScalar(out, a, b) {
          out.m00 = a.m00 * b;
          out.m01 = a.m01 * b;
          out.m02 = a.m02 * b;
          out.m03 = a.m03 * b;
          out.m04 = a.m04 * b;
          out.m05 = a.m05 * b;
          out.m06 = a.m06 * b;
          out.m07 = a.m07 * b;
          out.m08 = a.m08 * b;
          return out;
        };
        Mat3.multiplyScalarAndAdd = function multiplyScalarAndAdd(out, a, b, scale) {
          out.m00 = b.m00 * scale + a.m00;
          out.m01 = b.m01 * scale + a.m01;
          out.m02 = b.m02 * scale + a.m02;
          out.m03 = b.m03 * scale + a.m03;
          out.m04 = b.m04 * scale + a.m04;
          out.m05 = b.m05 * scale + a.m05;
          out.m06 = b.m06 * scale + a.m06;
          out.m07 = b.m07 * scale + a.m07;
          out.m08 = b.m08 * scale + a.m08;
          return out;
        };
        Mat3.strictEquals = function strictEquals(a, b) {
          return a.m00 === b.m00 && a.m01 === b.m01 && a.m02 === b.m02 && a.m03 === b.m03 && a.m04 === b.m04 && a.m05 === b.m05 && a.m06 === b.m06 && a.m07 === b.m07 && a.m08 === b.m08;
        };
        Mat3.equals = function equals(a, b, epsilon) {
          if (epsilon === void 0) {
            epsilon = EPSILON$3;
          }
          return Math.abs(a.m00 - b.m00) <= epsilon * Math.max(1.0, Math.abs(a.m00), Math.abs(b.m00)) && Math.abs(a.m01 - b.m01) <= epsilon * Math.max(1.0, Math.abs(a.m01), Math.abs(b.m01)) && Math.abs(a.m02 - b.m02) <= epsilon * Math.max(1.0, Math.abs(a.m02), Math.abs(b.m02)) && Math.abs(a.m03 - b.m03) <= epsilon * Math.max(1.0, Math.abs(a.m03), Math.abs(b.m03)) && Math.abs(a.m04 - b.m04) <= epsilon * Math.max(1.0, Math.abs(a.m04), Math.abs(b.m04)) && Math.abs(a.m05 - b.m05) <= epsilon * Math.max(1.0, Math.abs(a.m05), Math.abs(b.m05)) && Math.abs(a.m06 - b.m06) <= epsilon * Math.max(1.0, Math.abs(a.m06), Math.abs(b.m06)) && Math.abs(a.m07 - b.m07) <= epsilon * Math.max(1.0, Math.abs(a.m07), Math.abs(b.m07)) && Math.abs(a.m08 - b.m08) <= epsilon * Math.max(1.0, Math.abs(a.m08), Math.abs(b.m08));
        };
        Mat3.toEuler = function toEuler(matrix, v) {
          var a00 = matrix.m00;
          var a01 = matrix.m01;
          matrix.m02;
          var a10 = matrix.m03;
          var a11 = matrix.m04;
          matrix.m05;
          var a20 = matrix.m06;
          var a21 = matrix.m07;
          var a22 = matrix.m08;
          if (a21 < 0.999) {
            if (a21 > -0.999) {
              v.x = Math.asin(-a21);
              v.y = Math.atan2(a20, a22);
              v.z = Math.atan2(a01, a11);
              return true;
            } else {
              v.x = HALF_PI;
              v.y = Math.atan2(a10, a00);
              v.z = 0.0;
              return false;
            }
          } else {
            v.x = -HALF_PI;
            v.y = Math.atan2(-a10, a00);
            v.z = 0.0;
            return false;
          }
        };
        function Mat3(m00, m01, m02, m03, m04, m05, m06, m07, m08) {
          var _this;
          if (m00 === void 0) {
            m00 = 1;
          }
          if (m01 === void 0) {
            m01 = 0;
          }
          if (m02 === void 0) {
            m02 = 0;
          }
          if (m03 === void 0) {
            m03 = 0;
          }
          if (m04 === void 0) {
            m04 = 1;
          }
          if (m05 === void 0) {
            m05 = 0;
          }
          if (m06 === void 0) {
            m06 = 0;
          }
          if (m07 === void 0) {
            m07 = 0;
          }
          if (m08 === void 0) {
            m08 = 1;
          }
          _this = _ValueType.call(this) || this;
          if (typeof m00 === 'object') {
            _this.m00 = m00.m00;
            _this.m01 = m00.m01;
            _this.m02 = m00.m02;
            _this.m03 = m00.m03;
            _this.m04 = m00.m04;
            _this.m05 = m00.m05;
            _this.m06 = m00.m06;
            _this.m07 = m00.m07;
            _this.m08 = m00.m08;
          } else {
            _this.m00 = m00;
            _this.m01 = m01;
            _this.m02 = m02;
            _this.m03 = m03;
            _this.m04 = m04;
            _this.m05 = m05;
            _this.m06 = m06;
            _this.m07 = m07;
            _this.m08 = m08;
          }
          return _this;
        }
        var _proto = Mat3.prototype;
        _proto.clone = function clone() {
          var t = this;
          return new Mat3(t.m00, t.m01, t.m02, t.m03, t.m04, t.m05, t.m06, t.m07, t.m08);
        };
        _proto.set = function set(m00, m01, m02, m03, m04, m05, m06, m07, m08) {
          if (m00 === void 0) {
            m00 = 1;
          }
          if (m01 === void 0) {
            m01 = 0;
          }
          if (m02 === void 0) {
            m02 = 0;
          }
          if (m03 === void 0) {
            m03 = 0;
          }
          if (m04 === void 0) {
            m04 = 1;
          }
          if (m05 === void 0) {
            m05 = 0;
          }
          if (m06 === void 0) {
            m06 = 0;
          }
          if (m07 === void 0) {
            m07 = 0;
          }
          if (m08 === void 0) {
            m08 = 1;
          }
          if (typeof m00 === 'object') {
            this.m00 = m00.m00;
            this.m01 = m00.m01;
            this.m02 = m00.m02;
            this.m03 = m00.m03;
            this.m04 = m00.m04;
            this.m05 = m00.m05;
            this.m06 = m00.m06;
            this.m07 = m00.m07;
            this.m08 = m00.m08;
          } else {
            this.m00 = m00;
            this.m01 = m01;
            this.m02 = m02;
            this.m03 = m03;
            this.m04 = m04;
            this.m05 = m05;
            this.m06 = m06;
            this.m07 = m07;
            this.m08 = m08;
          }
          return this;
        };
        _proto.equals = function equals(other, epsilon) {
          if (epsilon === void 0) {
            epsilon = EPSILON$3;
          }
          return Math.abs(this.m00 - other.m00) <= epsilon * Math.max(1.0, Math.abs(this.m00), Math.abs(other.m00)) && Math.abs(this.m01 - other.m01) <= epsilon * Math.max(1.0, Math.abs(this.m01), Math.abs(other.m01)) && Math.abs(this.m02 - other.m02) <= epsilon * Math.max(1.0, Math.abs(this.m02), Math.abs(other.m02)) && Math.abs(this.m03 - other.m03) <= epsilon * Math.max(1.0, Math.abs(this.m03), Math.abs(other.m03)) && Math.abs(this.m04 - other.m04) <= epsilon * Math.max(1.0, Math.abs(this.m04), Math.abs(other.m04)) && Math.abs(this.m05 - other.m05) <= epsilon * Math.max(1.0, Math.abs(this.m05), Math.abs(other.m05)) && Math.abs(this.m06 - other.m06) <= epsilon * Math.max(1.0, Math.abs(this.m06), Math.abs(other.m06)) && Math.abs(this.m07 - other.m07) <= epsilon * Math.max(1.0, Math.abs(this.m07), Math.abs(other.m07)) && Math.abs(this.m08 - other.m08) <= epsilon * Math.max(1.0, Math.abs(this.m08), Math.abs(other.m08));
        };
        _proto.strictEquals = function strictEquals(other) {
          return this.m00 === other.m00 && this.m01 === other.m01 && this.m02 === other.m02 && this.m03 === other.m03 && this.m04 === other.m04 && this.m05 === other.m05 && this.m06 === other.m06 && this.m07 === other.m07 && this.m08 === other.m08;
        };
        _proto.toString = function toString() {
          var t = this;
          return "[\n" + t.m00 + ", " + t.m01 + ", " + t.m02 + ",\n" + t.m03 + ",\n" + t.m04 + ", " + t.m05 + ",\n" + t.m06 + ", " + t.m07 + ",\n" + t.m08 + "\n" + "]";
        };
        _proto.identity = function identity() {
          this.m00 = 1;
          this.m01 = 0;
          this.m02 = 0;
          this.m03 = 0;
          this.m04 = 1;
          this.m05 = 0;
          this.m06 = 0;
          this.m07 = 0;
          this.m08 = 1;
          return this;
        };
        _proto.transpose = function transpose() {
          var a01 = this.m01;
          var a02 = this.m02;
          var a12 = this.m05;
          this.m01 = this.m03;
          this.m02 = this.m06;
          this.m03 = a01;
          this.m05 = this.m07;
          this.m06 = a02;
          this.m07 = a12;
          return this;
        };
        _proto.invert = function invert() {
          var a00 = this.m00;
          var a01 = this.m01;
          var a02 = this.m02;
          var a10 = this.m03;
          var a11 = this.m04;
          var a12 = this.m05;
          var a20 = this.m06;
          var a21 = this.m07;
          var a22 = this.m08;
          var b01 = a22 * a11 - a12 * a21;
          var b11 = -a22 * a10 + a12 * a20;
          var b21 = a21 * a10 - a11 * a20;
          var det = a00 * b01 + a01 * b11 + a02 * b21;
          if (det === 0) {
            this.set(0, 0, 0, 0, 0, 0, 0, 0, 0);
            return this;
          }
          det = 1.0 / det;
          this.m00 = b01 * det;
          this.m01 = (-a22 * a01 + a02 * a21) * det;
          this.m02 = (a12 * a01 - a02 * a11) * det;
          this.m03 = b11 * det;
          this.m04 = (a22 * a00 - a02 * a20) * det;
          this.m05 = (-a12 * a00 + a02 * a10) * det;
          this.m06 = b21 * det;
          this.m07 = (-a21 * a00 + a01 * a20) * det;
          this.m08 = (a11 * a00 - a01 * a10) * det;
          return this;
        };
        _proto.determinant = function determinant() {
          var a00 = this.m00;
          var a01 = this.m01;
          var a02 = this.m02;
          var a10 = this.m03;
          var a11 = this.m04;
          var a12 = this.m05;
          var a20 = this.m06;
          var a21 = this.m07;
          var a22 = this.m08;
          return a00 * (a22 * a11 - a12 * a21) + a01 * (-a22 * a10 + a12 * a20) + a02 * (a21 * a10 - a11 * a20);
        };
        _proto.add = function add(mat) {
          this.m00 += mat.m00;
          this.m01 += mat.m01;
          this.m02 += mat.m02;
          this.m03 += mat.m03;
          this.m04 += mat.m04;
          this.m05 += mat.m05;
          this.m06 += mat.m06;
          this.m07 += mat.m07;
          this.m08 += mat.m08;
          return this;
        };
        _proto.subtract = function subtract(mat) {
          this.m00 -= mat.m00;
          this.m01 -= mat.m01;
          this.m02 -= mat.m02;
          this.m03 -= mat.m03;
          this.m04 -= mat.m04;
          this.m05 -= mat.m05;
          this.m06 -= mat.m06;
          this.m07 -= mat.m07;
          this.m08 -= mat.m08;
          return this;
        };
        _proto.multiply = function multiply(mat) {
          var a00 = this.m00;
          var a01 = this.m01;
          var a02 = this.m02;
          var a10 = this.m03;
          var a11 = this.m04;
          var a12 = this.m05;
          var a20 = this.m06;
          var a21 = this.m07;
          var a22 = this.m08;
          var b00 = mat.m00;
          var b01 = mat.m01;
          var b02 = mat.m02;
          var b10 = mat.m03;
          var b11 = mat.m04;
          var b12 = mat.m05;
          var b20 = mat.m06;
          var b21 = mat.m07;
          var b22 = mat.m08;
          this.m00 = b00 * a00 + b01 * a10 + b02 * a20;
          this.m01 = b00 * a01 + b01 * a11 + b02 * a21;
          this.m02 = b00 * a02 + b01 * a12 + b02 * a22;
          this.m03 = b10 * a00 + b11 * a10 + b12 * a20;
          this.m04 = b10 * a01 + b11 * a11 + b12 * a21;
          this.m05 = b10 * a02 + b11 * a12 + b12 * a22;
          this.m06 = b20 * a00 + b21 * a10 + b22 * a20;
          this.m07 = b20 * a01 + b21 * a11 + b22 * a21;
          this.m08 = b20 * a02 + b21 * a12 + b22 * a22;
          return this;
        };
        _proto.multiplyScalar = function multiplyScalar(scalar) {
          this.m00 *= scalar;
          this.m01 *= scalar;
          this.m02 *= scalar;
          this.m03 *= scalar;
          this.m04 *= scalar;
          this.m05 *= scalar;
          this.m06 *= scalar;
          this.m07 *= scalar;
          this.m08 *= scalar;
          return this;
        };
        _proto.scale = function scale(vec) {
          var x = vec.x;
          var y = vec.y;
          this.m00 = x * this.m00;
          this.m01 = x * this.m01;
          this.m02 = x * this.m02;
          this.m03 = y * this.m03;
          this.m04 = y * this.m04;
          this.m05 = y * this.m05;
          this.m06 = this.m06;
          this.m07 = this.m07;
          this.m08 = this.m08;
          return this;
        };
        _proto.rotate = function rotate(rad) {
          var a00 = this.m00;
          var a01 = this.m01;
          var a02 = this.m02;
          var a10 = this.m03;
          var a11 = this.m04;
          var a12 = this.m05;
          var a20 = this.m06;
          var a21 = this.m07;
          var a22 = this.m08;
          var s = Math.sin(rad);
          var c = Math.cos(rad);
          this.m00 = c * a00 + s * a10;
          this.m01 = c * a01 + s * a11;
          this.m02 = c * a02 + s * a12;
          this.m03 = c * a10 - s * a00;
          this.m04 = c * a11 - s * a01;
          this.m05 = c * a12 - s * a02;
          this.m06 = a20;
          this.m07 = a21;
          this.m08 = a22;
          return this;
        };
        _proto.fromQuat = function fromQuat(q) {
          var x = q.x;
          var y = q.y;
          var z = q.z;
          var w = q.w;
          var x2 = x + x;
          var y2 = y + y;
          var z2 = z + z;
          var xx = x * x2;
          var yx = y * x2;
          var yy = y * y2;
          var zx = z * x2;
          var zy = z * y2;
          var zz = z * z2;
          var wx = w * x2;
          var wy = w * y2;
          var wz = w * z2;
          this.m00 = 1 - yy - zz;
          this.m03 = yx - wz;
          this.m06 = zx + wy;
          this.m01 = yx + wz;
          this.m04 = 1 - xx - zz;
          this.m07 = zy - wx;
          this.m02 = zx - wy;
          this.m05 = zy + wx;
          this.m08 = 1 - xx - yy;
          return this;
        };
        return Mat3;
      }(ValueType));
      _class$39 = Mat3;
      Mat3.IDENTITY = Object.freeze(new _class$39());
      var v3_1$7 = new Vec3();
      var v3_2$2 = new Vec3();
      CCClass.fastDefine('cc.Mat3', Mat3, {
        m00: 1,
        m01: 0,
        m02: 0,
        m03: 0,
        m04: 1,
        m05: 0,
        m06: 0,
        m07: 0,
        m08: 1
      });
      legacyCC.Mat3 = Mat3;

      var _class$38;
      var Quat = exports('aM', function (_ValueType) {
        _inheritsLoose(Quat, _ValueType);
        Quat.clone = function clone(a) {
          return new Quat(a.x, a.y, a.z, a.w);
        };
        Quat.copy = function copy(out, a) {
          out.x = a.x;
          out.y = a.y;
          out.z = a.z;
          out.w = a.w;
          return out;
        };
        Quat.set = function set(out, x, y, z, w) {
          out.x = x;
          out.y = y;
          out.z = z;
          out.w = w;
          return out;
        };
        Quat.identity = function identity(out) {
          out.x = 0;
          out.y = 0;
          out.z = 0;
          out.w = 1;
          return out;
        };
        Quat.rotationTo = function rotationTo(out, a, b) {
          var dot = Vec3.dot(a, b);
          if (dot < -0.999999) {
            Vec3.cross(v3_1$6, Vec3.UNIT_X, a);
            if (v3_1$6.length() < 0.000001) {
              Vec3.cross(v3_1$6, Vec3.UNIT_Y, a);
            }
            Vec3.normalize(v3_1$6, v3_1$6);
            Quat.fromAxisAngle(out, v3_1$6, Math.PI);
            return out;
          } else if (dot > 0.999999) {
            out.x = 0;
            out.y = 0;
            out.z = 0;
            out.w = 1;
            return out;
          } else {
            Vec3.cross(v3_1$6, a, b);
            out.x = v3_1$6.x;
            out.y = v3_1$6.y;
            out.z = v3_1$6.z;
            out.w = 1 + dot;
            return Quat.normalize(out, out);
          }
        };
        Quat.getAxisAngle = function getAxisAngle(outAxis, q) {
          var rad = Math.acos(q.w) * 2.0;
          var s = Math.sin(rad / 2.0);
          if (s !== 0.0) {
            outAxis.x = q.x / s;
            outAxis.y = q.y / s;
            outAxis.z = q.z / s;
          } else {
            outAxis.x = 1;
            outAxis.y = 0;
            outAxis.z = 0;
          }
          return rad;
        };
        Quat.multiply = function multiply(out, a, b) {
          var x = a.x * b.w + a.w * b.x + a.y * b.z - a.z * b.y;
          var y = a.y * b.w + a.w * b.y + a.z * b.x - a.x * b.z;
          var z = a.z * b.w + a.w * b.z + a.x * b.y - a.y * b.x;
          var w = a.w * b.w - a.x * b.x - a.y * b.y - a.z * b.z;
          out.x = x;
          out.y = y;
          out.z = z;
          out.w = w;
          return out;
        };
        Quat.multiplyScalar = function multiplyScalar(out, a, b) {
          out.x = a.x * b;
          out.y = a.y * b;
          out.z = a.z * b;
          out.w = a.w * b;
          return out;
        };
        Quat.scaleAndAdd = function scaleAndAdd(out, a, b, scale) {
          out.x = a.x + b.x * scale;
          out.y = a.y + b.y * scale;
          out.z = a.z + b.z * scale;
          out.w = a.w + b.w * scale;
          return out;
        };
        Quat.rotateX = function rotateX(out, a, rad) {
          rad *= 0.5;
          var bx = Math.sin(rad);
          var bw = Math.cos(rad);
          var x = a.x,
            y = a.y,
            z = a.z,
            w = a.w;
          out.x = x * bw + w * bx;
          out.y = y * bw + z * bx;
          out.z = z * bw - y * bx;
          out.w = w * bw - x * bx;
          return out;
        };
        Quat.rotateY = function rotateY(out, a, rad) {
          rad *= 0.5;
          var by = Math.sin(rad);
          var bw = Math.cos(rad);
          var x = a.x,
            y = a.y,
            z = a.z,
            w = a.w;
          out.x = x * bw - z * by;
          out.y = y * bw + w * by;
          out.z = z * bw + x * by;
          out.w = w * bw - y * by;
          return out;
        };
        Quat.rotateZ = function rotateZ(out, a, rad) {
          rad *= 0.5;
          var bz = Math.sin(rad);
          var bw = Math.cos(rad);
          var x = a.x,
            y = a.y,
            z = a.z,
            w = a.w;
          out.x = x * bw + y * bz;
          out.y = y * bw - x * bz;
          out.z = z * bw + w * bz;
          out.w = w * bw - z * bz;
          return out;
        };
        Quat.rotateAround = function rotateAround(out, rot, axis, rad) {
          Quat.invert(qt_1$1, rot);
          Vec3.transformQuat(v3_1$6, axis, qt_1$1);
          Quat.fromAxisAngle(qt_1$1, v3_1$6, rad);
          Quat.multiply(out, rot, qt_1$1);
          return out;
        };
        Quat.rotateAroundLocal = function rotateAroundLocal(out, rot, axis, rad) {
          Quat.fromAxisAngle(qt_1$1, axis, rad);
          Quat.multiply(out, rot, qt_1$1);
          return out;
        };
        Quat.calculateW = function calculateW(out, a) {
          out.x = a.x;
          out.y = a.y;
          out.z = a.z;
          out.w = Math.sqrt(Math.abs(1.0 - a.x * a.x - a.y * a.y - a.z * a.z));
          return out;
        };
        Quat.dot = function dot(a, b) {
          return a.x * b.x + a.y * b.y + a.z * b.z + a.w * b.w;
        };
        Quat.lerp = function lerp(out, a, b, t) {
          out.x = a.x + t * (b.x - a.x);
          out.y = a.y + t * (b.y - a.y);
          out.z = a.z + t * (b.z - a.z);
          out.w = a.w + t * (b.w - a.w);
          return out;
        };
        Quat.slerp = function slerp(out, a, b, t) {
          var scale0 = 0;
          var scale1 = 0;
          var bx = b.x;
          var by = b.y;
          var bz = b.z;
          var bw = b.w;
          var cosom = a.x * b.x + a.y * b.y + a.z * b.z + a.w * b.w;
          if (cosom < 0.0) {
            cosom = -cosom;
            bx = -bx;
            by = -by;
            bz = -bz;
            bw = -bw;
          }
          if (1.0 - cosom > 0.000001) {
            var omega = Math.acos(cosom);
            var sinom = Math.sin(omega);
            scale0 = Math.sin((1.0 - t) * omega) / sinom;
            scale1 = Math.sin(t * omega) / sinom;
          } else {
            scale0 = 1.0 - t;
            scale1 = t;
          }
          out.x = scale0 * a.x + scale1 * bx;
          out.y = scale0 * a.y + scale1 * by;
          out.z = scale0 * a.z + scale1 * bz;
          out.w = scale0 * a.w + scale1 * bw;
          return out;
        };
        Quat.sqlerp = function sqlerp(out, a, b, c, d, t) {
          Quat.slerp(qt_1$1, a, d, t);
          Quat.slerp(qt_2, b, c, t);
          Quat.slerp(out, qt_1$1, qt_2, 2 * t * (1 - t));
          return out;
        };
        Quat.invert = function invert(out, a) {
          var dot = a.x * a.x + a.y * a.y + a.z * a.z + a.w * a.w;
          var invDot = dot ? 1.0 / dot : 0;
          out.x = -a.x * invDot;
          out.y = -a.y * invDot;
          out.z = -a.z * invDot;
          out.w = a.w * invDot;
          return out;
        };
        Quat.conjugate = function conjugate(out, a) {
          out.x = -a.x;
          out.y = -a.y;
          out.z = -a.z;
          out.w = a.w;
          return out;
        };
        Quat.len = function len(a) {
          return Math.sqrt(a.x * a.x + a.y * a.y + a.z * a.z + a.w * a.w);
        };
        Quat.lengthSqr = function lengthSqr(a) {
          return a.x * a.x + a.y * a.y + a.z * a.z + a.w * a.w;
        };
        Quat.normalize = function normalize(out, a) {
          var len = a.x * a.x + a.y * a.y + a.z * a.z + a.w * a.w;
          if (len > 0) {
            len = 1 / Math.sqrt(len);
            out.x = a.x * len;
            out.y = a.y * len;
            out.z = a.z * len;
            out.w = a.w * len;
          } else {
            out.x = 0;
            out.y = 0;
            out.z = 0;
            out.w = 0;
          }
          return out;
        };
        Quat.fromAxes = function fromAxes(out, xAxis, yAxis, zAxis) {
          Mat3.set(m3_1$2, xAxis.x, xAxis.y, xAxis.z, yAxis.x, yAxis.y, yAxis.z, zAxis.x, zAxis.y, zAxis.z);
          return Quat.normalize(out, Quat.fromMat3(out, m3_1$2));
        };
        Quat.fromViewUp = function fromViewUp(out, view, up) {
          Mat3.fromViewUp(m3_1$2, view, up);
          return Quat.normalize(out, Quat.fromMat3(out, m3_1$2));
        };
        Quat.fromAxisAngle = function fromAxisAngle(out, axis, rad) {
          rad *= 0.5;
          var s = Math.sin(rad);
          out.x = s * axis.x;
          out.y = s * axis.y;
          out.z = s * axis.z;
          out.w = Math.cos(rad);
          return out;
        };
        Quat.fromMat3 = function fromMat3(out, m) {
          var m00 = m.m00,
            m01 = m.m01,
            m02 = m.m02,
            m10 = m.m03,
            m11 = m.m04,
            m12 = m.m05,
            m20 = m.m06,
            m21 = m.m07,
            m22 = m.m08;
          var fourXSquaredMinus1 = m00 - m11 - m22;
          var fourYSquaredMinus1 = m11 - m00 - m22;
          var fourZSquaredMinus1 = m22 - m00 - m11;
          var fourWSquaredMinus1 = m00 + m11 + m22;
          var biggestIndex = 0;
          var fourBiggestSquaredMinus1 = fourWSquaredMinus1;
          if (fourXSquaredMinus1 > fourBiggestSquaredMinus1) {
            fourBiggestSquaredMinus1 = fourXSquaredMinus1;
            biggestIndex = 1;
          }
          if (fourYSquaredMinus1 > fourBiggestSquaredMinus1) {
            fourBiggestSquaredMinus1 = fourYSquaredMinus1;
            biggestIndex = 2;
          }
          if (fourZSquaredMinus1 > fourBiggestSquaredMinus1) {
            fourBiggestSquaredMinus1 = fourZSquaredMinus1;
            biggestIndex = 3;
          }
          var biggestVal = Math.sqrt(fourBiggestSquaredMinus1 + 1) * 0.5;
          var mult = 0.25 / biggestVal;
          switch (biggestIndex) {
            case 0:
              out.w = biggestVal;
              out.x = (m12 - m21) * mult;
              out.y = (m20 - m02) * mult;
              out.z = (m01 - m10) * mult;
              break;
            case 1:
              out.w = (m12 - m21) * mult;
              out.x = biggestVal;
              out.y = (m01 + m10) * mult;
              out.z = (m20 + m02) * mult;
              break;
            case 2:
              out.w = (m20 - m02) * mult;
              out.x = (m01 + m10) * mult;
              out.y = biggestVal;
              out.z = (m12 + m21) * mult;
              break;
            case 3:
              out.w = (m01 - m10) * mult;
              out.x = (m20 + m02) * mult;
              out.y = (m12 + m21) * mult;
              out.z = biggestVal;
              break;
            default:
              out.w = 1;
              out.x = 0;
              out.y = 0;
              out.z = 0;
              break;
          }
          return out;
        };
        Quat.fromEuler = function fromEuler(out, x, y, z) {
          x *= halfToRad;
          y *= halfToRad;
          z *= halfToRad;
          var sx = Math.sin(x);
          var cx = Math.cos(x);
          var sy = Math.sin(y);
          var cy = Math.cos(y);
          var sz = Math.sin(z);
          var cz = Math.cos(z);
          out.x = sx * cy * cz + cx * sy * sz;
          out.y = cx * sy * cz + sx * cy * sz;
          out.z = cx * cy * sz - sx * sy * cz;
          out.w = cx * cy * cz - sx * sy * sz;
          return out;
        };
        Quat.fromAngleZ = function fromAngleZ(out, z) {
          z *= halfToRad;
          out.x = out.y = 0;
          out.z = Math.sin(z);
          out.w = Math.cos(z);
          return out;
        };
        Quat.toAxisX = function toAxisX(out, q) {
          var fy = 2.0 * q.y;
          var fz = 2.0 * q.z;
          out.x = 1.0 - fy * q.y - fz * q.z;
          out.y = fy * q.x + fz * q.w;
          out.z = fz * q.x - fy * q.w;
          return out;
        };
        Quat.toAxisY = function toAxisY(out, q) {
          var fx = 2.0 * q.x;
          var fy = 2.0 * q.y;
          var fz = 2.0 * q.z;
          out.x = fy * q.x - fz * q.w;
          out.y = 1.0 - fx * q.x - fz * q.z;
          out.z = fz * q.y + fx * q.w;
          return out;
        };
        Quat.toAxisZ = function toAxisZ(out, q) {
          var fx = 2.0 * q.x;
          var fy = 2.0 * q.y;
          var fz = 2.0 * q.z;
          out.x = fz * q.x + fy * q.w;
          out.y = fz * q.y - fx * q.w;
          out.z = 1.0 - fx * q.x - fy * q.y;
          return out;
        };
        Quat.toEuler = function toEuler(out, q, outerZ) {
          var x = q.x,
            y = q.y,
            z = q.z,
            w = q.w;
          var bank = 0;
          var heading = 0;
          var attitude = 0;
          var test = x * y + z * w;
          if (test > 0.499999) {
            bank = 0;
            heading = toDegree(2 * Math.atan2(x, w));
            attitude = 90;
          } else if (test < -0.499999) {
            bank = 0;
            heading = -toDegree(2 * Math.atan2(x, w));
            attitude = -90;
          } else {
            var sqx = x * x;
            var sqy = y * y;
            var sqz = z * z;
            bank = toDegree(Math.atan2(2 * x * w - 2 * y * z, 1 - 2 * sqx - 2 * sqz));
            heading = toDegree(Math.atan2(2 * y * w - 2 * x * z, 1 - 2 * sqy - 2 * sqz));
            attitude = toDegree(Math.asin(2 * test));
            if (outerZ) {
              bank = -180 * Math.sign(bank + 1e-6) + bank;
              heading = -180 * Math.sign(heading + 1e-6) + heading;
              attitude = 180 * Math.sign(attitude + 1e-6) - attitude;
            }
          }
          out.x = bank;
          out.y = heading;
          out.z = attitude;
          return out;
        };
        Quat.toEulerInYXZOrder = function toEulerInYXZOrder(out, q) {
          Mat3.fromQuat(m3_1$2, q);
          Mat3.toEuler(m3_1$2, out);
          out.x = toDegree(out.x);
          out.y = toDegree(out.y);
          out.z = toDegree(out.z);
        };
        Quat.toArray = function toArray(out, q, ofs) {
          if (ofs === void 0) {
            ofs = 0;
          }
          out[ofs + 0] = q.x;
          out[ofs + 1] = q.y;
          out[ofs + 2] = q.z;
          out[ofs + 3] = q.w;
          return out;
        };
        Quat.fromArray = function fromArray(out, arr, ofs) {
          if (ofs === void 0) {
            ofs = 0;
          }
          out.x = arr[ofs + 0];
          out.y = arr[ofs + 1];
          out.z = arr[ofs + 2];
          out.w = arr[ofs + 3];
          return out;
        };
        Quat.strictEquals = function strictEquals(a, b) {
          return a.x === b.x && a.y === b.y && a.z === b.z && a.w === b.w;
        };
        Quat.equals = function equals(a, b, epsilon) {
          if (epsilon === void 0) {
            epsilon = EPSILON$3;
          }
          return Math.abs(a.x - b.x) <= epsilon * Math.max(1.0, Math.abs(a.x), Math.abs(b.x)) && Math.abs(a.y - b.y) <= epsilon * Math.max(1.0, Math.abs(a.y), Math.abs(b.y)) && Math.abs(a.z - b.z) <= epsilon * Math.max(1.0, Math.abs(a.z), Math.abs(b.z)) && Math.abs(a.w - b.w) <= epsilon * Math.max(1.0, Math.abs(a.w), Math.abs(b.w));
        };
        Quat.angle = function angle(a, b) {
          var dot = Math.min(Math.abs(Quat.dot(a, b)), 1.0);
          return Math.acos(dot) * 2.0;
        };
        Quat.rotateTowards = function rotateTowards(out, from, to, maxStep) {
          var angle = Quat.angle(from, to);
          if (angle === 0) {
            out.x = to.x;
            out.y = to.y;
            out.z = to.z;
            out.w = to.w;
            return out;
          }
          var t = Math.min(maxStep / toDegree(angle), 1.0);
          return Quat.slerp(out, from, to, t);
        };
        function Quat(x, y, z, w) {
          var _this;
          _this = _ValueType.call(this) || this;
          if (typeof x === 'object') {
            _this.x = x.x;
            _this.y = x.y;
            _this.z = x.z;
            _this.w = x.w;
          } else {
            _this.x = x || 0;
            _this.y = y || 0;
            _this.z = z || 0;
            _this.w = w !== null && w !== void 0 ? w : 1;
          }
          return _this;
        }
        var _proto = Quat.prototype;
        _proto.clone = function clone() {
          return new Quat(this.x, this.y, this.z, this.w);
        };
        _proto.set = function set(x, y, z, w) {
          if (typeof x === 'object') {
            this.x = x.x;
            this.y = x.y;
            this.z = x.z;
            this.w = x.w;
          } else {
            this.x = x || 0;
            this.y = y || 0;
            this.z = z || 0;
            this.w = w !== null && w !== void 0 ? w : 1;
          }
          return this;
        };
        _proto.equals = function equals(other, epsilon) {
          if (epsilon === void 0) {
            epsilon = EPSILON$3;
          }
          return Math.abs(this.x - other.x) <= epsilon * Math.max(1.0, Math.abs(this.x), Math.abs(other.x)) && Math.abs(this.y - other.y) <= epsilon * Math.max(1.0, Math.abs(this.y), Math.abs(other.y)) && Math.abs(this.z - other.z) <= epsilon * Math.max(1.0, Math.abs(this.z), Math.abs(other.z)) && Math.abs(this.w - other.w) <= epsilon * Math.max(1.0, Math.abs(this.w), Math.abs(other.w));
        };
        _proto.strictEquals = function strictEquals(other) {
          return other && this.x === other.x && this.y === other.y && this.z === other.z && this.w === other.w;
        };
        _proto.getEulerAngles = function getEulerAngles(out) {
          return Quat.toEuler(out, this);
        };
        _proto.lerp = function lerp(to, ratio) {
          this.x += ratio * (to.x - this.x);
          this.y += ratio * (to.y - this.y);
          this.z += ratio * (to.z - this.z);
          this.w += ratio * (to.w - this.w);
          return this;
        };
        _proto.slerp = function slerp(to, ratio) {
          return Quat.slerp(this, this, to, ratio);
        };
        _proto.length = function length() {
          return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
        };
        _proto.lengthSqr = function lengthSqr() {
          return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
        };
        return Quat;
      }(ValueType));
      _class$38 = Quat;
      Quat.IDENTITY = Object.freeze(new _class$38());
      var qt_1$1 = new Quat();
      var qt_2 = new Quat();
      var v3_1$6 = new Vec3();
      var m3_1$2 = new Mat3();
      var halfToRad = 0.5 * Math.PI / 180.0;
      CCClass.fastDefine('cc.Quat', Quat, {
        x: 0,
        y: 0,
        z: 0,
        w: 1
      });
      legacyCC.Quat = Quat;
      function quat$1(x, y, z, w) {
        if (x === void 0) {
          x = 0;
        }
        if (y === void 0) {
          y = 0;
        }
        if (z === void 0) {
          z = 0;
        }
        if (w === void 0) {
          w = 1;
        }
        return new Quat(x, y, z, w);
      }
      legacyCC.quat = quat$1;

      var _class$37;
      var preTransforms = exports('aY', Object.freeze([Object.freeze([1, 0, 0, 1]), Object.freeze([0, 1, -1, 0]), Object.freeze([-1, 0, 0, -1]), Object.freeze([0, -1, 1, 0])]));
      var Mat4 = exports('aP', function (_ValueType) {
        _inheritsLoose(Mat4, _ValueType);
        Mat4.clone = function clone(a) {
          return new Mat4(a.m00, a.m01, a.m02, a.m03, a.m04, a.m05, a.m06, a.m07, a.m08, a.m09, a.m10, a.m11, a.m12, a.m13, a.m14, a.m15);
        };
        Mat4.copy = function copy(out, a) {
          out.m00 = a.m00;
          out.m01 = a.m01;
          out.m02 = a.m02;
          out.m03 = a.m03;
          out.m04 = a.m04;
          out.m05 = a.m05;
          out.m06 = a.m06;
          out.m07 = a.m07;
          out.m08 = a.m08;
          out.m09 = a.m09;
          out.m10 = a.m10;
          out.m11 = a.m11;
          out.m12 = a.m12;
          out.m13 = a.m13;
          out.m14 = a.m14;
          out.m15 = a.m15;
          return out;
        };
        Mat4.set = function set(out, m00, m01, m02, m03, m10, m11, m12, m13, m20, m21, m22, m23, m30, m31, m32, m33) {
          out.m00 = m00;
          out.m01 = m01;
          out.m02 = m02;
          out.m03 = m03;
          out.m04 = m10;
          out.m05 = m11;
          out.m06 = m12;
          out.m07 = m13;
          out.m08 = m20;
          out.m09 = m21;
          out.m10 = m22;
          out.m11 = m23;
          out.m12 = m30;
          out.m13 = m31;
          out.m14 = m32;
          out.m15 = m33;
          return out;
        };
        Mat4.identity = function identity(out) {
          out.m00 = 1;
          out.m01 = 0;
          out.m02 = 0;
          out.m03 = 0;
          out.m04 = 0;
          out.m05 = 1;
          out.m06 = 0;
          out.m07 = 0;
          out.m08 = 0;
          out.m09 = 0;
          out.m10 = 1;
          out.m11 = 0;
          out.m12 = 0;
          out.m13 = 0;
          out.m14 = 0;
          out.m15 = 1;
          return out;
        };
        Mat4.transpose = function transpose(out, a) {
          if (out === a) {
            var a01 = a.m01;
            var a02 = a.m02;
            var a03 = a.m03;
            var a12 = a.m06;
            var a13 = a.m07;
            var a23 = a.m11;
            out.m01 = a.m04;
            out.m02 = a.m08;
            out.m03 = a.m12;
            out.m04 = a01;
            out.m06 = a.m09;
            out.m07 = a.m13;
            out.m08 = a02;
            out.m09 = a12;
            out.m11 = a.m14;
            out.m12 = a03;
            out.m13 = a13;
            out.m14 = a23;
          } else {
            out.m00 = a.m00;
            out.m01 = a.m04;
            out.m02 = a.m08;
            out.m03 = a.m12;
            out.m04 = a.m01;
            out.m05 = a.m05;
            out.m06 = a.m09;
            out.m07 = a.m13;
            out.m08 = a.m02;
            out.m09 = a.m06;
            out.m10 = a.m10;
            out.m11 = a.m14;
            out.m12 = a.m03;
            out.m13 = a.m07;
            out.m14 = a.m11;
            out.m15 = a.m15;
          }
          return out;
        };
        Mat4.invert = function invert(out, a) {
          var a00 = a.m00;
          var a01 = a.m01;
          var a02 = a.m02;
          var a03 = a.m03;
          var a10 = a.m04;
          var a11 = a.m05;
          var a12 = a.m06;
          var a13 = a.m07;
          var a20 = a.m08;
          var a21 = a.m09;
          var a22 = a.m10;
          var a23 = a.m11;
          var a30 = a.m12;
          var a31 = a.m13;
          var a32 = a.m14;
          var a33 = a.m15;
          var b00 = a00 * a11 - a01 * a10;
          var b01 = a00 * a12 - a02 * a10;
          var b02 = a00 * a13 - a03 * a10;
          var b03 = a01 * a12 - a02 * a11;
          var b04 = a01 * a13 - a03 * a11;
          var b05 = a02 * a13 - a03 * a12;
          var b06 = a20 * a31 - a21 * a30;
          var b07 = a20 * a32 - a22 * a30;
          var b08 = a20 * a33 - a23 * a30;
          var b09 = a21 * a32 - a22 * a31;
          var b10 = a21 * a33 - a23 * a31;
          var b11 = a22 * a33 - a23 * a32;
          var det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;
          if (det === 0) {
            out.m00 = 0;
            out.m01 = 0;
            out.m02 = 0;
            out.m03 = 0;
            out.m04 = 0;
            out.m05 = 0;
            out.m06 = 0;
            out.m07 = 0;
            out.m08 = 0;
            out.m09 = 0;
            out.m10 = 0;
            out.m11 = 0;
            out.m12 = 0;
            out.m13 = 0;
            out.m14 = 0;
            out.m15 = 0;
            return out;
          }
          det = 1.0 / det;
          out.m00 = (a11 * b11 - a12 * b10 + a13 * b09) * det;
          out.m01 = (a02 * b10 - a01 * b11 - a03 * b09) * det;
          out.m02 = (a31 * b05 - a32 * b04 + a33 * b03) * det;
          out.m03 = (a22 * b04 - a21 * b05 - a23 * b03) * det;
          out.m04 = (a12 * b08 - a10 * b11 - a13 * b07) * det;
          out.m05 = (a00 * b11 - a02 * b08 + a03 * b07) * det;
          out.m06 = (a32 * b02 - a30 * b05 - a33 * b01) * det;
          out.m07 = (a20 * b05 - a22 * b02 + a23 * b01) * det;
          out.m08 = (a10 * b10 - a11 * b08 + a13 * b06) * det;
          out.m09 = (a01 * b08 - a00 * b10 - a03 * b06) * det;
          out.m10 = (a30 * b04 - a31 * b02 + a33 * b00) * det;
          out.m11 = (a21 * b02 - a20 * b04 - a23 * b00) * det;
          out.m12 = (a11 * b07 - a10 * b09 - a12 * b06) * det;
          out.m13 = (a00 * b09 - a01 * b07 + a02 * b06) * det;
          out.m14 = (a31 * b01 - a30 * b03 - a32 * b00) * det;
          out.m15 = (a20 * b03 - a21 * b01 + a22 * b00) * det;
          return out;
        };
        Mat4.determinant = function determinant(a) {
          var a00 = a.m00;
          var a01 = a.m01;
          var a02 = a.m02;
          var a03 = a.m03;
          var a10 = a.m04;
          var a11 = a.m05;
          var a12 = a.m06;
          var a13 = a.m07;
          var a20 = a.m08;
          var a21 = a.m09;
          var a22 = a.m10;
          var a23 = a.m11;
          var a30 = a.m12;
          var a31 = a.m13;
          var a32 = a.m14;
          var a33 = a.m15;
          var b00 = a00 * a11 - a01 * a10;
          var b01 = a00 * a12 - a02 * a10;
          var b02 = a00 * a13 - a03 * a10;
          var b03 = a01 * a12 - a02 * a11;
          var b04 = a01 * a13 - a03 * a11;
          var b05 = a02 * a13 - a03 * a12;
          var b06 = a20 * a31 - a21 * a30;
          var b07 = a20 * a32 - a22 * a30;
          var b08 = a20 * a33 - a23 * a30;
          var b09 = a21 * a32 - a22 * a31;
          var b10 = a21 * a33 - a23 * a31;
          var b11 = a22 * a33 - a23 * a32;
          return b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;
        };
        Mat4.multiply = function multiply(out, a, b) {
          var a00 = a.m00;
          var a01 = a.m01;
          var a02 = a.m02;
          var a03 = a.m03;
          var a10 = a.m04;
          var a11 = a.m05;
          var a12 = a.m06;
          var a13 = a.m07;
          var a20 = a.m08;
          var a21 = a.m09;
          var a22 = a.m10;
          var a23 = a.m11;
          var a30 = a.m12;
          var a31 = a.m13;
          var a32 = a.m14;
          var a33 = a.m15;
          var b0 = b.m00;
          var b1 = b.m01;
          var b2 = b.m02;
          var b3 = b.m03;
          out.m00 = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30;
          out.m01 = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31;
          out.m02 = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32;
          out.m03 = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33;
          b0 = b.m04;
          b1 = b.m05;
          b2 = b.m06;
          b3 = b.m07;
          out.m04 = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30;
          out.m05 = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31;
          out.m06 = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32;
          out.m07 = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33;
          b0 = b.m08;
          b1 = b.m09;
          b2 = b.m10;
          b3 = b.m11;
          out.m08 = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30;
          out.m09 = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31;
          out.m10 = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32;
          out.m11 = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33;
          b0 = b.m12;
          b1 = b.m13;
          b2 = b.m14;
          b3 = b.m15;
          out.m12 = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30;
          out.m13 = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31;
          out.m14 = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32;
          out.m15 = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33;
          return out;
        };
        Mat4.transform = function transform(out, a, v) {
          var x = v.x;
          var y = v.y;
          var z = v.z;
          if (a === out) {
            out.m12 = a.m00 * x + a.m04 * y + a.m08 * z + a.m12;
            out.m13 = a.m01 * x + a.m05 * y + a.m09 * z + a.m13;
            out.m14 = a.m02 * x + a.m06 * y + a.m10 * z + a.m14;
            out.m15 = a.m03 * x + a.m07 * y + a.m11 * z + a.m15;
          } else {
            var a00 = a.m00;
            var a01 = a.m01;
            var a02 = a.m02;
            var a03 = a.m03;
            var a10 = a.m04;
            var a11 = a.m05;
            var a12 = a.m06;
            var a13 = a.m07;
            var a20 = a.m08;
            var a21 = a.m09;
            var a22 = a.m10;
            var a23 = a.m11;
            out.m00 = a00;
            out.m01 = a01;
            out.m02 = a02;
            out.m03 = a03;
            out.m04 = a10;
            out.m05 = a11;
            out.m06 = a12;
            out.m07 = a13;
            out.m08 = a20;
            out.m09 = a21;
            out.m10 = a22;
            out.m11 = a23;
            out.m12 = a00 * x + a10 * y + a20 * z + a.m12;
            out.m13 = a01 * x + a11 * y + a21 * z + a.m13;
            out.m14 = a02 * x + a12 * y + a22 * z + a.m14;
            out.m15 = a03 * x + a13 * y + a23 * z + a.m15;
          }
          return out;
        };
        Mat4.translate = function translate(out, a, v) {
          if (a === out) {
            out.m12 += v.x;
            out.m13 += v.y;
            out.m14 += v.z;
          } else {
            out.m00 = a.m00;
            out.m01 = a.m01;
            out.m02 = a.m02;
            out.m03 = a.m03;
            out.m04 = a.m04;
            out.m05 = a.m05;
            out.m06 = a.m06;
            out.m07 = a.m07;
            out.m08 = a.m08;
            out.m09 = a.m09;
            out.m10 = a.m10;
            out.m11 = a.m11;
            out.m12 = a.m12 + v.x;
            out.m13 = a.m13 + v.y;
            out.m14 = a.m14 + v.z;
            out.m15 = a.m15;
          }
          return out;
        };
        Mat4.scale = function scale(out, a, v) {
          var x = v.x;
          var y = v.y;
          var z = v.z;
          out.m00 = a.m00 * x;
          out.m01 = a.m01 * x;
          out.m02 = a.m02 * x;
          out.m03 = a.m03 * x;
          out.m04 = a.m04 * y;
          out.m05 = a.m05 * y;
          out.m06 = a.m06 * y;
          out.m07 = a.m07 * y;
          out.m08 = a.m08 * z;
          out.m09 = a.m09 * z;
          out.m10 = a.m10 * z;
          out.m11 = a.m11 * z;
          out.m12 = a.m12;
          out.m13 = a.m13;
          out.m14 = a.m14;
          out.m15 = a.m15;
          return out;
        };
        Mat4.rotate = function rotate(out, a, rad, axis) {
          var x = axis.x;
          var y = axis.y;
          var z = axis.z;
          var len = Math.sqrt(x * x + y * y + z * z);
          if (Math.abs(len) < EPSILON$3) {
            return null;
          }
          len = 1 / len;
          x *= len;
          y *= len;
          z *= len;
          var s = Math.sin(rad);
          var c = Math.cos(rad);
          var t = 1 - c;
          var a00 = a.m00;
          var a01 = a.m01;
          var a02 = a.m02;
          var a03 = a.m03;
          var a10 = a.m04;
          var a11 = a.m05;
          var a12 = a.m06;
          var a13 = a.m07;
          var a20 = a.m08;
          var a21 = a.m09;
          var a22 = a.m10;
          var a23 = a.m11;
          var b00 = x * x * t + c;
          var b01 = y * x * t + z * s;
          var b02 = z * x * t - y * s;
          var b10 = x * y * t - z * s;
          var b11 = y * y * t + c;
          var b12 = z * y * t + x * s;
          var b20 = x * z * t + y * s;
          var b21 = y * z * t - x * s;
          var b22 = z * z * t + c;
          out.m00 = a00 * b00 + a10 * b01 + a20 * b02;
          out.m01 = a01 * b00 + a11 * b01 + a21 * b02;
          out.m02 = a02 * b00 + a12 * b01 + a22 * b02;
          out.m03 = a03 * b00 + a13 * b01 + a23 * b02;
          out.m04 = a00 * b10 + a10 * b11 + a20 * b12;
          out.m05 = a01 * b10 + a11 * b11 + a21 * b12;
          out.m06 = a02 * b10 + a12 * b11 + a22 * b12;
          out.m07 = a03 * b10 + a13 * b11 + a23 * b12;
          out.m08 = a00 * b20 + a10 * b21 + a20 * b22;
          out.m09 = a01 * b20 + a11 * b21 + a21 * b22;
          out.m10 = a02 * b20 + a12 * b21 + a22 * b22;
          out.m11 = a03 * b20 + a13 * b21 + a23 * b22;
          if (a !== out) {
            out.m12 = a.m12;
            out.m13 = a.m13;
            out.m14 = a.m14;
            out.m15 = a.m15;
          }
          return out;
        };
        Mat4.rotateX = function rotateX(out, a, rad) {
          var s = Math.sin(rad);
          var c = Math.cos(rad);
          var a10 = a.m04;
          var a11 = a.m05;
          var a12 = a.m06;
          var a13 = a.m07;
          var a20 = a.m08;
          var a21 = a.m09;
          var a22 = a.m10;
          var a23 = a.m11;
          if (a !== out) {
            out.m00 = a.m00;
            out.m01 = a.m01;
            out.m02 = a.m02;
            out.m03 = a.m03;
            out.m12 = a.m12;
            out.m13 = a.m13;
            out.m14 = a.m14;
            out.m15 = a.m15;
          }
          out.m04 = a10 * c + a20 * s;
          out.m05 = a11 * c + a21 * s;
          out.m06 = a12 * c + a22 * s;
          out.m07 = a13 * c + a23 * s;
          out.m08 = a20 * c - a10 * s;
          out.m09 = a21 * c - a11 * s;
          out.m10 = a22 * c - a12 * s;
          out.m11 = a23 * c - a13 * s;
          return out;
        };
        Mat4.rotateY = function rotateY(out, a, rad) {
          var s = Math.sin(rad);
          var c = Math.cos(rad);
          var a00 = a.m00;
          var a01 = a.m01;
          var a02 = a.m02;
          var a03 = a.m03;
          var a20 = a.m08;
          var a21 = a.m09;
          var a22 = a.m10;
          var a23 = a.m11;
          if (a !== out) {
            out.m04 = a.m04;
            out.m05 = a.m05;
            out.m06 = a.m06;
            out.m07 = a.m07;
            out.m12 = a.m12;
            out.m13 = a.m13;
            out.m14 = a.m14;
            out.m15 = a.m15;
          }
          out.m00 = a00 * c - a20 * s;
          out.m01 = a01 * c - a21 * s;
          out.m02 = a02 * c - a22 * s;
          out.m03 = a03 * c - a23 * s;
          out.m08 = a00 * s + a20 * c;
          out.m09 = a01 * s + a21 * c;
          out.m10 = a02 * s + a22 * c;
          out.m11 = a03 * s + a23 * c;
          return out;
        };
        Mat4.rotateZ = function rotateZ(out, a, rad) {
          var s = Math.sin(rad);
          var c = Math.cos(rad);
          var a00 = a.m00;
          var a01 = a.m01;
          var a02 = a.m02;
          var a03 = a.m03;
          var a10 = a.m04;
          var a11 = a.m05;
          var a12 = a.m06;
          var a13 = a.m07;
          if (a !== out) {
            out.m08 = a.m08;
            out.m09 = a.m09;
            out.m10 = a.m10;
            out.m11 = a.m11;
            out.m12 = a.m12;
            out.m13 = a.m13;
            out.m14 = a.m14;
            out.m15 = a.m15;
          }
          out.m00 = a00 * c + a10 * s;
          out.m01 = a01 * c + a11 * s;
          out.m02 = a02 * c + a12 * s;
          out.m03 = a03 * c + a13 * s;
          out.m04 = a10 * c - a00 * s;
          out.m05 = a11 * c - a01 * s;
          out.m06 = a12 * c - a02 * s;
          out.m07 = a13 * c - a03 * s;
          return out;
        };
        Mat4.fromTranslation = function fromTranslation(out, v) {
          out.m00 = 1;
          out.m01 = 0;
          out.m02 = 0;
          out.m03 = 0;
          out.m04 = 0;
          out.m05 = 1;
          out.m06 = 0;
          out.m07 = 0;
          out.m08 = 0;
          out.m09 = 0;
          out.m10 = 1;
          out.m11 = 0;
          out.m12 = v.x;
          out.m13 = v.y;
          out.m14 = v.z;
          out.m15 = 1;
          return out;
        };
        Mat4.fromScaling = function fromScaling(out, v) {
          out.m00 = v.x;
          out.m01 = 0;
          out.m02 = 0;
          out.m03 = 0;
          out.m04 = 0;
          out.m05 = v.y;
          out.m06 = 0;
          out.m07 = 0;
          out.m08 = 0;
          out.m09 = 0;
          out.m10 = v.z;
          out.m11 = 0;
          out.m12 = 0;
          out.m13 = 0;
          out.m14 = 0;
          out.m15 = 1;
          return out;
        };
        Mat4.fromRotation = function fromRotation(out, rad, axis) {
          var x = axis.x;
          var y = axis.y;
          var z = axis.z;
          var len = Math.sqrt(x * x + y * y + z * z);
          if (Math.abs(len) < EPSILON$3) {
            return null;
          }
          len = 1 / len;
          x *= len;
          y *= len;
          z *= len;
          var s = Math.sin(rad);
          var c = Math.cos(rad);
          var t = 1 - c;
          out.m00 = x * x * t + c;
          out.m01 = y * x * t + z * s;
          out.m02 = z * x * t - y * s;
          out.m03 = 0;
          out.m04 = x * y * t - z * s;
          out.m05 = y * y * t + c;
          out.m06 = z * y * t + x * s;
          out.m07 = 0;
          out.m08 = x * z * t + y * s;
          out.m09 = y * z * t - x * s;
          out.m10 = z * z * t + c;
          out.m11 = 0;
          out.m12 = 0;
          out.m13 = 0;
          out.m14 = 0;
          out.m15 = 1;
          return out;
        };
        Mat4.fromXRotation = function fromXRotation(out, rad) {
          var s = Math.sin(rad);
          var c = Math.cos(rad);
          out.m00 = 1;
          out.m01 = 0;
          out.m02 = 0;
          out.m03 = 0;
          out.m04 = 0;
          out.m05 = c;
          out.m06 = s;
          out.m07 = 0;
          out.m08 = 0;
          out.m09 = -s;
          out.m10 = c;
          out.m11 = 0;
          out.m12 = 0;
          out.m13 = 0;
          out.m14 = 0;
          out.m15 = 1;
          return out;
        };
        Mat4.fromYRotation = function fromYRotation(out, rad) {
          var s = Math.sin(rad);
          var c = Math.cos(rad);
          out.m00 = c;
          out.m01 = 0;
          out.m02 = -s;
          out.m03 = 0;
          out.m04 = 0;
          out.m05 = 1;
          out.m06 = 0;
          out.m07 = 0;
          out.m08 = s;
          out.m09 = 0;
          out.m10 = c;
          out.m11 = 0;
          out.m12 = 0;
          out.m13 = 0;
          out.m14 = 0;
          out.m15 = 1;
          return out;
        };
        Mat4.fromZRotation = function fromZRotation(out, rad) {
          var s = Math.sin(rad);
          var c = Math.cos(rad);
          out.m00 = c;
          out.m01 = s;
          out.m02 = 0;
          out.m03 = 0;
          out.m04 = -s;
          out.m05 = c;
          out.m06 = 0;
          out.m07 = 0;
          out.m08 = 0;
          out.m09 = 0;
          out.m10 = 1;
          out.m11 = 0;
          out.m12 = 0;
          out.m13 = 0;
          out.m14 = 0;
          out.m15 = 1;
          return out;
        };
        Mat4.fromRT = function fromRT(out, q, v) {
          var x = q.x;
          var y = q.y;
          var z = q.z;
          var w = q.w;
          var x2 = x + x;
          var y2 = y + y;
          var z2 = z + z;
          var xx = x * x2;
          var xy = x * y2;
          var xz = x * z2;
          var yy = y * y2;
          var yz = y * z2;
          var zz = z * z2;
          var wx = w * x2;
          var wy = w * y2;
          var wz = w * z2;
          out.m00 = 1 - (yy + zz);
          out.m01 = xy + wz;
          out.m02 = xz - wy;
          out.m03 = 0;
          out.m04 = xy - wz;
          out.m05 = 1 - (xx + zz);
          out.m06 = yz + wx;
          out.m07 = 0;
          out.m08 = xz + wy;
          out.m09 = yz - wx;
          out.m10 = 1 - (xx + yy);
          out.m11 = 0;
          out.m12 = v.x;
          out.m13 = v.y;
          out.m14 = v.z;
          out.m15 = 1;
          return out;
        };
        Mat4.getTranslation = function getTranslation(out, mat) {
          out.x = mat.m12;
          out.y = mat.m13;
          out.z = mat.m14;
          return out;
        };
        Mat4.getScaling = function getScaling(out, mat) {
          var m00 = m3_1$1.m00 = mat.m00;
          var m01 = m3_1$1.m01 = mat.m01;
          var m02 = m3_1$1.m02 = mat.m02;
          var m04 = m3_1$1.m03 = mat.m04;
          var m05 = m3_1$1.m04 = mat.m05;
          var m06 = m3_1$1.m05 = mat.m06;
          var m08 = m3_1$1.m06 = mat.m08;
          var m09 = m3_1$1.m07 = mat.m09;
          var m10 = m3_1$1.m08 = mat.m10;
          out.x = Math.sqrt(m00 * m00 + m01 * m01 + m02 * m02);
          out.y = Math.sqrt(m04 * m04 + m05 * m05 + m06 * m06);
          out.z = Math.sqrt(m08 * m08 + m09 * m09 + m10 * m10);
          if (Mat3.determinant(m3_1$1) < 0) {
            out.x *= -1;
          }
          return out;
        };
        Mat4.getRotation = function getRotation(out, mat) {
          var trace = mat.m00 + mat.m05 + mat.m10;
          var S = 0;
          if (trace > 0) {
            S = Math.sqrt(trace + 1.0) * 2;
            out.w = 0.25 * S;
            out.x = (mat.m06 - mat.m09) / S;
            out.y = (mat.m08 - mat.m02) / S;
            out.z = (mat.m01 - mat.m04) / S;
          } else if (mat.m00 > mat.m05 && mat.m00 > mat.m10) {
            S = Math.sqrt(1.0 + mat.m00 - mat.m05 - mat.m10) * 2;
            out.w = (mat.m06 - mat.m09) / S;
            out.x = 0.25 * S;
            out.y = (mat.m01 + mat.m04) / S;
            out.z = (mat.m08 + mat.m02) / S;
          } else if (mat.m05 > mat.m10) {
            S = Math.sqrt(1.0 + mat.m05 - mat.m00 - mat.m10) * 2;
            out.w = (mat.m08 - mat.m02) / S;
            out.x = (mat.m01 + mat.m04) / S;
            out.y = 0.25 * S;
            out.z = (mat.m06 + mat.m09) / S;
          } else {
            S = Math.sqrt(1.0 + mat.m10 - mat.m00 - mat.m05) * 2;
            out.w = (mat.m01 - mat.m04) / S;
            out.x = (mat.m08 + mat.m02) / S;
            out.y = (mat.m06 + mat.m09) / S;
            out.z = 0.25 * S;
          }
          return out;
        };
        Mat4.toRTS = function toRTS(m, q, v, s) {
          var sx = Vec3.set(v3_1$5, m.m00, m.m01, m.m02).length();
          var sy = Vec3.set(v3_1$5, m.m04, m.m05, m.m06).length();
          var sz = Vec3.set(v3_1$5, m.m08, m.m09, m.m10).length();
          m3_1$1.m00 = m.m00 / sx;
          m3_1$1.m01 = m.m01 / sx;
          m3_1$1.m02 = m.m02 / sx;
          m3_1$1.m03 = m.m04 / sy;
          m3_1$1.m04 = m.m05 / sy;
          m3_1$1.m05 = m.m06 / sy;
          m3_1$1.m06 = m.m08 / sz;
          m3_1$1.m07 = m.m09 / sz;
          m3_1$1.m08 = m.m10 / sz;
          var det = Mat3.determinant(m3_1$1);
          if (s) {
            Vec3.set(s, sx, sy, sz);
            if (det < 0) {
              s.x *= -1;
            }
          }
          if (v) {
            Vec3.set(v, m.m12, m.m13, m.m14);
          }
          if (q) {
            if (det < 0) {
              m3_1$1.m00 *= -1;
              m3_1$1.m01 *= -1;
              m3_1$1.m02 *= -1;
            }
            Quat.fromMat3(q, m3_1$1);
          }
        };
        Mat4.toSRT = function toSRT(m, q, v, s) {
          var sx = Vec3.set(v3_1$5, m.m00, m.m01, m.m02).length();
          var sy = Vec3.set(v3_1$5, m.m04, m.m05, m.m06).length();
          var sz = Vec3.set(v3_1$5, m.m08, m.m09, m.m10).length();
          if (s) {
            s.x = sx;
            s.y = sy;
            s.z = sz;
          }
          if (v) {
            Vec3.set(v, m.m12, m.m13, m.m14);
          }
          if (q) {
            m3_1$1.m00 = m.m00 / sx;
            m3_1$1.m01 = m.m01 / sx;
            m3_1$1.m02 = m.m02 / sx;
            m3_1$1.m03 = m.m04 / sy;
            m3_1$1.m04 = m.m05 / sy;
            m3_1$1.m05 = m.m06 / sy;
            m3_1$1.m06 = m.m08 / sz;
            m3_1$1.m07 = m.m09 / sz;
            m3_1$1.m08 = m.m10 / sz;
            var det = Mat3.determinant(m3_1$1);
            if (det < 0) {
              if (s) s.x *= -1;
              m3_1$1.m00 *= -1;
              m3_1$1.m01 *= -1;
              m3_1$1.m02 *= -1;
            }
            Quat.fromMat3(q, m3_1$1);
          }
        };
        Mat4.toEuler = function toEuler(m, v) {
          Mat3.set(m3_1$1, m.m00, m.m01, m.m02, m.m04, m.m05, m.m06, m.m08, m.m09, m.m10);
          return Mat3.toEuler(m3_1$1, v);
        };
        Mat4.fromRTS = function fromRTS(out, q, v, s) {
          var x = q.x;
          var y = q.y;
          var z = q.z;
          var w = q.w;
          var x2 = x + x;
          var y2 = y + y;
          var z2 = z + z;
          var xx = x * x2;
          var xy = x * y2;
          var xz = x * z2;
          var yy = y * y2;
          var yz = y * z2;
          var zz = z * z2;
          var wx = w * x2;
          var wy = w * y2;
          var wz = w * z2;
          var sx = s.x;
          var sy = s.y;
          var sz = s.z;
          out.m00 = (1 - (yy + zz)) * sx;
          out.m01 = (xy + wz) * sx;
          out.m02 = (xz - wy) * sx;
          out.m03 = 0;
          out.m04 = (xy - wz) * sy;
          out.m05 = (1 - (xx + zz)) * sy;
          out.m06 = (yz + wx) * sy;
          out.m07 = 0;
          out.m08 = (xz + wy) * sz;
          out.m09 = (yz - wx) * sz;
          out.m10 = (1 - (xx + yy)) * sz;
          out.m11 = 0;
          out.m12 = v.x;
          out.m13 = v.y;
          out.m14 = v.z;
          out.m15 = 1;
          return out;
        };
        Mat4.fromSRT = function fromSRT(out, q, v, s) {
          var x = q.x;
          var y = q.y;
          var z = q.z;
          var w = q.w;
          var x2 = x + x;
          var y2 = y + y;
          var z2 = z + z;
          var xx = x * x2;
          var xy = x * y2;
          var xz = x * z2;
          var yy = y * y2;
          var yz = y * z2;
          var zz = z * z2;
          var wx = w * x2;
          var wy = w * y2;
          var wz = w * z2;
          var sx = s.x;
          var sy = s.y;
          var sz = s.z;
          out.m00 = (1 - (yy + zz)) * sx;
          out.m01 = (xy + wz) * sx;
          out.m02 = (xz - wy) * sx;
          out.m03 = 0;
          out.m04 = (xy - wz) * sy;
          out.m05 = (1 - (xx + zz)) * sy;
          out.m06 = (yz + wx) * sy;
          out.m07 = 0;
          out.m08 = (xz + wy) * sz;
          out.m09 = (yz - wx) * sz;
          out.m10 = (1 - (xx + yy)) * sz;
          out.m11 = 0;
          out.m12 = v.x;
          out.m13 = v.y;
          out.m14 = v.z;
          out.m15 = 1;
          return out;
        };
        Mat4.fromRTSOrigin = function fromRTSOrigin(out, q, v, s, o) {
          var x = q.x;
          var y = q.y;
          var z = q.z;
          var w = q.w;
          var x2 = x + x;
          var y2 = y + y;
          var z2 = z + z;
          var xx = x * x2;
          var xy = x * y2;
          var xz = x * z2;
          var yy = y * y2;
          var yz = y * z2;
          var zz = z * z2;
          var wx = w * x2;
          var wy = w * y2;
          var wz = w * z2;
          var sx = s.x;
          var sy = s.y;
          var sz = s.z;
          var ox = o.x;
          var oy = o.y;
          var oz = o.z;
          out.m00 = (1 - (yy + zz)) * sx;
          out.m01 = (xy + wz) * sx;
          out.m02 = (xz - wy) * sx;
          out.m03 = 0;
          out.m04 = (xy - wz) * sy;
          out.m05 = (1 - (xx + zz)) * sy;
          out.m06 = (yz + wx) * sy;
          out.m07 = 0;
          out.m08 = (xz + wy) * sz;
          out.m09 = (yz - wx) * sz;
          out.m10 = (1 - (xx + yy)) * sz;
          out.m11 = 0;
          out.m12 = v.x + ox - (out.m00 * ox + out.m04 * oy + out.m08 * oz);
          out.m13 = v.y + oy - (out.m01 * ox + out.m05 * oy + out.m09 * oz);
          out.m14 = v.z + oz - (out.m02 * ox + out.m06 * oy + out.m10 * oz);
          out.m15 = 1;
          return out;
        };
        Mat4.fromSRTOrigin = function fromSRTOrigin(out, q, v, s, o) {
          var x = q.x;
          var y = q.y;
          var z = q.z;
          var w = q.w;
          var x2 = x + x;
          var y2 = y + y;
          var z2 = z + z;
          var xx = x * x2;
          var xy = x * y2;
          var xz = x * z2;
          var yy = y * y2;
          var yz = y * z2;
          var zz = z * z2;
          var wx = w * x2;
          var wy = w * y2;
          var wz = w * z2;
          var sx = s.x;
          var sy = s.y;
          var sz = s.z;
          var ox = o.x;
          var oy = o.y;
          var oz = o.z;
          out.m00 = (1 - (yy + zz)) * sx;
          out.m01 = (xy + wz) * sx;
          out.m02 = (xz - wy) * sx;
          out.m03 = 0;
          out.m04 = (xy - wz) * sy;
          out.m05 = (1 - (xx + zz)) * sy;
          out.m06 = (yz + wx) * sy;
          out.m07 = 0;
          out.m08 = (xz + wy) * sz;
          out.m09 = (yz - wx) * sz;
          out.m10 = (1 - (xx + yy)) * sz;
          out.m11 = 0;
          out.m12 = v.x + ox - (out.m00 * ox + out.m04 * oy + out.m08 * oz);
          out.m13 = v.y + oy - (out.m01 * ox + out.m05 * oy + out.m09 * oz);
          out.m14 = v.z + oz - (out.m02 * ox + out.m06 * oy + out.m10 * oz);
          out.m15 = 1;
          return out;
        };
        Mat4.fromQuat = function fromQuat(out, q) {
          var x = q.x;
          var y = q.y;
          var z = q.z;
          var w = q.w;
          var x2 = x + x;
          var y2 = y + y;
          var z2 = z + z;
          var xx = x * x2;
          var yx = y * x2;
          var yy = y * y2;
          var zx = z * x2;
          var zy = z * y2;
          var zz = z * z2;
          var wx = w * x2;
          var wy = w * y2;
          var wz = w * z2;
          out.m00 = 1 - yy - zz;
          out.m01 = yx + wz;
          out.m02 = zx - wy;
          out.m03 = 0;
          out.m04 = yx - wz;
          out.m05 = 1 - xx - zz;
          out.m06 = zy + wx;
          out.m07 = 0;
          out.m08 = zx + wy;
          out.m09 = zy - wx;
          out.m10 = 1 - xx - yy;
          out.m11 = 0;
          out.m12 = 0;
          out.m13 = 0;
          out.m14 = 0;
          out.m15 = 1;
          return out;
        };
        Mat4.frustum = function frustum(out, left, right, bottom, top, near, far) {
          var rl = 1 / (right - left);
          var tb = 1 / (top - bottom);
          var nf = 1 / (near - far);
          out.m00 = near * 2 * rl;
          out.m01 = 0;
          out.m02 = 0;
          out.m03 = 0;
          out.m04 = 0;
          out.m05 = near * 2 * tb;
          out.m06 = 0;
          out.m07 = 0;
          out.m08 = (right + left) * rl;
          out.m09 = (top + bottom) * tb;
          out.m10 = (far + near) * nf;
          out.m11 = -1;
          out.m12 = 0;
          out.m13 = 0;
          out.m14 = far * near * 2 * nf;
          out.m15 = 0;
          return out;
        };
        Mat4.perspective = function perspective(out, fov, aspect, near, far, isFOVY, minClipZ, projectionSignY, orientation) {
          if (isFOVY === void 0) {
            isFOVY = true;
          }
          if (minClipZ === void 0) {
            minClipZ = -1;
          }
          if (projectionSignY === void 0) {
            projectionSignY = 1;
          }
          if (orientation === void 0) {
            orientation = 0;
          }
          var f = 1.0 / Math.tan(fov / 2);
          var nf = 1 / (near - far);
          var x = isFOVY ? f / aspect : f;
          var y = (isFOVY ? f : f * aspect) * projectionSignY;
          var preTransform = preTransforms[orientation];
          out.m00 = x * preTransform[0];
          out.m01 = x * preTransform[1];
          out.m02 = 0;
          out.m03 = 0;
          out.m04 = y * preTransform[2];
          out.m05 = y * preTransform[3];
          out.m06 = 0;
          out.m07 = 0;
          out.m08 = 0;
          out.m09 = 0;
          out.m10 = (far - minClipZ * near) * nf;
          out.m11 = -1;
          out.m12 = 0;
          out.m13 = 0;
          out.m14 = far * near * nf * (1 - minClipZ);
          out.m15 = 0;
          return out;
        };
        Mat4.ortho = function ortho(out, left, right, bottom, top, near, far, minClipZ, projectionSignY, orientation) {
          if (minClipZ === void 0) {
            minClipZ = -1;
          }
          if (projectionSignY === void 0) {
            projectionSignY = 1;
          }
          if (orientation === void 0) {
            orientation = 0;
          }
          var lr = 1 / (left - right);
          var bt = 1 / (bottom - top) * projectionSignY;
          var nf = 1 / (near - far);
          var x = -2 * lr;
          var y = -2 * bt;
          var dx = (left + right) * lr;
          var dy = (top + bottom) * bt;
          var preTransform = preTransforms[orientation];
          out.m00 = x * preTransform[0];
          out.m01 = x * preTransform[1];
          out.m02 = 0;
          out.m03 = 0;
          out.m04 = y * preTransform[2];
          out.m05 = y * preTransform[3];
          out.m06 = 0;
          out.m07 = 0;
          out.m08 = 0;
          out.m09 = 0;
          out.m10 = nf * (1 - minClipZ);
          out.m11 = 0;
          out.m12 = dx * preTransform[0] + dy * preTransform[2];
          out.m13 = dx * preTransform[1] + dy * preTransform[3];
          out.m14 = (near - minClipZ * far) * nf;
          out.m15 = 1;
          return out;
        };
        Mat4.lookAt = function lookAt(out, eye, center, up) {
          var eyex = eye.x;
          var eyey = eye.y;
          var eyez = eye.z;
          var upx = up.x;
          var upy = up.y;
          var upz = up.z;
          var centerx = center.x;
          var centery = center.y;
          var centerz = center.z;
          var z0 = eyex - centerx;
          var z1 = eyey - centery;
          var z2 = eyez - centerz;
          var len = 1 / Math.sqrt(z0 * z0 + z1 * z1 + z2 * z2);
          z0 *= len;
          z1 *= len;
          z2 *= len;
          var x0 = upy * z2 - upz * z1;
          var x1 = upz * z0 - upx * z2;
          var x2 = upx * z1 - upy * z0;
          len = 1 / Math.sqrt(x0 * x0 + x1 * x1 + x2 * x2);
          x0 *= len;
          x1 *= len;
          x2 *= len;
          var y0 = z1 * x2 - z2 * x1;
          var y1 = z2 * x0 - z0 * x2;
          var y2 = z0 * x1 - z1 * x0;
          out.m00 = x0;
          out.m01 = y0;
          out.m02 = z0;
          out.m03 = 0;
          out.m04 = x1;
          out.m05 = y1;
          out.m06 = z1;
          out.m07 = 0;
          out.m08 = x2;
          out.m09 = y2;
          out.m10 = z2;
          out.m11 = 0;
          out.m12 = -(x0 * eyex + x1 * eyey + x2 * eyez);
          out.m13 = -(y0 * eyex + y1 * eyey + y2 * eyez);
          out.m14 = -(z0 * eyex + z1 * eyey + z2 * eyez);
          out.m15 = 1;
          return out;
        };
        Mat4.inverseTranspose = function inverseTranspose(out, a) {
          var a00 = a.m00;
          var a01 = a.m01;
          var a02 = a.m02;
          var a03 = a.m03;
          var a10 = a.m04;
          var a11 = a.m05;
          var a12 = a.m06;
          var a13 = a.m07;
          var a20 = a.m08;
          var a21 = a.m09;
          var a22 = a.m10;
          var a23 = a.m11;
          var a30 = a.m12;
          var a31 = a.m13;
          var a32 = a.m14;
          var a33 = a.m15;
          var b00 = a00 * a11 - a01 * a10;
          var b01 = a00 * a12 - a02 * a10;
          var b02 = a00 * a13 - a03 * a10;
          var b03 = a01 * a12 - a02 * a11;
          var b04 = a01 * a13 - a03 * a11;
          var b05 = a02 * a13 - a03 * a12;
          var b06 = a20 * a31 - a21 * a30;
          var b07 = a20 * a32 - a22 * a30;
          var b08 = a20 * a33 - a23 * a30;
          var b09 = a21 * a32 - a22 * a31;
          var b10 = a21 * a33 - a23 * a31;
          var b11 = a22 * a33 - a23 * a32;
          var det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;
          if (!det) {
            return null;
          }
          det = 1.0 / det;
          out.m00 = (a11 * b11 - a12 * b10 + a13 * b09) * det;
          out.m01 = (a12 * b08 - a10 * b11 - a13 * b07) * det;
          out.m02 = (a10 * b10 - a11 * b08 + a13 * b06) * det;
          out.m03 = 0;
          out.m04 = (a02 * b10 - a01 * b11 - a03 * b09) * det;
          out.m05 = (a00 * b11 - a02 * b08 + a03 * b07) * det;
          out.m06 = (a01 * b08 - a00 * b10 - a03 * b06) * det;
          out.m07 = 0;
          out.m08 = (a31 * b05 - a32 * b04 + a33 * b03) * det;
          out.m09 = (a32 * b02 - a30 * b05 - a33 * b01) * det;
          out.m10 = (a30 * b04 - a31 * b02 + a33 * b00) * det;
          out.m11 = 0;
          out.m12 = 0;
          out.m13 = 0;
          out.m14 = 0;
          out.m15 = 1;
          return out;
        };
        Mat4.toArray = function toArray(out, m, ofs) {
          if (ofs === void 0) {
            ofs = 0;
          }
          out[ofs + 0] = m.m00;
          out[ofs + 1] = m.m01;
          out[ofs + 2] = m.m02;
          out[ofs + 3] = m.m03;
          out[ofs + 4] = m.m04;
          out[ofs + 5] = m.m05;
          out[ofs + 6] = m.m06;
          out[ofs + 7] = m.m07;
          out[ofs + 8] = m.m08;
          out[ofs + 9] = m.m09;
          out[ofs + 10] = m.m10;
          out[ofs + 11] = m.m11;
          out[ofs + 12] = m.m12;
          out[ofs + 13] = m.m13;
          out[ofs + 14] = m.m14;
          out[ofs + 15] = m.m15;
          return out;
        };
        Mat4.fromArray = function fromArray(out, arr, ofs) {
          if (ofs === void 0) {
            ofs = 0;
          }
          out.m00 = arr[ofs + 0];
          out.m01 = arr[ofs + 1];
          out.m02 = arr[ofs + 2];
          out.m03 = arr[ofs + 3];
          out.m04 = arr[ofs + 4];
          out.m05 = arr[ofs + 5];
          out.m06 = arr[ofs + 6];
          out.m07 = arr[ofs + 7];
          out.m08 = arr[ofs + 8];
          out.m09 = arr[ofs + 9];
          out.m10 = arr[ofs + 10];
          out.m11 = arr[ofs + 11];
          out.m12 = arr[ofs + 12];
          out.m13 = arr[ofs + 13];
          out.m14 = arr[ofs + 14];
          out.m15 = arr[ofs + 15];
          return out;
        };
        Mat4.add = function add(out, a, b) {
          out.m00 = a.m00 + b.m00;
          out.m01 = a.m01 + b.m01;
          out.m02 = a.m02 + b.m02;
          out.m03 = a.m03 + b.m03;
          out.m04 = a.m04 + b.m04;
          out.m05 = a.m05 + b.m05;
          out.m06 = a.m06 + b.m06;
          out.m07 = a.m07 + b.m07;
          out.m08 = a.m08 + b.m08;
          out.m09 = a.m09 + b.m09;
          out.m10 = a.m10 + b.m10;
          out.m11 = a.m11 + b.m11;
          out.m12 = a.m12 + b.m12;
          out.m13 = a.m13 + b.m13;
          out.m14 = a.m14 + b.m14;
          out.m15 = a.m15 + b.m15;
          return out;
        };
        Mat4.subtract = function subtract(out, a, b) {
          out.m00 = a.m00 - b.m00;
          out.m01 = a.m01 - b.m01;
          out.m02 = a.m02 - b.m02;
          out.m03 = a.m03 - b.m03;
          out.m04 = a.m04 - b.m04;
          out.m05 = a.m05 - b.m05;
          out.m06 = a.m06 - b.m06;
          out.m07 = a.m07 - b.m07;
          out.m08 = a.m08 - b.m08;
          out.m09 = a.m09 - b.m09;
          out.m10 = a.m10 - b.m10;
          out.m11 = a.m11 - b.m11;
          out.m12 = a.m12 - b.m12;
          out.m13 = a.m13 - b.m13;
          out.m14 = a.m14 - b.m14;
          out.m15 = a.m15 - b.m15;
          return out;
        };
        Mat4.multiplyScalar = function multiplyScalar(out, a, b) {
          out.m00 = a.m00 * b;
          out.m01 = a.m01 * b;
          out.m02 = a.m02 * b;
          out.m03 = a.m03 * b;
          out.m04 = a.m04 * b;
          out.m05 = a.m05 * b;
          out.m06 = a.m06 * b;
          out.m07 = a.m07 * b;
          out.m08 = a.m08 * b;
          out.m09 = a.m09 * b;
          out.m10 = a.m10 * b;
          out.m11 = a.m11 * b;
          out.m12 = a.m12 * b;
          out.m13 = a.m13 * b;
          out.m14 = a.m14 * b;
          out.m15 = a.m15 * b;
          return out;
        };
        Mat4.multiplyScalarAndAdd = function multiplyScalarAndAdd(out, a, b, scale) {
          out.m00 = a.m00 + b.m00 * scale;
          out.m01 = a.m01 + b.m01 * scale;
          out.m02 = a.m02 + b.m02 * scale;
          out.m03 = a.m03 + b.m03 * scale;
          out.m04 = a.m04 + b.m04 * scale;
          out.m05 = a.m05 + b.m05 * scale;
          out.m06 = a.m06 + b.m06 * scale;
          out.m07 = a.m07 + b.m07 * scale;
          out.m08 = a.m08 + b.m08 * scale;
          out.m09 = a.m09 + b.m09 * scale;
          out.m10 = a.m10 + b.m10 * scale;
          out.m11 = a.m11 + b.m11 * scale;
          out.m12 = a.m12 + b.m12 * scale;
          out.m13 = a.m13 + b.m13 * scale;
          out.m14 = a.m14 + b.m14 * scale;
          out.m15 = a.m15 + b.m15 * scale;
          return out;
        };
        Mat4.strictEquals = function strictEquals(a, b) {
          return a.m00 === b.m00 && a.m01 === b.m01 && a.m02 === b.m02 && a.m03 === b.m03 && a.m04 === b.m04 && a.m05 === b.m05 && a.m06 === b.m06 && a.m07 === b.m07 && a.m08 === b.m08 && a.m09 === b.m09 && a.m10 === b.m10 && a.m11 === b.m11 && a.m12 === b.m12 && a.m13 === b.m13 && a.m14 === b.m14 && a.m15 === b.m15;
        };
        Mat4.equals = function equals(a, b, epsilon) {
          if (epsilon === void 0) {
            epsilon = EPSILON$3;
          }
          return Math.abs(a.m00 - b.m00) <= epsilon * Math.max(1.0, Math.abs(a.m00), Math.abs(b.m00)) && Math.abs(a.m01 - b.m01) <= epsilon * Math.max(1.0, Math.abs(a.m01), Math.abs(b.m01)) && Math.abs(a.m02 - b.m02) <= epsilon * Math.max(1.0, Math.abs(a.m02), Math.abs(b.m02)) && Math.abs(a.m03 - b.m03) <= epsilon * Math.max(1.0, Math.abs(a.m03), Math.abs(b.m03)) && Math.abs(a.m04 - b.m04) <= epsilon * Math.max(1.0, Math.abs(a.m04), Math.abs(b.m04)) && Math.abs(a.m05 - b.m05) <= epsilon * Math.max(1.0, Math.abs(a.m05), Math.abs(b.m05)) && Math.abs(a.m06 - b.m06) <= epsilon * Math.max(1.0, Math.abs(a.m06), Math.abs(b.m06)) && Math.abs(a.m07 - b.m07) <= epsilon * Math.max(1.0, Math.abs(a.m07), Math.abs(b.m07)) && Math.abs(a.m08 - b.m08) <= epsilon * Math.max(1.0, Math.abs(a.m08), Math.abs(b.m08)) && Math.abs(a.m09 - b.m09) <= epsilon * Math.max(1.0, Math.abs(a.m09), Math.abs(b.m09)) && Math.abs(a.m10 - b.m10) <= epsilon * Math.max(1.0, Math.abs(a.m10), Math.abs(b.m10)) && Math.abs(a.m11 - b.m11) <= epsilon * Math.max(1.0, Math.abs(a.m11), Math.abs(b.m11)) && Math.abs(a.m12 - b.m12) <= epsilon * Math.max(1.0, Math.abs(a.m12), Math.abs(b.m12)) && Math.abs(a.m13 - b.m13) <= epsilon * Math.max(1.0, Math.abs(a.m13), Math.abs(b.m13)) && Math.abs(a.m14 - b.m14) <= epsilon * Math.max(1.0, Math.abs(a.m14), Math.abs(b.m14)) && Math.abs(a.m15 - b.m15) <= epsilon * Math.max(1.0, Math.abs(a.m15), Math.abs(b.m15));
        };
        function Mat4(m00, m01, m02, m03, m04, m05, m06, m07, m08, m09, m10, m11, m12, m13, m14, m15) {
          var _this;
          if (m00 === void 0) {
            m00 = 1;
          }
          if (m01 === void 0) {
            m01 = 0;
          }
          if (m02 === void 0) {
            m02 = 0;
          }
          if (m03 === void 0) {
            m03 = 0;
          }
          if (m04 === void 0) {
            m04 = 0;
          }
          if (m05 === void 0) {
            m05 = 1;
          }
          if (m06 === void 0) {
            m06 = 0;
          }
          if (m07 === void 0) {
            m07 = 0;
          }
          if (m08 === void 0) {
            m08 = 0;
          }
          if (m09 === void 0) {
            m09 = 0;
          }
          if (m10 === void 0) {
            m10 = 1;
          }
          if (m11 === void 0) {
            m11 = 0;
          }
          if (m12 === void 0) {
            m12 = 0;
          }
          if (m13 === void 0) {
            m13 = 0;
          }
          if (m14 === void 0) {
            m14 = 0;
          }
          if (m15 === void 0) {
            m15 = 1;
          }
          _this = _ValueType.call(this) || this;
          if (typeof m00 === 'object') {
            _this.m00 = m00.m00;
            _this.m01 = m00.m01;
            _this.m02 = m00.m02;
            _this.m03 = m00.m03;
            _this.m04 = m00.m04;
            _this.m05 = m00.m05;
            _this.m06 = m00.m06;
            _this.m07 = m00.m07;
            _this.m08 = m00.m08;
            _this.m09 = m00.m09;
            _this.m10 = m00.m10;
            _this.m11 = m00.m11;
            _this.m12 = m00.m12;
            _this.m13 = m00.m13;
            _this.m14 = m00.m14;
            _this.m15 = m00.m15;
          } else {
            _this.m00 = m00;
            _this.m01 = m01;
            _this.m02 = m02;
            _this.m03 = m03;
            _this.m04 = m04;
            _this.m05 = m05;
            _this.m06 = m06;
            _this.m07 = m07;
            _this.m08 = m08;
            _this.m09 = m09;
            _this.m10 = m10;
            _this.m11 = m11;
            _this.m12 = m12;
            _this.m13 = m13;
            _this.m14 = m14;
            _this.m15 = m15;
          }
          return _this;
        }
        var _proto = Mat4.prototype;
        _proto.clone = function clone() {
          return new Mat4(this.m00, this.m01, this.m02, this.m03, this.m04, this.m05, this.m06, this.m07, this.m08, this.m09, this.m10, this.m11, this.m12, this.m13, this.m14, this.m15);
        };
        _proto.set = function set(m00, m01, m02, m03, m04, m05, m06, m07, m08, m09, m10, m11, m12, m13, m14, m15) {
          if (m00 === void 0) {
            m00 = 1;
          }
          if (m01 === void 0) {
            m01 = 0;
          }
          if (m02 === void 0) {
            m02 = 0;
          }
          if (m03 === void 0) {
            m03 = 0;
          }
          if (m04 === void 0) {
            m04 = 0;
          }
          if (m05 === void 0) {
            m05 = 1;
          }
          if (m06 === void 0) {
            m06 = 0;
          }
          if (m07 === void 0) {
            m07 = 0;
          }
          if (m08 === void 0) {
            m08 = 0;
          }
          if (m09 === void 0) {
            m09 = 0;
          }
          if (m10 === void 0) {
            m10 = 1;
          }
          if (m11 === void 0) {
            m11 = 0;
          }
          if (m12 === void 0) {
            m12 = 0;
          }
          if (m13 === void 0) {
            m13 = 0;
          }
          if (m14 === void 0) {
            m14 = 0;
          }
          if (m15 === void 0) {
            m15 = 1;
          }
          if (typeof m00 === 'object') {
            this.m01 = m00.m01;
            this.m02 = m00.m02;
            this.m03 = m00.m03;
            this.m04 = m00.m04;
            this.m05 = m00.m05;
            this.m06 = m00.m06;
            this.m07 = m00.m07;
            this.m08 = m00.m08;
            this.m09 = m00.m09;
            this.m10 = m00.m10;
            this.m11 = m00.m11;
            this.m12 = m00.m12;
            this.m13 = m00.m13;
            this.m14 = m00.m14;
            this.m15 = m00.m15;
            this.m00 = m00.m00;
          } else {
            this.m01 = m01;
            this.m02 = m02;
            this.m03 = m03;
            this.m04 = m04;
            this.m05 = m05;
            this.m06 = m06;
            this.m07 = m07;
            this.m08 = m08;
            this.m09 = m09;
            this.m10 = m10;
            this.m11 = m11;
            this.m12 = m12;
            this.m13 = m13;
            this.m14 = m14;
            this.m15 = m15;
            this.m00 = m00;
          }
          return this;
        };
        _proto.equals = function equals(other, epsilon) {
          if (epsilon === void 0) {
            epsilon = EPSILON$3;
          }
          var hasInf = Math.abs(this.m00) === Infinity || Math.abs(this.m01) === Infinity || Math.abs(this.m02) === Infinity || Math.abs(this.m03) === Infinity || Math.abs(this.m04) === Infinity || Math.abs(this.m05) === Infinity || Math.abs(this.m06) === Infinity || Math.abs(this.m07) === Infinity || Math.abs(this.m08) === Infinity || Math.abs(this.m09) === Infinity || Math.abs(this.m10) === Infinity || Math.abs(this.m11) === Infinity || Math.abs(this.m12) === Infinity || Math.abs(this.m13) === Infinity || Math.abs(this.m14) === Infinity || Math.abs(this.m15) === Infinity;
          return !hasInf && Math.abs(this.m00 - other.m00) <= epsilon * Math.max(1.0, Math.abs(this.m00), Math.abs(other.m00)) && Math.abs(this.m01 - other.m01) <= epsilon * Math.max(1.0, Math.abs(this.m01), Math.abs(other.m01)) && Math.abs(this.m02 - other.m02) <= epsilon * Math.max(1.0, Math.abs(this.m02), Math.abs(other.m02)) && Math.abs(this.m03 - other.m03) <= epsilon * Math.max(1.0, Math.abs(this.m03), Math.abs(other.m03)) && Math.abs(this.m04 - other.m04) <= epsilon * Math.max(1.0, Math.abs(this.m04), Math.abs(other.m04)) && Math.abs(this.m05 - other.m05) <= epsilon * Math.max(1.0, Math.abs(this.m05), Math.abs(other.m05)) && Math.abs(this.m06 - other.m06) <= epsilon * Math.max(1.0, Math.abs(this.m06), Math.abs(other.m06)) && Math.abs(this.m07 - other.m07) <= epsilon * Math.max(1.0, Math.abs(this.m07), Math.abs(other.m07)) && Math.abs(this.m08 - other.m08) <= epsilon * Math.max(1.0, Math.abs(this.m08), Math.abs(other.m08)) && Math.abs(this.m09 - other.m09) <= epsilon * Math.max(1.0, Math.abs(this.m09), Math.abs(other.m09)) && Math.abs(this.m10 - other.m10) <= epsilon * Math.max(1.0, Math.abs(this.m10), Math.abs(other.m10)) && Math.abs(this.m11 - other.m11) <= epsilon * Math.max(1.0, Math.abs(this.m11), Math.abs(other.m11)) && Math.abs(this.m12 - other.m12) <= epsilon * Math.max(1.0, Math.abs(this.m12), Math.abs(other.m12)) && Math.abs(this.m13 - other.m13) <= epsilon * Math.max(1.0, Math.abs(this.m13), Math.abs(other.m13)) && Math.abs(this.m14 - other.m14) <= epsilon * Math.max(1.0, Math.abs(this.m14), Math.abs(other.m14)) && Math.abs(this.m15 - other.m15) <= epsilon * Math.max(1.0, Math.abs(this.m15), Math.abs(other.m15));
        };
        _proto.strictEquals = function strictEquals(other) {
          return this.m00 === other.m00 && this.m01 === other.m01 && this.m02 === other.m02 && this.m03 === other.m03 && this.m04 === other.m04 && this.m05 === other.m05 && this.m06 === other.m06 && this.m07 === other.m07 && this.m08 === other.m08 && this.m09 === other.m09 && this.m10 === other.m10 && this.m11 === other.m11 && this.m12 === other.m12 && this.m13 === other.m13 && this.m14 === other.m14 && this.m15 === other.m15;
        };
        _proto.toString = function toString() {
          return "[\n" + this.m00 + ", " + this.m01 + ", " + this.m02 + ", " + this.m03 + ",\n" + this.m04 + ", " + this.m05 + ", " + this.m06 + ", " + this.m07 + ",\n" + this.m08 + ", " + this.m09 + ", " + this.m10 + ", " + this.m11 + ",\n" + this.m12 + ", " + this.m13 + ", " + this.m14 + ", " + this.m15 + "\n" + ']';
        };
        _proto.identity = function identity() {
          this.m00 = 1;
          this.m01 = 0;
          this.m02 = 0;
          this.m03 = 0;
          this.m04 = 0;
          this.m05 = 1;
          this.m06 = 0;
          this.m07 = 0;
          this.m08 = 0;
          this.m09 = 0;
          this.m10 = 1;
          this.m11 = 0;
          this.m12 = 0;
          this.m13 = 0;
          this.m14 = 0;
          this.m15 = 1;
          return this;
        };
        _proto.zero = function zero() {
          this.m00 = 0;
          this.m01 = 0;
          this.m02 = 0;
          this.m03 = 0;
          this.m04 = 0;
          this.m05 = 0;
          this.m06 = 0;
          this.m07 = 0;
          this.m08 = 0;
          this.m09 = 0;
          this.m10 = 0;
          this.m11 = 0;
          this.m12 = 0;
          this.m13 = 0;
          this.m14 = 0;
          this.m15 = 0;
          return this;
        };
        _proto.transpose = function transpose() {
          var a01 = this.m01;
          var a02 = this.m02;
          var a03 = this.m03;
          var a12 = this.m06;
          var a13 = this.m07;
          var a23 = this.m11;
          this.m01 = this.m04;
          this.m02 = this.m08;
          this.m03 = this.m12;
          this.m04 = a01;
          this.m06 = this.m09;
          this.m07 = this.m13;
          this.m08 = a02;
          this.m09 = a12;
          this.m11 = this.m14;
          this.m12 = a03;
          this.m13 = a13;
          this.m14 = a23;
          return this;
        };
        _proto.invert = function invert() {
          var a00 = this.m00;
          var a01 = this.m01;
          var a02 = this.m02;
          var a03 = this.m03;
          var a10 = this.m04;
          var a11 = this.m05;
          var a12 = this.m06;
          var a13 = this.m07;
          var a20 = this.m08;
          var a21 = this.m09;
          var a22 = this.m10;
          var a23 = this.m11;
          var a30 = this.m12;
          var a31 = this.m13;
          var a32 = this.m14;
          var a33 = this.m15;
          var b00 = a00 * a11 - a01 * a10;
          var b01 = a00 * a12 - a02 * a10;
          var b02 = a00 * a13 - a03 * a10;
          var b03 = a01 * a12 - a02 * a11;
          var b04 = a01 * a13 - a03 * a11;
          var b05 = a02 * a13 - a03 * a12;
          var b06 = a20 * a31 - a21 * a30;
          var b07 = a20 * a32 - a22 * a30;
          var b08 = a20 * a33 - a23 * a30;
          var b09 = a21 * a32 - a22 * a31;
          var b10 = a21 * a33 - a23 * a31;
          var b11 = a22 * a33 - a23 * a32;
          var det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;
          if (det === 0) {
            this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
            return this;
          }
          det = 1.0 / det;
          this.m00 = (a11 * b11 - a12 * b10 + a13 * b09) * det;
          this.m01 = (a02 * b10 - a01 * b11 - a03 * b09) * det;
          this.m02 = (a31 * b05 - a32 * b04 + a33 * b03) * det;
          this.m03 = (a22 * b04 - a21 * b05 - a23 * b03) * det;
          this.m04 = (a12 * b08 - a10 * b11 - a13 * b07) * det;
          this.m05 = (a00 * b11 - a02 * b08 + a03 * b07) * det;
          this.m06 = (a32 * b02 - a30 * b05 - a33 * b01) * det;
          this.m07 = (a20 * b05 - a22 * b02 + a23 * b01) * det;
          this.m08 = (a10 * b10 - a11 * b08 + a13 * b06) * det;
          this.m09 = (a01 * b08 - a00 * b10 - a03 * b06) * det;
          this.m10 = (a30 * b04 - a31 * b02 + a33 * b00) * det;
          this.m11 = (a21 * b02 - a20 * b04 - a23 * b00) * det;
          this.m12 = (a11 * b07 - a10 * b09 - a12 * b06) * det;
          this.m13 = (a00 * b09 - a01 * b07 + a02 * b06) * det;
          this.m14 = (a31 * b01 - a30 * b03 - a32 * b00) * det;
          this.m15 = (a20 * b03 - a21 * b01 + a22 * b00) * det;
          return this;
        };
        _proto.determinant = function determinant() {
          var a00 = this.m00;
          var a01 = this.m01;
          var a02 = this.m02;
          var a03 = this.m03;
          var a10 = this.m04;
          var a11 = this.m05;
          var a12 = this.m06;
          var a13 = this.m07;
          var a20 = this.m08;
          var a21 = this.m09;
          var a22 = this.m10;
          var a23 = this.m11;
          var a30 = this.m12;
          var a31 = this.m13;
          var a32 = this.m14;
          var a33 = this.m15;
          var b00 = a00 * a11 - a01 * a10;
          var b01 = a00 * a12 - a02 * a10;
          var b02 = a00 * a13 - a03 * a10;
          var b03 = a01 * a12 - a02 * a11;
          var b04 = a01 * a13 - a03 * a11;
          var b05 = a02 * a13 - a03 * a12;
          var b06 = a20 * a31 - a21 * a30;
          var b07 = a20 * a32 - a22 * a30;
          var b08 = a20 * a33 - a23 * a30;
          var b09 = a21 * a32 - a22 * a31;
          var b10 = a21 * a33 - a23 * a31;
          var b11 = a22 * a33 - a23 * a32;
          return b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;
        };
        _proto.add = function add(mat) {
          this.m00 += mat.m00;
          this.m01 += mat.m01;
          this.m02 += mat.m02;
          this.m03 += mat.m03;
          this.m04 += mat.m04;
          this.m05 += mat.m05;
          this.m06 += mat.m06;
          this.m07 += mat.m07;
          this.m08 += mat.m08;
          this.m09 += mat.m09;
          this.m10 += mat.m10;
          this.m11 += mat.m11;
          this.m12 += mat.m12;
          this.m13 += mat.m13;
          this.m14 += mat.m14;
          this.m15 += mat.m15;
          return this;
        };
        _proto.subtract = function subtract(mat) {
          this.m00 -= mat.m00;
          this.m01 -= mat.m01;
          this.m02 -= mat.m02;
          this.m03 -= mat.m03;
          this.m04 -= mat.m04;
          this.m05 -= mat.m05;
          this.m06 -= mat.m06;
          this.m07 -= mat.m07;
          this.m08 -= mat.m08;
          this.m09 -= mat.m09;
          this.m10 -= mat.m10;
          this.m11 -= mat.m11;
          this.m12 -= mat.m12;
          this.m13 -= mat.m13;
          this.m14 -= mat.m14;
          this.m15 -= mat.m15;
          return this;
        };
        _proto.multiply = function multiply(mat) {
          var a00 = this.m00;
          var a01 = this.m01;
          var a02 = this.m02;
          var a03 = this.m03;
          var a10 = this.m04;
          var a11 = this.m05;
          var a12 = this.m06;
          var a13 = this.m07;
          var a20 = this.m08;
          var a21 = this.m09;
          var a22 = this.m10;
          var a23 = this.m11;
          var a30 = this.m12;
          var a31 = this.m13;
          var a32 = this.m14;
          var a33 = this.m15;
          var b0 = mat.m00;
          var b1 = mat.m01;
          var b2 = mat.m02;
          var b3 = mat.m03;
          this.m00 = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30;
          this.m01 = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31;
          this.m02 = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32;
          this.m03 = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33;
          b0 = mat.m04;
          b1 = mat.m05;
          b2 = mat.m06;
          b3 = mat.m07;
          this.m04 = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30;
          this.m05 = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31;
          this.m06 = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32;
          this.m07 = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33;
          b0 = mat.m08;
          b1 = mat.m09;
          b2 = mat.m10;
          b3 = mat.m11;
          this.m08 = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30;
          this.m09 = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31;
          this.m10 = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32;
          this.m11 = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33;
          b0 = mat.m12;
          b1 = mat.m13;
          b2 = mat.m14;
          b3 = mat.m15;
          this.m12 = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30;
          this.m13 = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31;
          this.m14 = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32;
          this.m15 = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33;
          return this;
        };
        _proto.multiplyScalar = function multiplyScalar(scalar) {
          this.m00 *= scalar;
          this.m01 *= scalar;
          this.m02 *= scalar;
          this.m03 *= scalar;
          this.m04 *= scalar;
          this.m05 *= scalar;
          this.m06 *= scalar;
          this.m07 *= scalar;
          this.m08 *= scalar;
          this.m09 *= scalar;
          this.m10 *= scalar;
          this.m11 *= scalar;
          this.m12 *= scalar;
          this.m13 *= scalar;
          this.m14 *= scalar;
          this.m15 *= scalar;
          return this;
        };
        _proto.translate = function translate(vec) {
          this.m12 += vec.x;
          this.m13 += vec.y;
          this.m14 += vec.z;
          return this;
        };
        _proto.transform = function transform(vec) {
          var x = vec.x,
            y = vec.y,
            z = vec.z;
          var a00 = this.m00;
          var a01 = this.m01;
          var a02 = this.m02;
          var a03 = this.m03;
          var a10 = this.m04;
          var a11 = this.m05;
          var a12 = this.m06;
          var a13 = this.m07;
          var a20 = this.m08;
          var a21 = this.m09;
          var a22 = this.m10;
          var a23 = this.m11;
          this.m12 = a00 * x + a10 * y + a20 * z + this.m12;
          this.m13 = a01 * x + a11 * y + a21 * z + this.m13;
          this.m14 = a02 * x + a12 * y + a22 * z + this.m14;
          this.m15 = a03 * x + a13 * y + a23 * z + this.m15;
          return this;
        };
        _proto.scale = function scale(vec) {
          var x = vec.x;
          var y = vec.y;
          var z = vec.z;
          this.m00 *= x;
          this.m01 *= x;
          this.m02 *= x;
          this.m03 *= x;
          this.m04 *= y;
          this.m05 *= y;
          this.m06 *= y;
          this.m07 *= y;
          this.m08 *= z;
          this.m09 *= z;
          this.m10 *= z;
          this.m11 *= z;
          return this;
        };
        _proto.rotate = function rotate(rad, axis) {
          var x = axis.x;
          var y = axis.y;
          var z = axis.z;
          var len = Math.sqrt(x * x + y * y + z * z);
          if (Math.abs(len) < EPSILON$3) {
            return null;
          }
          len = 1 / len;
          x *= len;
          y *= len;
          z *= len;
          var s = Math.sin(rad);
          var c = Math.cos(rad);
          var t = 1 - c;
          var a00 = this.m00;
          var a01 = this.m01;
          var a02 = this.m02;
          var a03 = this.m03;
          var a10 = this.m04;
          var a11 = this.m05;
          var a12 = this.m06;
          var a13 = this.m07;
          var a20 = this.m08;
          var a21 = this.m09;
          var a22 = this.m10;
          var a23 = this.m11;
          var b00 = x * x * t + c;
          var b01 = y * x * t + z * s;
          var b02 = z * x * t - y * s;
          var b10 = x * y * t - z * s;
          var b11 = y * y * t + c;
          var b12 = z * y * t + x * s;
          var b20 = x * z * t + y * s;
          var b21 = y * z * t - x * s;
          var b22 = z * z * t + c;
          this.m00 = a00 * b00 + a10 * b01 + a20 * b02;
          this.m01 = a01 * b00 + a11 * b01 + a21 * b02;
          this.m02 = a02 * b00 + a12 * b01 + a22 * b02;
          this.m03 = a03 * b00 + a13 * b01 + a23 * b02;
          this.m04 = a00 * b10 + a10 * b11 + a20 * b12;
          this.m05 = a01 * b10 + a11 * b11 + a21 * b12;
          this.m06 = a02 * b10 + a12 * b11 + a22 * b12;
          this.m07 = a03 * b10 + a13 * b11 + a23 * b12;
          this.m08 = a00 * b20 + a10 * b21 + a20 * b22;
          this.m09 = a01 * b20 + a11 * b21 + a21 * b22;
          this.m10 = a02 * b20 + a12 * b21 + a22 * b22;
          this.m11 = a03 * b20 + a13 * b21 + a23 * b22;
          return this;
        };
        _proto.getTranslation = function getTranslation(out) {
          out.x = this.m12;
          out.y = this.m13;
          out.z = this.m14;
          return out;
        };
        _proto.getScale = function getScale(out) {
          var m00 = m3_1$1.m00 = this.m00;
          var m01 = m3_1$1.m01 = this.m01;
          var m02 = m3_1$1.m02 = this.m02;
          var m04 = m3_1$1.m03 = this.m04;
          var m05 = m3_1$1.m04 = this.m05;
          var m06 = m3_1$1.m05 = this.m06;
          var m08 = m3_1$1.m06 = this.m08;
          var m09 = m3_1$1.m07 = this.m09;
          var m10 = m3_1$1.m08 = this.m10;
          out.x = Math.sqrt(m00 * m00 + m01 * m01 + m02 * m02);
          out.y = Math.sqrt(m04 * m04 + m05 * m05 + m06 * m06);
          out.z = Math.sqrt(m08 * m08 + m09 * m09 + m10 * m10);
          if (Mat3.determinant(m3_1$1) < 0) {
            out.x *= -1;
          }
          return out;
        };
        _proto.getRotation = function getRotation(out) {
          var sx = Vec3.set(v3_1$5, this.m00, this.m01, this.m02).length();
          var sy = Vec3.set(v3_1$5, this.m04, this.m05, this.m06).length();
          var sz = Vec3.set(v3_1$5, this.m08, this.m09, this.m10).length();
          m3_1$1.m00 = this.m00 / sx;
          m3_1$1.m01 = this.m01 / sx;
          m3_1$1.m02 = this.m02 / sx;
          m3_1$1.m03 = this.m04 / sy;
          m3_1$1.m04 = this.m05 / sy;
          m3_1$1.m05 = this.m06 / sy;
          m3_1$1.m06 = this.m08 / sz;
          m3_1$1.m07 = this.m09 / sz;
          m3_1$1.m08 = this.m10 / sz;
          var det = Mat3.determinant(m3_1$1);
          if (det < 0) {
            m3_1$1.m00 *= -1;
            m3_1$1.m01 *= -1;
            m3_1$1.m02 *= -1;
          }
          return Quat.fromMat3(out, m3_1$1);
        };
        _proto.fromRTS = function fromRTS(q, v, s) {
          var x = q.x;
          var y = q.y;
          var z = q.z;
          var w = q.w;
          var x2 = x + x;
          var y2 = y + y;
          var z2 = z + z;
          var xx = x * x2;
          var xy = x * y2;
          var xz = x * z2;
          var yy = y * y2;
          var yz = y * z2;
          var zz = z * z2;
          var wx = w * x2;
          var wy = w * y2;
          var wz = w * z2;
          var sx = s.x;
          var sy = s.y;
          var sz = s.z;
          this.m00 = (1 - (yy + zz)) * sx;
          this.m01 = (xy + wz) * sx;
          this.m02 = (xz - wy) * sx;
          this.m03 = 0;
          this.m04 = (xy - wz) * sy;
          this.m05 = (1 - (xx + zz)) * sy;
          this.m06 = (yz + wx) * sy;
          this.m07 = 0;
          this.m08 = (xz + wy) * sz;
          this.m09 = (yz - wx) * sz;
          this.m10 = (1 - (xx + yy)) * sz;
          this.m11 = 0;
          this.m12 = v.x;
          this.m13 = v.y;
          this.m14 = v.z;
          this.m15 = 1;
          return this;
        };
        _proto.fromSRT = function fromSRT(q, v, s) {
          var x = q.x;
          var y = q.y;
          var z = q.z;
          var w = q.w;
          var x2 = x + x;
          var y2 = y + y;
          var z2 = z + z;
          var xx = x * x2;
          var xy = x * y2;
          var xz = x * z2;
          var yy = y * y2;
          var yz = y * z2;
          var zz = z * z2;
          var wx = w * x2;
          var wy = w * y2;
          var wz = w * z2;
          var sx = s.x;
          var sy = s.y;
          var sz = s.z;
          this.m00 = (1 - (yy + zz)) * sx;
          this.m01 = (xy + wz) * sx;
          this.m02 = (xz - wy) * sx;
          this.m03 = 0;
          this.m04 = (xy - wz) * sy;
          this.m05 = (1 - (xx + zz)) * sy;
          this.m06 = (yz + wx) * sy;
          this.m07 = 0;
          this.m08 = (xz + wy) * sz;
          this.m09 = (yz - wx) * sz;
          this.m10 = (1 - (xx + yy)) * sz;
          this.m11 = 0;
          this.m12 = v.x;
          this.m13 = v.y;
          this.m14 = v.z;
          this.m15 = 1;
          return this;
        };
        _proto.fromQuat = function fromQuat(q) {
          var x = q.x;
          var y = q.y;
          var z = q.z;
          var w = q.w;
          var x2 = x + x;
          var y2 = y + y;
          var z2 = z + z;
          var xx = x * x2;
          var yx = y * x2;
          var yy = y * y2;
          var zx = z * x2;
          var zy = z * y2;
          var zz = z * z2;
          var wx = w * x2;
          var wy = w * y2;
          var wz = w * z2;
          this.m00 = 1 - yy - zz;
          this.m01 = yx + wz;
          this.m02 = zx - wy;
          this.m03 = 0;
          this.m04 = yx - wz;
          this.m05 = 1 - xx - zz;
          this.m06 = zy + wx;
          this.m07 = 0;
          this.m08 = zx + wy;
          this.m09 = zy - wx;
          this.m10 = 1 - xx - yy;
          this.m11 = 0;
          this.m12 = 0;
          this.m13 = 0;
          this.m14 = 0;
          this.m15 = 1;
          return this;
        };
        return Mat4;
      }(ValueType));
      _class$37 = Mat4;
      Mat4.IDENTITY = Object.freeze(new _class$37());
      var v3_1$5 = new Vec3();
      var m3_1$1 = new Mat3();
      CCClass.fastDefine('cc.Mat4', Mat4, {
        m00: 1,
        m01: 0,
        m02: 0,
        m03: 0,
        m04: 0,
        m05: 1,
        m06: 0,
        m07: 0,
        m08: 0,
        m09: 0,
        m10: 1,
        m11: 0,
        m12: 0,
        m13: 0,
        m14: 0,
        m15: 1
      });
      legacyCC.Mat4 = Mat4;
      function mat4(m00, m01, m02, m03, m10, m11, m12, m13, m20, m21, m22, m23, m30, m31, m32, m33) {
        return new Mat4(m00, m01, m02, m03, m10, m11, m12, m13, m20, m21, m22, m23, m30, m31, m32, m33);
      }
      legacyCC.mat4 = mat4;

      var _class$36;
      var Vec2 = exports('aG', function (_ValueType) {
        _inheritsLoose(Vec2, _ValueType);
        Vec2.clone = function clone(a) {
          return new Vec2(a.x, a.y);
        };
        Vec2.copy = function copy(out, a) {
          out.x = a.x;
          out.y = a.y;
          return out;
        };
        Vec2.set = function set(out, x, y) {
          out.x = x;
          out.y = y;
          return out;
        };
        Vec2.add = function add(out, a, b) {
          out.x = a.x + b.x;
          out.y = a.y + b.y;
          return out;
        };
        Vec2.subtract = function subtract(out, a, b) {
          out.x = a.x - b.x;
          out.y = a.y - b.y;
          return out;
        };
        Vec2.multiply = function multiply(out, a, b) {
          out.x = a.x * b.x;
          out.y = a.y * b.y;
          return out;
        };
        Vec2.divide = function divide(out, a, b) {
          out.x = a.x / b.x;
          out.y = a.y / b.y;
          return out;
        };
        Vec2.ceil = function ceil(out, a) {
          out.x = Math.ceil(a.x);
          out.y = Math.ceil(a.y);
          return out;
        };
        Vec2.floor = function floor(out, a) {
          out.x = Math.floor(a.x);
          out.y = Math.floor(a.y);
          return out;
        };
        Vec2.min = function min(out, a, b) {
          out.x = Math.min(a.x, b.x);
          out.y = Math.min(a.y, b.y);
          return out;
        };
        Vec2.max = function max(out, a, b) {
          out.x = Math.max(a.x, b.x);
          out.y = Math.max(a.y, b.y);
          return out;
        };
        Vec2.round = function round(out, a) {
          out.x = Math.round(a.x);
          out.y = Math.round(a.y);
          return out;
        };
        Vec2.multiplyScalar = function multiplyScalar(out, a, b) {
          out.x = a.x * b;
          out.y = a.y * b;
          return out;
        };
        Vec2.scaleAndAdd = function scaleAndAdd(out, a, b, scale) {
          out.x = a.x + b.x * scale;
          out.y = a.y + b.y * scale;
          return out;
        };
        Vec2.distance = function distance(a, b) {
          var x = b.x - a.x;
          var y = b.y - a.y;
          return Math.sqrt(x * x + y * y);
        };
        Vec2.squaredDistance = function squaredDistance(a, b) {
          var x = b.x - a.x;
          var y = b.y - a.y;
          return x * x + y * y;
        };
        Vec2.len = function len(a) {
          var x = a.x;
          var y = a.y;
          return Math.sqrt(x * x + y * y);
        };
        Vec2.lengthSqr = function lengthSqr(a) {
          var x = a.x;
          var y = a.y;
          return x * x + y * y;
        };
        Vec2.negate = function negate(out, a) {
          out.x = -a.x;
          out.y = -a.y;
          return out;
        };
        Vec2.inverse = function inverse(out, a) {
          out.x = 1.0 / a.x;
          out.y = 1.0 / a.y;
          return out;
        };
        Vec2.inverseSafe = function inverseSafe(out, a) {
          var x = a.x;
          var y = a.y;
          if (Math.abs(x) < EPSILON$3) {
            out.x = 0;
          } else {
            out.x = 1.0 / x;
          }
          if (Math.abs(y) < EPSILON$3) {
            out.y = 0;
          } else {
            out.y = 1.0 / y;
          }
          return out;
        };
        Vec2.normalize = function normalize(out, a) {
          var x = a.x;
          var y = a.y;
          var len = x * x + y * y;
          if (len > 0) {
            len = 1 / Math.sqrt(len);
            out.x = x * len;
            out.y = y * len;
          } else {
            out.x = 0;
            out.y = 0;
          }
          return out;
        };
        Vec2.dot = function dot(a, b) {
          return a.x * b.x + a.y * b.y;
        };
        Vec2.cross = function cross(out, a, b) {
          if (out instanceof Vec3) {
            out.x = out.y = 0;
            out.z = a.x * b.y - a.y * b.x;
            return out;
          } else {
            return out.x * a.y - out.y * a.x;
          }
        };
        Vec2.lerp = function lerp(out, a, b, t) {
          var x = a.x;
          var y = a.y;
          out.x = x + t * (b.x - x);
          out.y = y + t * (b.y - y);
          return out;
        };
        Vec2.random = function random$1(out, scale) {
          scale = scale || 1.0;
          var r = random() * 2.0 * Math.PI;
          out.x = Math.cos(r) * scale;
          out.y = Math.sin(r) * scale;
          return out;
        };
        Vec2.transformMat3 = function transformMat3(out, a, m) {
          var x = a.x;
          var y = a.y;
          out.x = m.m00 * x + m.m03 * y + m.m06;
          out.y = m.m01 * x + m.m04 * y + m.m07;
          return out;
        };
        Vec2.transformMat4 = function transformMat4(out, a, m) {
          var x = a.x;
          var y = a.y;
          out.x = m.m00 * x + m.m04 * y + m.m12;
          out.y = m.m01 * x + m.m05 * y + m.m13;
          return out;
        };
        Vec2.str = function str(a) {
          return "Vec2(" + a.x + ", " + a.y + ")";
        };
        Vec2.toArray = function toArray(out, v, ofs) {
          if (ofs === void 0) {
            ofs = 0;
          }
          out[ofs + 0] = v.x;
          out[ofs + 1] = v.y;
          return out;
        };
        Vec2.fromArray = function fromArray(out, arr, ofs) {
          if (ofs === void 0) {
            ofs = 0;
          }
          out.x = arr[ofs + 0];
          out.y = arr[ofs + 1];
          return out;
        };
        Vec2.strictEquals = function strictEquals(a, b) {
          return a.x === b.x && a.y === b.y;
        };
        Vec2.equals = function equals(a, b, epsilon) {
          if (epsilon === void 0) {
            epsilon = EPSILON$3;
          }
          return Math.abs(a.x - b.x) <= epsilon * Math.max(1.0, Math.abs(a.x), Math.abs(b.x)) && Math.abs(a.y - b.y) <= epsilon * Math.max(1.0, Math.abs(a.y), Math.abs(b.y));
        };
        Vec2.angle = function angle(a, b) {
          var magSqr1 = a.x * a.x + a.y * a.y;
          var magSqr2 = b.x * b.x + b.y * b.y;
          if (magSqr1 === 0 || magSqr2 === 0) {
            return 0.0;
          }
          var dot = a.x * b.x + a.y * b.y;
          var cosine = dot / Math.sqrt(magSqr1 * magSqr2);
          cosine = clamp$1(cosine, -1.0, 1.0);
          return Math.acos(cosine);
        };
        function Vec2(x, y) {
          var _this;
          _this = _ValueType.call(this) || this;
          if (typeof x === 'object') {
            _this.x = x.x;
            _this.y = x.y;
          } else {
            _this.x = x || 0;
            _this.y = y || 0;
          }
          return _this;
        }
        var _proto = Vec2.prototype;
        _proto.clone = function clone() {
          return new Vec2(this.x, this.y);
        };
        _proto.set = function set(x, y) {
          if (typeof x === 'object') {
            this.x = x.x;
            this.y = x.y;
          } else {
            this.x = x || 0;
            this.y = y || 0;
          }
          return this;
        };
        _proto.equals = function equals(other, epsilon) {
          if (epsilon === void 0) {
            epsilon = EPSILON$3;
          }
          return Math.abs(this.x - other.x) <= epsilon * Math.max(1.0, Math.abs(this.x), Math.abs(other.x)) && Math.abs(this.y - other.y) <= epsilon * Math.max(1.0, Math.abs(this.y), Math.abs(other.y));
        };
        _proto.equals2f = function equals2f(x, y, epsilon) {
          if (epsilon === void 0) {
            epsilon = EPSILON$3;
          }
          return Math.abs(this.x - x) <= epsilon * Math.max(1.0, Math.abs(this.x), Math.abs(x)) && Math.abs(this.y - y) <= epsilon * Math.max(1.0, Math.abs(this.y), Math.abs(y));
        };
        _proto.strictEquals = function strictEquals(other) {
          return other && this.x === other.x && this.y === other.y;
        };
        _proto.strictEquals2f = function strictEquals2f(x, y) {
          return this.x === x && this.y === y;
        };
        _proto.toString = function toString() {
          return "(" + this.x.toFixed(2) + ", " + this.y.toFixed(2) + ")";
        };
        _proto.lerp = function lerp(to, ratio) {
          var x = this.x;
          var y = this.y;
          this.x = x + ratio * (to.x - x);
          this.y = y + ratio * (to.y - y);
          return this;
        };
        _proto.clampf = function clampf(minInclusive, maxInclusive) {
          this.x = clamp$1(this.x, minInclusive.x, maxInclusive.x);
          this.y = clamp$1(this.y, minInclusive.y, maxInclusive.y);
          return this;
        };
        _proto.add = function add(other) {
          this.x += other.x;
          this.y += other.y;
          return this;
        };
        _proto.add2f = function add2f(x, y) {
          this.x += x;
          this.y += y;
          return this;
        };
        _proto.subtract = function subtract(other) {
          this.x -= other.x;
          this.y -= other.y;
          return this;
        };
        _proto.subtract2f = function subtract2f(x, y) {
          this.x -= x;
          this.y -= y;
          return this;
        };
        _proto.multiplyScalar = function multiplyScalar(scalar) {
          if (typeof scalar === 'object') {
            console.warn('should use Vec2.multiply for vector * vector operation');
          }
          this.x *= scalar;
          this.y *= scalar;
          return this;
        };
        _proto.multiply = function multiply(other) {
          if (typeof other !== 'object') {
            console.warn('should use Vec2.scale for vector * scalar operation');
          }
          this.x *= other.x;
          this.y *= other.y;
          return this;
        };
        _proto.multiply2f = function multiply2f(x, y) {
          this.x *= x;
          this.y *= y;
          return this;
        };
        _proto.divide = function divide(other) {
          this.x /= other.x;
          this.y /= other.y;
          return this;
        };
        _proto.divide2f = function divide2f(x, y) {
          this.x /= x;
          this.y /= y;
          return this;
        };
        _proto.negative = function negative() {
          this.x = -this.x;
          this.y = -this.y;
          return this;
        };
        _proto.dot = function dot(other) {
          return this.x * other.x + this.y * other.y;
        };
        _proto.cross = function cross(other) {
          return this.x * other.y - this.y * other.x;
        };
        _proto.length = function length() {
          return Math.sqrt(this.x * this.x + this.y * this.y);
        };
        _proto.lengthSqr = function lengthSqr() {
          return this.x * this.x + this.y * this.y;
        };
        _proto.normalize = function normalize() {
          var x = this.x;
          var y = this.y;
          var len = x * x + y * y;
          if (len > 0) {
            len = 1 / Math.sqrt(len);
            this.x *= len;
            this.y *= len;
          }
          return this;
        };
        _proto.angle = function angle(other) {
          var magSqr1 = this.lengthSqr();
          var magSqr2 = other.lengthSqr();
          if (magSqr1 === 0 || magSqr2 === 0) {
            return 0.0;
          }
          var dot = this.dot(other);
          var cosine = dot / Math.sqrt(magSqr1 * magSqr2);
          cosine = clamp$1(cosine, -1.0, 1.0);
          return Math.acos(cosine);
        };
        _proto.signAngle = function signAngle(other) {
          var angle = this.angle(other);
          return this.cross(other) < 0 ? -angle : angle;
        };
        _proto.rotate = function rotate(radians) {
          var x = this.x;
          var y = this.y;
          var sin = Math.sin(radians);
          var cos = Math.cos(radians);
          this.x = cos * x - sin * y;
          this.y = sin * x + cos * y;
          return this;
        };
        _proto.project = function project(other) {
          var scalar = this.dot(other) / other.dot(other);
          this.x = other.x * scalar;
          this.y = other.y * scalar;
          return this;
        };
        _proto.transformMat4 = function transformMat4(matrix) {
          var x = this.x;
          var y = this.y;
          this.x = matrix.m00 * x + matrix.m04 * y + matrix.m12;
          this.y = matrix.m01 * x + matrix.m05 * y + matrix.m13;
          return this;
        };
        return Vec2;
      }(ValueType));
      _class$36 = Vec2;
      Vec2.ZERO = Object.freeze(new _class$36(0, 0));
      Vec2.ONE = Object.freeze(new _class$36(1, 1));
      Vec2.NEG_ONE = Object.freeze(new _class$36(-1, -1));
      Vec2.UNIT_X = Object.freeze(new _class$36(1, 0));
      Vec2.UNIT_Y = Object.freeze(new _class$36(0, 1));
      CCClass.fastDefine('cc.Vec2', Vec2, {
        x: 0,
        y: 0
      });
      legacyCC.Vec2 = Vec2;
      function v2$1(x, y) {
        return new Vec2(x, y);
      }
      legacyCC.v2 = v2$1;

      var _class$35;
      var Vec4 = exports('aK', function (_ValueType) {
        _inheritsLoose(Vec4, _ValueType);
        Vec4.clone = function clone(a) {
          return new Vec4(a.x, a.y, a.z, a.w);
        };
        Vec4.copy = function copy(out, a) {
          out.x = a.x;
          out.y = a.y;
          out.z = a.z;
          out.w = a.w;
          return out;
        };
        Vec4.set = function set(out, x, y, z, w) {
          out.x = x;
          out.y = y;
          out.z = z;
          out.w = w;
          return out;
        };
        Vec4.fromColor = function fromColor(out, color) {
          out.x = color.r;
          out.y = color.g;
          out.z = color.b;
          out.w = color.a;
          return out;
        };
        Vec4.angle = function angle(a, b) {
          var dx = a.y * b.z - a.z * b.y;
          var dy = a.z * b.x - a.x * b.z;
          var dz = a.x * b.y - a.y * b.x;
          var dotVal = a.x * b.x + a.y * b.y + a.z * b.z;
          return Math.atan2(Math.sqrt(dx * dx + dy * dy + dz * dz), dotVal);
        };
        Vec4.add = function add(out, a, b) {
          out.x = a.x + b.x;
          out.y = a.y + b.y;
          out.z = a.z + b.z;
          out.w = a.w + b.w;
          return out;
        };
        Vec4.subtract = function subtract(out, a, b) {
          out.x = a.x - b.x;
          out.y = a.y - b.y;
          out.z = a.z - b.z;
          out.w = a.w - b.w;
          return out;
        };
        Vec4.multiply = function multiply(out, a, b) {
          out.x = a.x * b.x;
          out.y = a.y * b.y;
          out.z = a.z * b.z;
          out.w = a.w * b.w;
          return out;
        };
        Vec4.divide = function divide(out, a, b) {
          out.x = a.x / b.x;
          out.y = a.y / b.y;
          out.z = a.z / b.z;
          out.w = a.w / b.w;
          return out;
        };
        Vec4.ceil = function ceil(out, a) {
          out.x = Math.ceil(a.x);
          out.y = Math.ceil(a.y);
          out.z = Math.ceil(a.z);
          out.w = Math.ceil(a.w);
          return out;
        };
        Vec4.floor = function floor(out, a) {
          out.x = Math.floor(a.x);
          out.y = Math.floor(a.y);
          out.z = Math.floor(a.z);
          out.w = Math.floor(a.w);
          return out;
        };
        Vec4.min = function min(out, a, b) {
          out.x = Math.min(a.x, b.x);
          out.y = Math.min(a.y, b.y);
          out.z = Math.min(a.z, b.z);
          out.w = Math.min(a.w, b.w);
          return out;
        };
        Vec4.max = function max(out, a, b) {
          out.x = Math.max(a.x, b.x);
          out.y = Math.max(a.y, b.y);
          out.z = Math.max(a.z, b.z);
          out.w = Math.max(a.w, b.w);
          return out;
        };
        Vec4.round = function round(out, a) {
          out.x = Math.round(a.x);
          out.y = Math.round(a.y);
          out.z = Math.round(a.z);
          out.w = Math.round(a.w);
          return out;
        };
        Vec4.multiplyScalar = function multiplyScalar(out, a, b) {
          out.x = a.x * b;
          out.y = a.y * b;
          out.z = a.z * b;
          out.w = a.w * b;
          return out;
        };
        Vec4.scaleAndAdd = function scaleAndAdd(out, a, b, scale) {
          out.x = a.x + b.x * scale;
          out.y = a.y + b.y * scale;
          out.z = a.z + b.z * scale;
          out.w = a.w + b.w * scale;
          return out;
        };
        Vec4.distance = function distance(a, b) {
          var x = b.x - a.x;
          var y = b.y - a.y;
          var z = b.z - a.z;
          var w = b.w - a.w;
          return Math.sqrt(x * x + y * y + z * z + w * w);
        };
        Vec4.squaredDistance = function squaredDistance(a, b) {
          var x = b.x - a.x;
          var y = b.y - a.y;
          var z = b.z - a.z;
          var w = b.w - a.w;
          return x * x + y * y + z * z + w * w;
        };
        Vec4.len = function len(a) {
          var x = a.x;
          var y = a.y;
          var z = a.z;
          var w = a.w;
          return Math.sqrt(x * x + y * y + z * z + w * w);
        };
        Vec4.lengthSqr = function lengthSqr(a) {
          var x = a.x;
          var y = a.y;
          var z = a.z;
          var w = a.w;
          return x * x + y * y + z * z + w * w;
        };
        Vec4.negate = function negate(out, a) {
          out.x = -a.x;
          out.y = -a.y;
          out.z = -a.z;
          out.w = -a.w;
          return out;
        };
        Vec4.inverse = function inverse(out, a) {
          out.x = 1.0 / a.x;
          out.y = 1.0 / a.y;
          out.z = 1.0 / a.z;
          out.w = 1.0 / a.w;
          return out;
        };
        Vec4.inverseSafe = function inverseSafe(out, a) {
          var x = a.x;
          var y = a.y;
          var z = a.z;
          var w = a.w;
          if (Math.abs(x) < EPSILON$3) {
            out.x = 0;
          } else {
            out.x = 1.0 / x;
          }
          if (Math.abs(y) < EPSILON$3) {
            out.y = 0;
          } else {
            out.y = 1.0 / y;
          }
          if (Math.abs(z) < EPSILON$3) {
            out.z = 0;
          } else {
            out.z = 1.0 / z;
          }
          if (Math.abs(w) < EPSILON$3) {
            out.w = 0;
          } else {
            out.w = 1.0 / w;
          }
          return out;
        };
        Vec4.normalize = function normalize(out, a) {
          var x = a.x;
          var y = a.y;
          var z = a.z;
          var w = a.w;
          var len = x * x + y * y + z * z + w * w;
          if (len > 0) {
            len = 1 / Math.sqrt(len);
            out.x = x * len;
            out.y = y * len;
            out.z = z * len;
            out.w = w * len;
          } else {
            out.x = 0;
            out.y = 0;
            out.z = 0;
            out.w = 0;
          }
          return out;
        };
        Vec4.dot = function dot(a, b) {
          return a.x * b.x + a.y * b.y + a.z * b.z + a.w * b.w;
        };
        Vec4.lerp = function lerp(out, a, b, t) {
          out.x = a.x + t * (b.x - a.x);
          out.y = a.y + t * (b.y - a.y);
          out.z = a.z + t * (b.z - a.z);
          out.w = a.w + t * (b.w - a.w);
          return out;
        };
        Vec4.scale = function scale(out, a, b) {
          out.x = a.x * b;
          out.y = a.y * b;
          out.z = a.z * b;
          out.w = a.w * b;
          return out;
        };
        Vec4.random = function random$1(out, scale) {
          scale = scale || 1.0;
          var phi = random() * 2.0 * Math.PI;
          var cosTheta = random() * 2 - 1;
          var sinTheta = Math.sqrt(1 - cosTheta * cosTheta);
          out.x = sinTheta * Math.cos(phi) * scale;
          out.y = sinTheta * Math.sin(phi) * scale;
          out.z = cosTheta * scale;
          out.w = 0;
          return out;
        };
        Vec4.transformMat4 = function transformMat4(out, a, m) {
          var x = a.x;
          var y = a.y;
          var z = a.z;
          var w = a.w;
          out.x = m.m00 * x + m.m04 * y + m.m08 * z + m.m12 * w;
          out.y = m.m01 * x + m.m05 * y + m.m09 * z + m.m13 * w;
          out.z = m.m02 * x + m.m06 * y + m.m10 * z + m.m14 * w;
          out.w = m.m03 * x + m.m07 * y + m.m11 * z + m.m15 * w;
          return out;
        };
        Vec4.transformAffine = function transformAffine(out, v, m) {
          var x = v.x;
          var y = v.y;
          var z = v.z;
          var w = v.w;
          out.x = m.m00 * x + m.m04 * y + m.m08 * z + m.m12 * w;
          out.y = m.m01 * x + m.m05 * y + m.m09 * z + m.m13 * w;
          out.z = m.m02 * x + m.m06 * y + m.m10 * z + m.m14 * w;
          out.w = v.w;
          return out;
        };
        Vec4.transformQuat = function transformQuat(out, a, q) {
          var x = a.x,
            y = a.y,
            z = a.z;
          var _x = q.x;
          var _y = q.y;
          var _z = q.z;
          var _w = q.w;
          var ix = _w * x + _y * z - _z * y;
          var iy = _w * y + _z * x - _x * z;
          var iz = _w * z + _x * y - _y * x;
          var iw = -_x * x - _y * y - _z * z;
          out.x = ix * _w + iw * -_x + iy * -_z - iz * -_y;
          out.y = iy * _w + iw * -_y + iz * -_x - ix * -_z;
          out.z = iz * _w + iw * -_z + ix * -_y - iy * -_x;
          out.w = a.w;
          return out;
        };
        Vec4.toArray = function toArray(out, v, ofs) {
          if (ofs === void 0) {
            ofs = 0;
          }
          out[ofs + 0] = v.x;
          out[ofs + 1] = v.y;
          out[ofs + 2] = v.z;
          out[ofs + 3] = v.w;
          return out;
        };
        Vec4.fromArray = function fromArray(out, arr, ofs) {
          if (ofs === void 0) {
            ofs = 0;
          }
          out.x = arr[ofs + 0];
          out.y = arr[ofs + 1];
          out.z = arr[ofs + 2];
          out.w = arr[ofs + 3];
          return out;
        };
        Vec4.strictEquals = function strictEquals(a, b) {
          return a.x === b.x && a.y === b.y && a.z === b.z && a.w === b.w;
        };
        Vec4.equals = function equals(a, b, epsilon) {
          if (epsilon === void 0) {
            epsilon = EPSILON$3;
          }
          var hasInf = Math.abs(a.x) === Infinity || Math.abs(a.y) === Infinity || Math.abs(a.z) === Infinity || Math.abs(a.w) === Infinity || Math.abs(b.x) === Infinity || Math.abs(b.y) === Infinity || Math.abs(b.z) === Infinity || Math.abs(b.w) === Infinity;
          return !hasInf && Math.abs(a.x - b.x) <= epsilon * Math.max(1.0, Math.abs(a.x), Math.abs(b.x)) && Math.abs(a.y - b.y) <= epsilon * Math.max(1.0, Math.abs(a.y), Math.abs(b.y)) && Math.abs(a.z - b.z) <= epsilon * Math.max(1.0, Math.abs(a.z), Math.abs(b.z)) && Math.abs(a.w - b.w) <= epsilon * Math.max(1.0, Math.abs(a.w), Math.abs(b.w));
        };
        function Vec4(x, y, z, w) {
          var _this;
          _this = _ValueType.call(this) || this;
          if (typeof x === 'object') {
            _this.x = x.x;
            _this.y = x.y;
            _this.z = x.z;
            _this.w = x.w;
          } else {
            _this.x = x || 0;
            _this.y = y || 0;
            _this.z = z || 0;
            _this.w = w || 0;
          }
          return _this;
        }
        var _proto = Vec4.prototype;
        _proto.clone = function clone() {
          return new Vec4(this.x, this.y, this.z, this.w);
        };
        _proto.set = function set(x, y, z, w) {
          if (typeof x === 'object') {
            this.x = x.x;
            this.y = x.y;
            this.z = x.z;
            this.w = x.w;
          } else {
            this.x = x || 0;
            this.y = y || 0;
            this.z = z || 0;
            this.w = w || 0;
          }
          return this;
        };
        _proto.equals = function equals(other, epsilon) {
          if (epsilon === void 0) {
            epsilon = EPSILON$3;
          }
          return Math.abs(this.x - other.x) <= epsilon * Math.max(1.0, Math.abs(this.x), Math.abs(other.x)) && Math.abs(this.y - other.y) <= epsilon * Math.max(1.0, Math.abs(this.y), Math.abs(other.y)) && Math.abs(this.z - other.z) <= epsilon * Math.max(1.0, Math.abs(this.z), Math.abs(other.z)) && Math.abs(this.w - other.w) <= epsilon * Math.max(1.0, Math.abs(this.w), Math.abs(other.w));
        };
        _proto.equals4f = function equals4f(x, y, z, w, epsilon) {
          if (epsilon === void 0) {
            epsilon = EPSILON$3;
          }
          return Math.abs(this.x - x) <= epsilon * Math.max(1.0, Math.abs(this.x), Math.abs(x)) && Math.abs(this.y - y) <= epsilon * Math.max(1.0, Math.abs(this.y), Math.abs(y)) && Math.abs(this.z - z) <= epsilon * Math.max(1.0, Math.abs(this.z), Math.abs(z)) && Math.abs(this.w - w) <= epsilon * Math.max(1.0, Math.abs(this.w), Math.abs(w));
        };
        _proto.strictEquals = function strictEquals(other) {
          return this.x === other.x && this.y === other.y && this.z === other.z && this.w === other.w;
        };
        _proto.strictEquals4f = function strictEquals4f(x, y, z, w) {
          return this.x === x && this.y === y && this.z === z && this.w === w;
        };
        _proto.lerp = function lerp(to, ratio) {
          var x = this.x;
          var y = this.y;
          var z = this.z;
          var w = this.w;
          this.x = x + ratio * (to.x - x);
          this.y = y + ratio * (to.y - y);
          this.z = z + ratio * (to.z - z);
          this.w = w + ratio * (to.w - w);
          return this;
        };
        _proto.toString = function toString() {
          return "(" + this.x.toFixed(2) + ", " + this.y.toFixed(2) + ", " + this.z.toFixed(2) + ", " + this.w.toFixed(2) + ")";
        };
        _proto.clampf = function clampf(minInclusive, maxInclusive) {
          this.x = clamp$1(this.x, minInclusive.x, maxInclusive.x);
          this.y = clamp$1(this.y, minInclusive.y, maxInclusive.y);
          this.z = clamp$1(this.z, minInclusive.z, maxInclusive.z);
          this.w = clamp$1(this.w, minInclusive.w, maxInclusive.w);
          return this;
        };
        _proto.add = function add(other) {
          this.x += other.x;
          this.y += other.y;
          this.z += other.z;
          this.w += other.w;
          return this;
        };
        _proto.add4f = function add4f(x, y, z, w) {
          this.x += x;
          this.y += y;
          this.z += z;
          this.w += w;
          return this;
        };
        _proto.subtract = function subtract(other) {
          this.x -= other.x;
          this.y -= other.y;
          this.z -= other.z;
          this.w -= other.w;
          return this;
        };
        _proto.subtract4f = function subtract4f(x, y, z, w) {
          this.x -= x;
          this.y -= y;
          this.z -= z;
          this.w -= w;
          return this;
        };
        _proto.multiplyScalar = function multiplyScalar(scalar) {
          if (typeof scalar === 'object') {
            console.warn('should use Vec4.multiply for vector * vector operation');
          }
          this.x *= scalar;
          this.y *= scalar;
          this.z *= scalar;
          this.w *= scalar;
          return this;
        };
        _proto.multiply = function multiply(other) {
          if (typeof other !== 'object') {
            console.warn('should use Vec4.scale for vector * scalar operation');
          }
          this.x *= other.x;
          this.y *= other.y;
          this.z *= other.z;
          this.w *= other.w;
          return this;
        };
        _proto.multiply4f = function multiply4f(x, y, z, w) {
          this.x *= x;
          this.y *= y;
          this.z *= z;
          this.w *= w;
          return this;
        };
        _proto.divide = function divide(other) {
          this.x /= other.x;
          this.y /= other.y;
          this.z /= other.z;
          this.w /= other.w;
          return this;
        };
        _proto.divide4f = function divide4f(x, y, z, w) {
          this.x /= x;
          this.y /= y;
          this.z /= z;
          this.w /= w;
          return this;
        };
        _proto.negative = function negative() {
          this.x = -this.x;
          this.y = -this.y;
          this.z = -this.z;
          this.w = -this.w;
          return this;
        };
        _proto.dot = function dot(vector) {
          return this.x * vector.x + this.y * vector.y + this.z * vector.z + this.w * vector.w;
        };
        _proto.cross = function cross(vector) {
          var ax = this.x,
            ay = this.y,
            az = this.z;
          var bx = vector.x,
            by = vector.y,
            bz = vector.z;
          this.x = ay * bz - az * by;
          this.y = az * bx - ax * bz;
          this.z = ax * by - ay * bx;
          return this;
        };
        _proto.length = function length() {
          var x = this.x;
          var y = this.y;
          var z = this.z;
          var w = this.w;
          return Math.sqrt(x * x + y * y + z * z + w * w);
        };
        _proto.lengthSqr = function lengthSqr() {
          var x = this.x;
          var y = this.y;
          var z = this.z;
          var w = this.w;
          return x * x + y * y + z * z + w * w;
        };
        _proto.normalize = function normalize() {
          var x = this.x;
          var y = this.y;
          var z = this.z;
          var w = this.w;
          var len = x * x + y * y + z * z + w * w;
          if (len > 0) {
            len = 1 / Math.sqrt(len);
            this.x = x * len;
            this.y = y * len;
            this.z = z * len;
            this.w = w * len;
          }
          return this;
        };
        _proto.scale = function scale(scalar) {
          this.x *= scalar;
          this.y *= scalar;
          this.z *= scalar;
          this.w *= scalar;
          return this;
        };
        _proto.transformMat4 = function transformMat4(matrix) {
          var x = this.x;
          var y = this.y;
          var z = this.z;
          var w = this.w;
          this.x = matrix.m00 * x + matrix.m04 * y + matrix.m08 * z + matrix.m12 * w;
          this.y = matrix.m01 * x + matrix.m05 * y + matrix.m09 * z + matrix.m13 * w;
          this.z = matrix.m02 * x + matrix.m06 * y + matrix.m10 * z + matrix.m14 * w;
          this.w = matrix.m03 * x + matrix.m07 * y + matrix.m11 * z + matrix.m15 * w;
          return this;
        };
        return Vec4;
      }(ValueType));
      _class$35 = Vec4;
      Vec4.ZERO = Object.freeze(new _class$35(0, 0, 0, 0));
      Vec4.ONE = Object.freeze(new _class$35(1, 1, 1, 1));
      Vec4.NEG_ONE = Object.freeze(new _class$35(-1, -1, -1, -1));
      Vec4.UNIT_X = Object.freeze(new _class$35(1, 0, 0, 0));
      Vec4.UNIT_Y = Object.freeze(new _class$35(0, 1, 0, 0));
      Vec4.UNIT_Z = Object.freeze(new _class$35(0, 0, 1, 0));
      Vec4.UNIT_W = Object.freeze(new _class$35(0, 0, 0, 1));
      CCClass.fastDefine('cc.Vec4', Vec4, {
        x: 0,
        y: 0,
        z: 0,
        w: 0
      });
      legacyCC.Vec4 = Vec4;
      function v4(x, y, z, w) {
        return new Vec4(x, y, z, w);
      }
      legacyCC.v4 = v4;

      var _class$34;
      var toFloat = 1 / 255;
      var Color$1 = exports('aW', function (_ValueType) {
        _inheritsLoose(Color, _ValueType);
        Color.clone = function clone(a) {
          var out = new Color();
          if (a._val) {
            out._val = a._val;
          } else {
            out._val = (a.a << 24 >>> 0) + (a.b << 16) + (a.g << 8) + a.r;
          }
          return out;
        };
        Color.copy = function copy(out, a) {
          out.r = a.r;
          out.g = a.g;
          out.b = a.b;
          out.a = a.a;
          return out;
        };
        Color.set = function set(out, r, g, b, a) {
          out.r = r;
          out.g = g;
          out.b = b;
          out.a = a;
          return out;
        };
        Color.toVec4 = function toVec4(color, out) {
          out = out !== undefined ? out : new Vec4();
          out.x = color.r * toFloat;
          out.y = color.g * toFloat;
          out.z = color.b * toFloat;
          out.w = color.a * toFloat;
          return out;
        };
        Color.fromVec4 = function fromVec4(value, out) {
          out = out === undefined ? new Color() : out;
          out.r = Math.floor(value.x / toFloat);
          out.g = Math.floor(value.y / toFloat);
          out.b = Math.floor(value.z / toFloat);
          out.a = Math.floor(value.w / toFloat);
          return out;
        };
        Color.fromHEX = function fromHEX(out, hexString) {
          hexString = hexString.indexOf('#') === 0 ? hexString.substring(1) : hexString;
          out.r = parseInt(hexString.substr(0, 2), 16) || 0;
          out.g = parseInt(hexString.substr(2, 2), 16) || 0;
          out.b = parseInt(hexString.substr(4, 2), 16) || 0;
          var a = parseInt(hexString.substr(6, 2), 16);
          out.a = !Number.isNaN(a) ? a : 255;
          out._val = (out.a << 24 >>> 0) + (out.b << 16) + (out.g << 8) + out.r;
          return out;
        };
        Color.add = function add(out, a, b) {
          out.r = a.r + b.r;
          out.g = a.g + b.g;
          out.b = a.b + b.b;
          out.a = a.a + b.a;
          return out;
        };
        Color.subtract = function subtract(out, a, b) {
          out.r = a.r - b.r;
          out.g = a.g - b.g;
          out.b = a.b - b.b;
          out.a = a.a - b.a;
          return out;
        };
        Color.multiply = function multiply(out, a, b) {
          out.r = a.r * b.r;
          out.g = a.g * b.g;
          out.b = a.b * b.b;
          out.a = a.a * b.a;
          return out;
        };
        Color.divide = function divide(out, a, b) {
          out.r = a.r / b.r;
          out.g = a.g / b.g;
          out.b = a.b / b.b;
          out.a = a.a / b.a;
          return out;
        };
        Color.scale = function scale(out, a, b) {
          out.r = a.r * b;
          out.g = a.g * b;
          out.b = a.b * b;
          out.a = a.a * b;
          return out;
        };
        Color.lerp = function lerp(out, from, to, ratio) {
          var r = from.r;
          var g = from.g;
          var b = from.b;
          var a = from.a;
          r += (to.r - r) * ratio;
          g += (to.g - g) * ratio;
          b += (to.b - b) * ratio;
          a += (to.a - a) * ratio;
          out._val = Math.floor((a << 24 >>> 0) + (b << 16) + (g << 8) + r);
          return out;
        };
        Color.toArray = function toArray(out, a, ofs) {
          if (ofs === void 0) {
            ofs = 0;
          }
          var scale = a instanceof Color || a.a > 1 ? 1 / 255 : 1;
          out[ofs + 0] = a.r * scale;
          out[ofs + 1] = a.g * scale;
          out[ofs + 2] = a.b * scale;
          out[ofs + 3] = a.a * scale;
          return out;
        };
        Color.fromArray = function fromArray(arr, out, ofs) {
          if (ofs === void 0) {
            ofs = 0;
          }
          out.r = arr[ofs + 0] * 255;
          out.g = arr[ofs + 1] * 255;
          out.b = arr[ofs + 2] * 255;
          out.a = arr[ofs + 3] * 255;
          return out;
        };
        Color.fromUint32 = function fromUint32(out, uint32) {
          out._val = uint32;
          return out;
        };
        Color.toUint32 = function toUint32(color) {
          return color._val;
        };
        Color.strictEquals = function strictEquals(a, b) {
          return a.r === b.r && a.g === b.g && a.b === b.b && a.a === b.a;
        };
        Color.equals = function equals(a, b, epsilon) {
          if (epsilon === void 0) {
            epsilon = EPSILON$3;
          }
          var hasInf = Math.abs(a.r) === Infinity || Math.abs(a.g) === Infinity || Math.abs(a.b) === Infinity || Math.abs(a.a) === Infinity;
          return !hasInf && Math.abs(a.r - b.r) <= epsilon * Math.max(1.0, Math.abs(a.r), Math.abs(b.r)) && Math.abs(a.g - b.g) <= epsilon * Math.max(1.0, Math.abs(a.g), Math.abs(b.g)) && Math.abs(a.b - b.b) <= epsilon * Math.max(1.0, Math.abs(a.b), Math.abs(b.b)) && Math.abs(a.a - b.a) <= epsilon * Math.max(1.0, Math.abs(a.a), Math.abs(b.a));
        };
        Color.hex = function hex(a) {
          return (a.r * 255 << 24 | a.g * 255 << 16 | a.b * 255 << 8 | a.a * 255) >>> 0;
        };
        function Color(r, g, b, a) {
          var _this;
          _this = _ValueType.call(this) || this;
          _this._val = 0;
          if (typeof r === 'string') {
            _this.fromHEX(r);
          } else if (g !== undefined) {
            _this.set(r, g, b, a);
          } else {
            _this.set(r);
          }
          return _this;
        }
        var _proto = Color.prototype;
        _proto.clone = function clone() {
          var ret = new Color();
          ret._val = this._val;
          return ret;
        };
        _proto.equals = function equals(other) {
          return other && this._val === other._val;
        };
        _proto.lerp = function lerp(to, ratio) {
          var r = this.r;
          var g = this.g;
          var b = this.b;
          var a = this.a;
          r += (to.r - r) * ratio;
          g += (to.g - g) * ratio;
          b += (to.b - b) * ratio;
          a += (to.a - a) * ratio;
          this._val = Math.floor((a << 24 >>> 0) + (b << 16) + (g << 8) + r);
          return this;
        };
        _proto.toString = function toString() {
          return "rgba(" + this.r.toFixed() + ", " + this.g.toFixed() + ", " + this.b.toFixed() + ", " + this.a.toFixed() + ")";
        };
        _proto.toCSS = function toCSS(opt) {
          if (opt === void 0) {
            opt = 'rgba';
          }
          if (opt === 'rgba') {
            return "rgba(" + this.r + "," + this.g + "," + this.b + "," + (this.a * toFloat).toFixed(2) + ")";
          } else if (opt === 'rgb') {
            return "rgb(" + this.r + "," + this.g + "," + this.b + ")";
          } else {
            return "#" + this.toHEX(opt);
          }
        };
        _proto.fromHEX = function fromHEX(hexString) {
          hexString = hexString.indexOf('#') === 0 ? hexString.substring(1) : hexString;
          var r = parseInt(hexString.substr(0, 2), 16) || 0;
          var g = parseInt(hexString.substr(2, 2), 16) || 0;
          var b = parseInt(hexString.substr(4, 2), 16) || 0;
          var a = parseInt(hexString.substr(6, 2), 16);
          a = !Number.isNaN(a) ? a : 255;
          this._val = (a << 24 >>> 0) + (b << 16) + (g << 8) + (r | 0);
          return this;
        };
        _proto.toHEX = function toHEX(fmt) {
          if (fmt === void 0) {
            fmt = '#rrggbb';
          }
          var prefix = '0';
          var hex = [(this.r < 16 ? prefix : '') + this.r.toString(16), (this.g < 16 ? prefix : '') + this.g.toString(16), (this.b < 16 ? prefix : '') + this.b.toString(16)];
          if (fmt === '#rgb') {
            hex[0] = hex[0][0];
            hex[1] = hex[1][0];
            hex[2] = hex[2][0];
          } else if (fmt === '#rrggbbaa') {
            hex.push((this.a < 16 ? prefix : '') + this.a.toString(16));
          }
          return hex.join('');
        };
        _proto.toRGBValue = function toRGBValue() {
          return this._val & 0x00ffffff;
        };
        _proto.fromHSV = function fromHSV(h, s, v) {
          var r = 0;
          var g = 0;
          var b = 0;
          if (s === 0) {
            r = g = b = v;
          } else if (v === 0) {
            r = g = b = 0;
          } else {
            if (h === 1) {
              h = 0;
            }
            h *= 6;
            var i = Math.floor(h);
            var f = h - i;
            var p = v * (1 - s);
            var q = v * (1 - s * f);
            var t = v * (1 - s * (1 - f));
            switch (i) {
              default:
                assertIsTrue(false);
              case 0:
                r = v;
                g = t;
                b = p;
                break;
              case 1:
                r = q;
                g = v;
                b = p;
                break;
              case 2:
                r = p;
                g = v;
                b = t;
                break;
              case 3:
                r = p;
                g = q;
                b = v;
                break;
              case 4:
                r = t;
                g = p;
                b = v;
                break;
              case 5:
                r = v;
                g = p;
                b = q;
                break;
            }
          }
          r *= 255;
          g *= 255;
          b *= 255;
          this._val = (this.a << 24 >>> 0) + (b << 16) + (g << 8) + (r | 0);
          return this;
        };
        _proto.toHSV = function toHSV() {
          var r = this.r * toFloat;
          var g = this.g * toFloat;
          var b = this.b * toFloat;
          var hsv = {
            h: 0,
            s: 0,
            v: 0
          };
          var max = Math.max(r, g, b);
          var min = Math.min(r, g, b);
          var delta = 0;
          hsv.v = max;
          hsv.s = max ? (max - min) / max : 0;
          if (!hsv.s) {
            hsv.h = 0;
          } else {
            delta = max - min;
            if (r === max) {
              hsv.h = (g - b) / delta;
            } else if (g === max) {
              hsv.h = 2 + (b - r) / delta;
            } else {
              hsv.h = 4 + (r - g) / delta;
            }
            hsv.h /= 6;
            if (hsv.h < 0) {
              hsv.h += 1.0;
            }
          }
          return hsv;
        };
        _proto.set = function set(r, g, b, a) {
          if (typeof r === 'object') {
            if (r._val != null) {
              this._val = r._val;
            } else {
              g = r.g || 0;
              b = r.b || 0;
              a = typeof r.a === 'number' ? r.a : 255;
              r = r.r || 0;
              this._val = (a << 24 >>> 0) + (b << 16) + (g << 8) + (r | 0);
            }
          } else {
            r = r || 0;
            g = g || 0;
            b = b || 0;
            a = typeof a === 'number' ? a : 255;
            this._val = (a << 24 >>> 0) + (b << 16) + (g << 8) + (r | 0);
          }
          return this;
        };
        _proto.multiply = function multiply(other) {
          var r = (this._val & 0x000000ff) * other.r >> 8;
          var g = (this._val & 0x0000ff00) * other.g >> 8;
          var b = (this._val & 0x00ff0000) * other.b >> 8;
          var a = ((this._val & 0xff000000) >>> 8) * other.a;
          this._val = a & 0xff000000 | b & 0x00ff0000 | g & 0x0000ff00 | r & 0x000000ff;
          return this;
        };
        _proto._set_r_unsafe = function _set_r_unsafe(red) {
          this._val = (this._val & 0xffffff00 | red) >>> 0;
          return this;
        };
        _proto._set_g_unsafe = function _set_g_unsafe(green) {
          this._val = (this._val & 0xffff00ff | green << 8) >>> 0;
          return this;
        };
        _proto._set_b_unsafe = function _set_b_unsafe(blue) {
          this._val = (this._val & 0xff00ffff | blue << 16) >>> 0;
          return this;
        };
        _proto._set_a_unsafe = function _set_a_unsafe(alpha) {
          this._val = (this._val & 0x00ffffff | alpha << 24) >>> 0;
          return this;
        };
        _createClass(Color, [{
          key: "r",
          get: function get() {
            return this._val & 0x000000ff;
          },
          set: function set(red) {
            red = ~~clamp$1(red, 0, 255);
            this._val = (this._val & 0xffffff00 | red) >>> 0;
          }
        }, {
          key: "g",
          get: function get() {
            return (this._val & 0x0000ff00) >> 8;
          },
          set: function set(green) {
            green = ~~clamp$1(green, 0, 255);
            this._val = (this._val & 0xffff00ff | green << 8) >>> 0;
          }
        }, {
          key: "b",
          get: function get() {
            return (this._val & 0x00ff0000) >> 16;
          },
          set: function set(blue) {
            blue = ~~clamp$1(blue, 0, 255);
            this._val = (this._val & 0xff00ffff | blue << 16) >>> 0;
          }
        }, {
          key: "a",
          get: function get() {
            return (this._val & 0xff000000) >>> 24;
          },
          set: function set(alpha) {
            alpha = ~~clamp$1(alpha, 0, 255);
            this._val = (this._val & 0x00ffffff | alpha << 24) >>> 0;
          }
        }, {
          key: "x",
          get: function get() {
            return this.r * toFloat;
          },
          set: function set(value) {
            this.r = value * 255;
          }
        }, {
          key: "y",
          get: function get() {
            return this.g * toFloat;
          },
          set: function set(value) {
            this.g = value * 255;
          }
        }, {
          key: "z",
          get: function get() {
            return this.b * toFloat;
          },
          set: function set(value) {
            this.b = value * 255;
          }
        }, {
          key: "w",
          get: function get() {
            return this.a * toFloat;
          },
          set: function set(value) {
            this.a = value * 255;
          }
        }]);
        return Color;
      }(ValueType));
      _class$34 = Color$1;
      Color$1.WHITE = Object.freeze(new _class$34(255, 255, 255, 255));
      Color$1.GRAY = Object.freeze(new _class$34(127, 127, 127, 255));
      Color$1.BLACK = Object.freeze(new _class$34(0, 0, 0, 255));
      Color$1.TRANSPARENT = Object.freeze(new _class$34(0, 0, 0, 0));
      Color$1.RED = Object.freeze(new _class$34(255, 0, 0, 255));
      Color$1.GREEN = Object.freeze(new _class$34(0, 255, 0, 255));
      Color$1.BLUE = Object.freeze(new _class$34(0, 0, 255, 255));
      Color$1.CYAN = Object.freeze(new _class$34(0, 255, 255, 255));
      Color$1.MAGENTA = Object.freeze(new _class$34(255, 0, 255, 255));
      Color$1.YELLOW = Object.freeze(new _class$34(255, 255, 0, 255));
      CCClass.fastDefine('cc.Color', Color$1, {
        r: 0,
        g: 0,
        b: 0,
        a: 255
      });
      legacyCC.Color = Color$1;
      function color(r, g, b, a) {
        return new Color$1(r, g, b, a);
      }
      legacyCC.color = color;
      function clampVec3(val, min, max) {
        if (min > max) {
          var temp = min;
          min = max;
          max = temp;
        }
        return val < min ? min : val > max ? max : val;
      }
      function floorVec3(val) {
        var temp = val.clone();
        temp.x = Math.floor(val.x);
        temp.y = Math.floor(val.y);
        temp.z = Math.floor(val.z);
        return temp;
      }
      function stepVec3(a, b) {
        if (a < b) {
          return b;
        } else {
          return a;
        }
      }
      function packRGBE(rgb) {
        var maxComp = Math.max(Math.max(rgb.x, rgb.y), rgb.z);
        var e = 128.0;
        if (maxComp > 0.0001) {
          e = Math.log(maxComp) / Math.log(1.1);
          e = Math.ceil(e);
          e = clamp$1(e + 128.0, 0.0, 255.0);
        }
        var sc = 1.0 / Math.pow(1.1, e - 128.0);
        var encode = clampVec3(rgb.multiplyScalar(sc), new Vec3(0.0, 0.0, 0.0), new Vec3(1.0, 1.0, 1.0));
        encode.multiplyScalar(255.0);
        var encode_rounded = floorVec3(encode).add(stepVec3(encode.subtract(floorVec3(encode)), new Vec3(0.5, 0.5, 0.5)));
        return new Vec4(encode_rounded.x / 255.0, encode_rounded.y / 255.0, encode_rounded.z / 255.0, e / 255.0);
      }

      var MathType;
      (function (MathType) {
        MathType[MathType["VEC2"] = 0] = "VEC2";
        MathType[MathType["VEC3"] = 1] = "VEC3";
        MathType[MathType["VEC4"] = 2] = "VEC4";
        MathType[MathType["QUATERNION"] = 3] = "QUATERNION";
        MathType[MathType["MAT3"] = 4] = "MAT3";
        MathType[MathType["MAT4"] = 5] = "MAT4";
        MathType[MathType["SIZE"] = 6] = "SIZE";
        MathType[MathType["RECT"] = 7] = "RECT";
        MathType[MathType["COLOR"] = 8] = "COLOR";
      })(MathType || (MathType = {}));

      var AffineTransform = exports('aR', function () {
        AffineTransform.identity = function identity() {
          return new AffineTransform();
        };
        AffineTransform.clone = function clone(affineTransform) {
          return new AffineTransform(affineTransform.a, affineTransform.b, affineTransform.c, affineTransform.d, affineTransform.tx, affineTransform.ty);
        };
        AffineTransform.concat = function concat(out, t1, t2) {
          var a = t1.a;
          var b = t1.b;
          var c = t1.c;
          var d = t1.d;
          var tx = t1.tx;
          var ty = t1.ty;
          out.a = a * t2.a + b * t2.c;
          out.b = a * t2.b + b * t2.d;
          out.c = c * t2.a + d * t2.c;
          out.d = c * t2.b + d * t2.d;
          out.tx = tx * t2.a + ty * t2.c + t2.tx;
          out.ty = tx * t2.b + ty * t2.d + t2.ty;
        };
        AffineTransform.invert = function invert(out, t) {
          var determinant = 1 / (t.a * t.d - t.b * t.c);
          out.a = determinant * t.d;
          out.b = -determinant * t.b;
          out.c = -determinant * t.c;
          out.d = determinant * t.a;
          out.tx = determinant * (t.c * t.ty - t.d * t.tx);
          out.ty = determinant * (t.b * t.tx - t.a * t.ty);
        };
        AffineTransform.fromMat4 = function fromMat4(out, mat) {
          out.a = mat.m00;
          out.b = mat.m01;
          out.c = mat.m04;
          out.d = mat.m05;
          out.tx = mat.m12;
          out.ty = mat.m13;
        };
        AffineTransform.transformVec2 = function transformVec2(out, point, transOrY, t) {
          var x;
          var y;
          if (!t) {
            t = transOrY;
            x = point.x;
            y = point.y;
          } else {
            x = point;
            y = transOrY;
          }
          out.x = t.a * x + t.c * y + t.tx;
          out.y = t.b * x + t.d * y + t.ty;
        };
        AffineTransform.transformSize = function transformSize(out, size, t) {
          out.width = t.a * size.width + t.c * size.height;
          out.height = t.b * size.width + t.d * size.height;
        };
        AffineTransform.transformRect = function transformRect(out, rect, t) {
          var or = rect.x + rect.width;
          var ot = rect.y + rect.height;
          var lbx = t.a * rect.x + t.c * rect.y + t.tx;
          var lby = t.b * rect.x + t.d * rect.y + t.ty;
          var rbx = t.a * or + t.c * rect.y + t.tx;
          var rby = t.b * or + t.d * rect.y + t.ty;
          var ltx = t.a * rect.x + t.c * ot + t.tx;
          var lty = t.b * rect.x + t.d * ot + t.ty;
          var rtx = t.a * or + t.c * ot + t.tx;
          var rty = t.b * or + t.d * ot + t.ty;
          var minX = Math.min(lbx, rbx, ltx, rtx);
          var maxX = Math.max(lbx, rbx, ltx, rtx);
          var minY = Math.min(lby, rby, lty, rty);
          var maxY = Math.max(lby, rby, lty, rty);
          out.x = minX;
          out.y = minY;
          out.width = maxX - minX;
          out.height = maxY - minY;
        };
        AffineTransform.transformObb = function transformObb(out_bl, out_tl, out_tr, out_br, rect, anAffineTransform, flipY) {
          if (flipY === void 0) {
            flipY = true;
          }
          var tx = anAffineTransform.a * rect.x + anAffineTransform.c * rect.y + anAffineTransform.tx;
          var ty = anAffineTransform.b * rect.x + anAffineTransform.d * rect.y + anAffineTransform.ty;
          var xa = anAffineTransform.a * rect.width;
          var xb = anAffineTransform.b * rect.width;
          var yc = anAffineTransform.c * rect.height;
          var yd = anAffineTransform.d * rect.height;
          if (flipY) {
            out_tl.x = tx;
            out_tl.y = ty;
            out_tr.x = xa + tx;
            out_tr.y = xb + ty;
            out_bl.x = yc + tx;
            out_bl.y = yd + ty;
            out_br.x = xa + yc + tx;
            out_br.y = xb + yd + ty;
          } else {
            out_bl.x = tx;
            out_bl.y = ty;
            out_br.x = xa + tx;
            out_br.y = xb + ty;
            out_tl.x = yc + tx;
            out_tl.y = yd + ty;
            out_tr.x = xa + yc + tx;
            out_tr.y = xb + yd + ty;
          }
        };
        function AffineTransform(a, b, c, d, tx, ty) {
          if (a === void 0) {
            a = 1;
          }
          if (b === void 0) {
            b = 0;
          }
          if (c === void 0) {
            c = 0;
          }
          if (d === void 0) {
            d = 1;
          }
          if (tx === void 0) {
            tx = 0;
          }
          if (ty === void 0) {
            ty = 0;
          }
          this.a = a;
          this.b = b;
          this.c = c;
          this.d = d;
          this.tx = tx;
          this.ty = ty;
        }
        return AffineTransform;
      }());
      legacyCC.AffineTransform = AffineTransform;

      var _class$33;
      var Size$1 = exports('aS', function (_ValueType) {
        _inheritsLoose(Size, _ValueType);
        Size.lerp = function lerp(out, from, to, ratio) {
          out.width = from.width + (to.width - from.width) * ratio;
          out.height = from.height + (to.height - from.height) * ratio;
          return out;
        };
        Size.equals = function equals(a, b) {
          return a.width === b.width && a.height === b.height;
        };
        function Size(width, height) {
          var _this;
          _this = _ValueType.call(this) || this;
          if (typeof width === 'object') {
            _this.width = width.width;
            _this.height = width.height;
          } else {
            _this.width = width || 0;
            _this.height = height || 0;
          }
          return _this;
        }
        var _proto = Size.prototype;
        _proto.clone = function clone() {
          return new Size(this.width, this.height);
        };
        _proto.set = function set(width, height) {
          if (typeof width === 'object') {
            this.height = width.height;
            this.width = width.width;
          } else {
            this.width = width || 0;
            this.height = height || 0;
          }
          return this;
        };
        _proto.equals = function equals(other) {
          return this.width === other.width && this.height === other.height;
        };
        _proto.lerp = function lerp(to, ratio) {
          this.width += (to.width - this.width) * ratio;
          this.height += (to.height - this.height) * ratio;
          return this;
        };
        _proto.toString = function toString() {
          return "(" + this.width.toFixed(2) + ", " + this.height.toFixed(2) + ")";
        };
        _createClass(Size, [{
          key: "x",
          get: function get() {
            return this.width;
          },
          set: function set(val) {
            this.width = val;
          }
        }, {
          key: "y",
          get: function get() {
            return this.height;
          },
          set: function set(val) {
            this.height = val;
          }
        }]);
        return Size;
      }(ValueType));
      _class$33 = Size$1;
      Size$1.ZERO = Object.freeze(new _class$33(0, 0));
      Size$1.ONE = Object.freeze(new _class$33(1, 1));
      CCClass.fastDefine('cc.Size', Size$1, {
        width: 0,
        height: 0
      });
      function size(width, height) {
        if (width === void 0) {
          width = 0;
        }
        if (height === void 0) {
          height = 0;
        }
        return new Size$1(width, height);
      }
      legacyCC.size = size;
      legacyCC.Size = Size$1;

      var Rect$1 = exports('aU', function (_ValueType) {
        _inheritsLoose(Rect, _ValueType);
        Rect.fromMinMax = function fromMinMax(out, v1, v2) {
          var minX = Math.min(v1.x, v2.x);
          var minY = Math.min(v1.y, v2.y);
          var maxX = Math.max(v1.x, v2.x);
          var maxY = Math.max(v1.y, v2.y);
          out.x = minX;
          out.y = minY;
          out.width = maxX - minX;
          out.height = maxY - minY;
          return out;
        };
        Rect.lerp = function lerp(out, from, to, ratio) {
          var x = from.x;
          var y = from.y;
          var w = from.width;
          var h = from.height;
          out.x = x + (to.x - x) * ratio;
          out.y = y + (to.y - y) * ratio;
          out.width = w + (to.width - w) * ratio;
          out.height = h + (to.height - h) * ratio;
          return out;
        };
        Rect.intersection = function intersection(out, one, other) {
          var axMin = one.x;
          var ayMin = one.y;
          var axMax = one.x + one.width;
          var ayMax = one.y + one.height;
          var bxMin = other.x;
          var byMin = other.y;
          var bxMax = other.x + other.width;
          var byMax = other.y + other.height;
          out.x = Math.max(axMin, bxMin);
          out.y = Math.max(ayMin, byMin);
          out.width = Math.min(axMax, bxMax) - out.x;
          out.height = Math.min(ayMax, byMax) - out.y;
          return out;
        };
        Rect.union = function union(out, one, other) {
          var x = one.x;
          var y = one.y;
          var w = one.width;
          var h = one.height;
          var bx = other.x;
          var by = other.y;
          var bw = other.width;
          var bh = other.height;
          out.x = Math.min(x, bx);
          out.y = Math.min(y, by);
          out.width = Math.max(x + w, bx + bw) - out.x;
          out.height = Math.max(y + h, by + bh) - out.y;
          return out;
        };
        Rect.equals = function equals(a, b) {
          return a.x === b.x && a.y === b.y && a.width === b.width && a.height === b.height;
        };
        function Rect(x, y, width, height) {
          var _this;
          _this = _ValueType.call(this) || this;
          if (typeof x === 'object') {
            _this.x = x.x;
            _this.y = x.y;
            _this.width = x.width;
            _this.height = x.height;
          } else {
            _this.x = x || 0;
            _this.y = y || 0;
            _this.width = width || 0;
            _this.height = height || 0;
          }
          return _this;
        }
        var _proto = Rect.prototype;
        _proto.clone = function clone() {
          return new Rect(this.x, this.y, this.width, this.height);
        };
        _proto.set = function set(x, y, width, height) {
          if (typeof x === 'object') {
            this.x = x.x;
            this.y = x.y;
            this.width = x.width;
            this.height = x.height;
          } else {
            this.x = x || 0;
            this.y = y || 0;
            this.width = width || 0;
            this.height = height || 0;
          }
          return this;
        };
        _proto.equals = function equals(other) {
          return this.x === other.x && this.y === other.y && this.width === other.width && this.height === other.height;
        };
        _proto.lerp = function lerp(to, ratio) {
          var x = this.x;
          var y = this.y;
          var w = this.width;
          var h = this.height;
          this.x = x + (to.x - x) * ratio;
          this.y = y + (to.y - y) * ratio;
          this.width = w + (to.width - w) * ratio;
          this.height = h + (to.height - h) * ratio;
          return this;
        };
        _proto.toString = function toString() {
          return "(" + this.x.toFixed(2) + ", " + this.y.toFixed(2) + ", " + this.width.toFixed(2) + ", " + this.height.toFixed(2) + ")";
        };
        _proto.intersects = function intersects(other) {
          var maxax = this.x + this.width;
          var maxay = this.y + this.height;
          var maxbx = other.x + other.width;
          var maxby = other.y + other.height;
          return !(maxax < other.x || maxbx < this.x || maxay < other.y || maxby < this.y);
        };
        _proto.contains = function contains(point) {
          return this.x <= point.x && this.x + this.width >= point.x && this.y <= point.y && this.y + this.height >= point.y;
        };
        _proto.containsRect = function containsRect(other) {
          return this.x <= other.x && this.x + this.width >= other.x + other.width && this.y <= other.y && this.y + this.height >= other.y + other.height;
        };
        _proto.transformMat4 = function transformMat4(mat) {
          var ol = this.x;
          var ob = this.y;
          var or = ol + this.width;
          var ot = ob + this.height;
          var lbx = mat.m00 * ol + mat.m04 * ob + mat.m12;
          var lby = mat.m01 * ol + mat.m05 * ob + mat.m13;
          var rbx = mat.m00 * or + mat.m04 * ob + mat.m12;
          var rby = mat.m01 * or + mat.m05 * ob + mat.m13;
          var ltx = mat.m00 * ol + mat.m04 * ot + mat.m12;
          var lty = mat.m01 * ol + mat.m05 * ot + mat.m13;
          var rtx = mat.m00 * or + mat.m04 * ot + mat.m12;
          var rty = mat.m01 * or + mat.m05 * ot + mat.m13;
          var minX = Math.min(lbx, rbx, ltx, rtx);
          var maxX = Math.max(lbx, rbx, ltx, rtx);
          var minY = Math.min(lby, rby, lty, rty);
          var maxY = Math.max(lby, rby, lty, rty);
          this.x = minX;
          this.y = minY;
          this.width = maxX - minX;
          this.height = maxY - minY;
          return this;
        };
        _proto.transformMat4ToPoints = function transformMat4ToPoints(mat, out_lb, out_lt, out_rt, out_rb) {
          var ol = this.x;
          var ob = this.y;
          var or = ol + this.width;
          var ot = ob + this.height;
          out_lb.x = mat.m00 * ol + mat.m04 * ob + mat.m12;
          out_lb.y = mat.m01 * ol + mat.m05 * ob + mat.m13;
          out_rb.x = mat.m00 * or + mat.m04 * ob + mat.m12;
          out_rb.y = mat.m01 * or + mat.m05 * ob + mat.m13;
          out_lt.x = mat.m00 * ol + mat.m04 * ot + mat.m12;
          out_lt.y = mat.m01 * ol + mat.m05 * ot + mat.m13;
          out_rt.x = mat.m00 * or + mat.m04 * ot + mat.m12;
          out_rt.y = mat.m01 * or + mat.m05 * ot + mat.m13;
        };
        _createClass(Rect, [{
          key: "xMin",
          get: function get() {
            return this.x;
          },
          set: function set(value) {
            this.width += this.x - value;
            this.x = value;
          }
        }, {
          key: "yMin",
          get: function get() {
            return this.y;
          },
          set: function set(value) {
            this.height += this.y - value;
            this.y = value;
          }
        }, {
          key: "xMax",
          get: function get() {
            return this.x + this.width;
          },
          set: function set(value) {
            this.width = value - this.x;
          }
        }, {
          key: "yMax",
          get: function get() {
            return this.y + this.height;
          },
          set: function set(value) {
            this.height = value - this.y;
          }
        }, {
          key: "center",
          get: function get() {
            return new Vec2(this.x + this.width * 0.5, this.y + this.height * 0.5);
          },
          set: function set(value) {
            this.x = value.x - this.width * 0.5;
            this.y = value.y - this.height * 0.5;
          }
        }, {
          key: "origin",
          get: function get() {
            return new Vec2(this.x, this.y);
          },
          set: function set(value) {
            this.x = value.x;
            this.y = value.y;
          }
        }, {
          key: "size",
          get: function get() {
            return new Size$1(this.width, this.height);
          },
          set: function set(value) {
            this.width = value.width;
            this.height = value.height;
          }
        }, {
          key: "z",
          get: function get() {
            return this.width;
          },
          set: function set(val) {
            this.width = val;
          }
        }, {
          key: "w",
          get: function get() {
            return this.height;
          },
          set: function set(val) {
            this.height = val;
          }
        }]);
        return Rect;
      }(ValueType));
      CCClass.fastDefine('cc.Rect', Rect$1, {
        x: 0,
        y: 0,
        width: 0,
        height: 0
      });
      legacyCC.Rect = Rect$1;
      function rect(x, y, width, height) {
        if (x === void 0) {
          x = 0;
        }
        if (y === void 0) {
          y = 0;
        }
        if (width === void 0) {
          width = 0;
        }
        if (height === void 0) {
          height = 0;
        }
        return new Rect$1(x, y, width, height);
      }
      legacyCC.rect = rect;

      var MATH_FLOAT_ARRAY = exports('bn', Float64Array);
      var MathBase = exports('bo', function (_ValueType) {
        _inheritsLoose(MathBase, _ValueType);
        function MathBase() {
          return _ValueType.apply(this, arguments) || this;
        }
        MathBase.createFloatArray = function createFloatArray(size) {
          return new MATH_FLOAT_ARRAY(size);
        };
        _createClass(MathBase, [{
          key: "array",
          get: function get() {
            return this._array;
          }
        }]);
        return MathBase;
      }(ValueType));

      var math = /*#__PURE__*/Object.freeze({
        __proto__: null,
        bits: bits,
        Vec2: Vec2,
        v2: v2$1,
        Vec3: Vec3,
        v3: v3,
        Vec4: Vec4,
        v4: v4,
        Quat: Quat,
        quat: quat$1,
        Mat3: Mat3,
        Mat4: Mat4,
        mat4: mat4,
        AffineTransform: AffineTransform,
        Size: Size$1,
        size: size,
        Rect: Rect$1,
        rect: rect,
        Color: Color$1,
        color: color,
        preTransforms: preTransforms,
        HALF_PI: HALF_PI,
        TWO_PI: TWO_PI,
        EPSILON: EPSILON$3,
        equals: equals$1,
        approx: approx,
        clamp: clamp$1,
        clamp01: clamp01,
        lerp: lerp,
        toRadian: toRadian,
        toDegree: toDegree,
        random: random,
        setRandGenerator: setRandGenerator,
        randomRange: randomRange,
        randomRangeInt: randomRangeInt,
        pseudoRandom: pseudoRandom,
        pseudoRandomRange: pseudoRandomRange,
        pseudoRandomRangeInt: pseudoRandomRangeInt,
        nextPow2: nextPow2,
        repeat: repeat$2,
        pingPong: pingPong,
        inverseLerp: inverseLerp,
        absMaxComponent: absMaxComponent,
        absMax: absMax,
        enumerableProps: enumerableProps,
        floatToHalf: floatToHalf,
        halfToFloat: halfToFloat,
        MATH_FLOAT_ARRAY: MATH_FLOAT_ARRAY,
        MathBase: MathBase
      });
      exports('aA', math);

      var X = new Vec3();
      var Y = new Vec3();
      var Z = new Vec3();
      var d = new Vec3();
      var min$2 = new Vec3();
      var max$3 = new Vec3();
      var u = new Array(3);
      var e = new Array(3);
      function point_plane(point, plane_) {
        return Vec3.dot(plane_.n, point) - plane_.d;
      }
      function pt_point_plane(out, point, plane_) {
        var t = point_plane(point, plane_);
        return Vec3.subtract(out, point, Vec3.multiplyScalar(out, plane_.n, t));
      }
      function pt_point_aabb(out, point, aabb_) {
        Vec3.copy(out, point);
        Vec3.subtract(min$2, aabb_.center, aabb_.halfExtents);
        Vec3.add(max$3, aabb_.center, aabb_.halfExtents);
        out.x = out.x < min$2.x ? min$2.x : out.x;
        out.y = out.y < min$2.y ? min$2.y : out.y;
        out.z = out.z < min$2.z ? min$2.z : out.z;
        out.x = out.x > max$3.x ? max$3.x : out.x;
        out.y = out.y > max$3.y ? max$3.y : out.y;
        out.z = out.z > max$3.z ? max$3.z : out.z;
        return out;
      }
      function pt_point_obb(out, point, obb_) {
        Vec3.set(X, obb_.orientation.m00, obb_.orientation.m01, obb_.orientation.m02);
        Vec3.set(Y, obb_.orientation.m03, obb_.orientation.m04, obb_.orientation.m05);
        Vec3.set(Z, obb_.orientation.m06, obb_.orientation.m07, obb_.orientation.m08);
        u[0] = X;
        u[1] = Y;
        u[2] = Z;
        e[0] = obb_.halfExtents.x;
        e[1] = obb_.halfExtents.y;
        e[2] = obb_.halfExtents.z;
        Vec3.subtract(d, point, obb_.center);
        Vec3.set(out, obb_.center.x, obb_.center.y, obb_.center.z);
        for (var i = 0; i < 3; i++) {
          var dist = Vec3.dot(d, u[i]);
          if (dist > e[i]) {
            dist = e[i];
          }
          if (dist < -e[i]) {
            dist = -e[i];
          }
          out.x += dist * u[i].x;
          out.y += dist * u[i].y;
          out.z += dist * u[i].z;
        }
        return out;
      }
      function pt_point_line(out, point, linePointA, linePointB) {
        Vec3.subtract(X, linePointA, linePointB);
        var dir = X.clone();
        var dirSquaredLength = Vec3.lengthSqr(dir);
        if (dirSquaredLength === 0) {
          Vec3.copy(out, linePointA);
        } else {
          Vec3.subtract(X, point, linePointA);
          var t = Vec3.dot(X, dir) / dirSquaredLength;
          if (t < 0) {
            Vec3.copy(out, linePointA);
          } else if (t > 1) {
            Vec3.copy(out, linePointB);
          } else {
            Vec3.scaleAndAdd(out, linePointA, dir, t);
          }
        }
      }

      var distance = /*#__PURE__*/Object.freeze({
        __proto__: null,
        point_plane: point_plane,
        pt_point_plane: pt_point_plane,
        pt_point_aabb: pt_point_aabb,
        pt_point_obb: pt_point_obb,
        pt_point_line: pt_point_line
      });

      var enums = {
        SHAPE_RAY: 1 << 0,
        SHAPE_LINE: 1 << 1,
        SHAPE_SPHERE: 1 << 2,
        SHAPE_AABB: 1 << 3,
        SHAPE_OBB: 1 << 4,
        SHAPE_PLANE: 1 << 5,
        SHAPE_TRIANGLE: 1 << 6,
        SHAPE_FRUSTUM: 1 << 7,
        SHAPE_FRUSTUM_ACCURATE: 1 << 8,
        SHAPE_CAPSULE: 1 << 9,
        SHAPE_SPLINE: 1 << 10
      };

      var Line = function () {
        Line.create = function create(sx, sy, sz, ex, ey, ez) {
          return new Line(sx, sy, sz, ex, ey, ez);
        };
        Line.clone = function clone(a) {
          return new Line(a.s.x, a.s.y, a.s.z, a.e.x, a.e.y, a.e.z);
        };
        Line.copy = function copy(out, a) {
          Vec3.copy(out.s, a.s);
          Vec3.copy(out.e, a.e);
          return out;
        };
        Line.fromPoints = function fromPoints(out, start, end) {
          Vec3.copy(out.s, start);
          Vec3.copy(out.e, end);
          return out;
        };
        Line.set = function set(out, sx, sy, sz, ex, ey, ez) {
          out.s.x = sx;
          out.s.y = sy;
          out.s.z = sz;
          out.e.x = ex;
          out.e.y = ey;
          out.e.z = ez;
          return out;
        };
        Line.len = function len(a) {
          return Vec3.distance(a.s, a.e);
        };
        function Line(sx, sy, sz, ex, ey, ez) {
          if (sx === void 0) {
            sx = 0;
          }
          if (sy === void 0) {
            sy = 0;
          }
          if (sz === void 0) {
            sz = 0;
          }
          if (ex === void 0) {
            ex = 0;
          }
          if (ey === void 0) {
            ey = 0;
          }
          if (ez === void 0) {
            ez = -1;
          }
          this.s = void 0;
          this.e = void 0;
          this._type = void 0;
          this._type = enums.SHAPE_LINE;
          this.s = new Vec3(sx, sy, sz);
          this.e = new Vec3(ex, ey, ez);
        }
        var _proto = Line.prototype;
        _proto.length = function length() {
          return Vec3.distance(this.s, this.e);
        };
        _createClass(Line, [{
          key: "type",
          get: function get() {
            return this._type;
          }
        }]);
        return Line;
      }();

      var v1 = new Vec3(0, 0, 0);
      var v2 = new Vec3(0, 0, 0);
      var temp_mat = legacyCC.mat4();
      var temp_vec4 = legacyCC.v4();
      var Plane = function () {
        Plane.create = function create(nx, ny, nz, d) {
          return new Plane(nx, ny, nz, d);
        };
        Plane.clone = function clone(p) {
          return new Plane(p.n.x, p.n.y, p.n.z, p.d);
        };
        Plane.copy = function copy(out, p) {
          Vec3.copy(out.n, p.n);
          out.d = p.d;
          return out;
        };
        Plane.fromPoints = function fromPoints(out, a, b, c) {
          Vec3.subtract(v1, b, a);
          Vec3.subtract(v2, c, a);
          Vec3.normalize(out.n, Vec3.cross(out.n, v1, v2));
          out.d = Vec3.dot(out.n, a);
          return out;
        };
        Plane.set = function set(out, nx, ny, nz, d) {
          out.n.x = nx;
          out.n.y = ny;
          out.n.z = nz;
          out.d = d;
          return out;
        };
        Plane.fromNormalAndPoint = function fromNormalAndPoint(out, normal, point) {
          Vec3.copy(out.n, normal);
          out.d = Vec3.dot(normal, point);
          return out;
        };
        Plane.normalize = function normalize(out, a) {
          var len = a.n.length();
          Vec3.normalize(out.n, a.n);
          if (len > 0) {
            out.d = a.d / len;
          }
          return out;
        };
        function Plane(nx, ny, nz, d) {
          if (nx === void 0) {
            nx = 0;
          }
          if (ny === void 0) {
            ny = 1;
          }
          if (nz === void 0) {
            nz = 0;
          }
          if (d === void 0) {
            d = 0;
          }
          this.n = void 0;
          this._type = enums.SHAPE_PLANE;
          this.n = new Vec3(nx, ny, nz);
          this.d = d;
        }
        var _proto = Plane.prototype;
        _proto.transform = function transform(mat) {
          Mat4.invert(temp_mat, mat);
          Mat4.transpose(temp_mat, temp_mat);
          Vec4.set(temp_vec4, this.n.x, this.n.y, this.n.z, -this.d);
          Vec4.transformMat4(temp_vec4, temp_vec4, temp_mat);
          Vec3.set(this.n, temp_vec4.x, temp_vec4.y, temp_vec4.z);
          this.d = -temp_vec4.w;
        };
        _createClass(Plane, [{
          key: "type",
          get: function get() {
            return this._type;
          }
        }, {
          key: "x",
          get: function get() {
            return this.n.x;
          },
          set: function set(val) {
            this.n.x = val;
          }
        }, {
          key: "y",
          get: function get() {
            return this.n.y;
          },
          set: function set(val) {
            this.n.y = val;
          }
        }, {
          key: "z",
          get: function get() {
            return this.n.z;
          },
          set: function set(val) {
            this.n.z = val;
          }
        }, {
          key: "w",
          get: function get() {
            return this.d;
          },
          set: function set(val) {
            this.d = val;
          }
        }]);
        return Plane;
      }();

      var Ray = function () {
        Ray.create = function create(ox, oy, oz, dx, dy, dz) {
          if (ox === void 0) {
            ox = 0;
          }
          if (oy === void 0) {
            oy = 0;
          }
          if (oz === void 0) {
            oz = 0;
          }
          if (dx === void 0) {
            dx = 0;
          }
          if (dy === void 0) {
            dy = 0;
          }
          if (dz === void 0) {
            dz = 1;
          }
          return new Ray(ox, oy, oz, dx, dy, dz);
        };
        Ray.clone = function clone(a) {
          return new Ray(a.o.x, a.o.y, a.o.z, a.d.x, a.d.y, a.d.z);
        };
        Ray.copy = function copy(out, a) {
          Vec3.copy(out.o, a.o);
          Vec3.copy(out.d, a.d);
          return out;
        };
        Ray.fromPoints = function fromPoints(out, origin, target) {
          Vec3.copy(out.o, origin);
          Vec3.normalize(out.d, Vec3.subtract(out.d, target, origin));
          return out;
        };
        Ray.set = function set(out, ox, oy, oz, dx, dy, dz) {
          out.o.x = ox;
          out.o.y = oy;
          out.o.z = oz;
          out.d.x = dx;
          out.d.y = dy;
          out.d.z = dz;
          return out;
        };
        function Ray(ox, oy, oz, dx, dy, dz) {
          if (ox === void 0) {
            ox = 0;
          }
          if (oy === void 0) {
            oy = 0;
          }
          if (oz === void 0) {
            oz = 0;
          }
          if (dx === void 0) {
            dx = 0;
          }
          if (dy === void 0) {
            dy = 0;
          }
          if (dz === void 0) {
            dz = -1;
          }
          this.o = void 0;
          this.d = void 0;
          this._type = void 0;
          this._type = enums.SHAPE_RAY;
          this.o = new Vec3(ox, oy, oz);
          this.d = new Vec3(dx, dy, dz);
        }
        var _proto = Ray.prototype;
        _proto.computeHit = function computeHit(out, distance) {
          Vec3.normalize(out, this.d);
          Vec3.scaleAndAdd(out, this.o, out, distance);
        };
        _createClass(Ray, [{
          key: "type",
          get: function get() {
            return this._type;
          }
        }]);
        return Ray;
      }();

      var Triangle = function () {
        Triangle.create = function create(ax, ay, az, bx, by, bz, cx, cy, cz) {
          if (ax === void 0) {
            ax = 1;
          }
          if (ay === void 0) {
            ay = 0;
          }
          if (az === void 0) {
            az = 0;
          }
          if (bx === void 0) {
            bx = 0;
          }
          if (by === void 0) {
            by = 0;
          }
          if (bz === void 0) {
            bz = 0;
          }
          if (cx === void 0) {
            cx = 0;
          }
          if (cy === void 0) {
            cy = 0;
          }
          if (cz === void 0) {
            cz = 1;
          }
          return new Triangle(ax, ay, az, bx, by, bz, cx, cy, cz);
        };
        Triangle.clone = function clone(t) {
          return new Triangle(t.a.x, t.a.y, t.a.z, t.b.x, t.b.y, t.b.z, t.c.x, t.c.y, t.c.z);
        };
        Triangle.copy = function copy(out, t) {
          Vec3.copy(out.a, t.a);
          Vec3.copy(out.b, t.b);
          Vec3.copy(out.c, t.c);
          return out;
        };
        Triangle.fromPoints = function fromPoints(out, a, b, c) {
          Vec3.copy(out.a, a);
          Vec3.copy(out.b, b);
          Vec3.copy(out.c, c);
          return out;
        };
        Triangle.set = function set(out, ax, ay, az, bx, by, bz, cx, cy, cz) {
          out.a.x = ax;
          out.a.y = ay;
          out.a.z = az;
          out.b.x = bx;
          out.b.y = by;
          out.b.z = bz;
          out.c.x = cx;
          out.c.y = cy;
          out.c.z = cz;
          return out;
        };
        function Triangle(ax, ay, az, bx, by, bz, cx, cy, cz) {
          if (ax === void 0) {
            ax = 0;
          }
          if (ay === void 0) {
            ay = 0;
          }
          if (az === void 0) {
            az = 0;
          }
          if (bx === void 0) {
            bx = 1;
          }
          if (by === void 0) {
            by = 0;
          }
          if (bz === void 0) {
            bz = 0;
          }
          if (cx === void 0) {
            cx = 0;
          }
          if (cy === void 0) {
            cy = 1;
          }
          if (cz === void 0) {
            cz = 0;
          }
          this.a = void 0;
          this.b = void 0;
          this.c = void 0;
          this._type = void 0;
          this._type = enums.SHAPE_TRIANGLE;
          this.a = new Vec3(ax, ay, az);
          this.b = new Vec3(bx, by, bz);
          this.c = new Vec3(cx, cy, cz);
        }
        _createClass(Triangle, [{
          key: "type",
          get: function get() {
            return this._type;
          }
        }]);
        return Triangle;
      }();

      var _v3_tmp$2 = new Vec3();
      var _offset = new Vec3();
      var _min = new Vec3();
      var _max = new Vec3();
      function maxComponent$1(v) {
        return Math.max(Math.max(v.x, v.y), v.z);
      }
      var Sphere = function () {
        Sphere.create = function create(cx, cy, cz, r) {
          return new Sphere(cx, cy, cz, r);
        };
        Sphere.clone = function clone(p) {
          return new Sphere(p.center.x, p.center.y, p.center.z, p.radius);
        };
        Sphere.copy = function copy(out, p) {
          Vec3.copy(out.center, p.center);
          out.radius = p.radius;
          return out;
        };
        Sphere.fromPoints = function fromPoints(out, minPos, maxPos) {
          Vec3.multiplyScalar(out.center, Vec3.add(_v3_tmp$2, minPos, maxPos), 0.5);
          out.radius = Vec3.subtract(_v3_tmp$2, maxPos, minPos).length() * 0.5;
          return out;
        };
        Sphere.set = function set(out, cx, cy, cz, r) {
          out.center.x = cx;
          out.center.y = cy;
          out.center.z = cz;
          out.radius = r;
          return out;
        };
        function Sphere(cx, cy, cz, r) {
          if (cx === void 0) {
            cx = 0;
          }
          if (cy === void 0) {
            cy = 0;
          }
          if (cz === void 0) {
            cz = 0;
          }
          if (r === void 0) {
            r = 1;
          }
          this._center = new Vec3(0, 0, 0);
          this._radius = 0;
          this._type = void 0;
          this._type = enums.SHAPE_SPHERE;
          this._center = new Vec3(cx, cy, cz);
          this._radius = r;
        }
        var _proto = Sphere.prototype;
        _proto.destroy = function destroy() {};
        _proto.clone = function clone() {
          return Sphere.clone(this);
        };
        _proto.copy = function copy(a) {
          return Sphere.copy(this, a);
        };
        _proto.getBoundary = function getBoundary(minPos, maxPos) {
          Vec3.set(minPos, this.center.x - this.radius, this.center.y - this.radius, this.center.z - this.radius);
          Vec3.set(maxPos, this.center.x + this.radius, this.center.y + this.radius, this.center.z + this.radius);
        };
        _proto.transform = function transform(m, pos, rot, scale, out) {
          Vec3.transformMat4(out.center, this.center, m);
          out.radius = this.radius * maxComponent$1(scale);
        };
        _proto.translateAndRotate = function translateAndRotate(m, rot, out) {
          Vec3.transformMat4(out.center, this.center, m);
        };
        _proto.setScale = function setScale(scale, out) {
          out.radius = this.radius * maxComponent$1(scale);
        };
        _proto.mergePoint = function mergePoint(point) {
          if (this.radius < 0.0) {
            this.center.set(point);
            this.radius = 0.0;
          }
          Vec3.subtract(_offset, point, this.center);
          var dist = _offset.length();
          if (dist > this.radius) {
            var half = (dist - this.radius) * 0.5;
            this.radius += half;
            Vec3.multiplyScalar(_offset, _offset, half / dist);
            Vec3.add(this.center, this.center, _offset);
          }
        };
        _proto.mergePoints = function mergePoints(points) {
          var length = points.length;
          if (length < 1) return;
          this.radius = -1.0;
          for (var i = 0; i < length; i++) {
            this.mergePoint(points[i]);
          }
        };
        _proto.mergeAABB = function mergeAABB(a) {
          a.getBoundary(_min, _max);
          this.mergePoint(_min);
          this.mergePoint(_max);
        };
        _createClass(Sphere, [{
          key: "center",
          get: function get() {
            return this._center;
          },
          set: function set(val) {
            this._center = val;
          }
        }, {
          key: "radius",
          get: function get() {
            return this._radius;
          },
          set: function set(val) {
            this._radius = val;
          }
        }, {
          key: "type",
          get: function get() {
            return this._type;
          }
        }]);
        return Sphere;
      }();

      var _v3_tmp$1 = new Vec3();
      var _v3_tmp2$1 = new Vec3();
      var _v3_tmp3 = new Vec3();
      var _v3_tmp4 = new Vec3();
      var _m3_tmp$1 = new Mat3();
      var transform_extent_m4 = function transform_extent_m4(out, extent, m4) {
        _m3_tmp$1.m00 = Math.abs(m4.m00);
        _m3_tmp$1.m01 = Math.abs(m4.m01);
        _m3_tmp$1.m02 = Math.abs(m4.m02);
        _m3_tmp$1.m03 = Math.abs(m4.m04);
        _m3_tmp$1.m04 = Math.abs(m4.m05);
        _m3_tmp$1.m05 = Math.abs(m4.m06);
        _m3_tmp$1.m06 = Math.abs(m4.m08);
        _m3_tmp$1.m07 = Math.abs(m4.m09);
        _m3_tmp$1.m08 = Math.abs(m4.m10);
        Vec3.transformMat3(out, extent, _m3_tmp$1);
      };
      var AABB = function () {
        AABB.create = function create(px, py, pz, hw, hh, hl) {
          return new AABB(px, py, pz, hw, hh, hl);
        };
        AABB.clone = function clone(a) {
          return new AABB(a.center.x, a.center.y, a.center.z, a.halfExtents.x, a.halfExtents.y, a.halfExtents.z);
        };
        AABB.copy = function copy(out, a) {
          Vec3.copy(out.center, a.center);
          Vec3.copy(out.halfExtents, a.halfExtents);
          return out;
        };
        AABB.fromPoints = function fromPoints(out, minPos, maxPos) {
          Vec3.add(_v3_tmp$1, maxPos, minPos);
          Vec3.subtract(_v3_tmp2$1, maxPos, minPos);
          Vec3.multiplyScalar(out.center, _v3_tmp$1, 0.5);
          Vec3.multiplyScalar(out.halfExtents, _v3_tmp2$1, 0.5);
          return out;
        };
        AABB.set = function set(out, px, py, pz, hw, hh, hl) {
          out.center.set(px, py, pz);
          out.halfExtents.set(hw, hh, hl);
          return out;
        };
        AABB.merge = function merge(out, a, b) {
          Vec3.subtract(_v3_tmp$1, a.center, a.halfExtents);
          Vec3.subtract(_v3_tmp2$1, b.center, b.halfExtents);
          Vec3.add(_v3_tmp3, a.center, a.halfExtents);
          Vec3.add(_v3_tmp4, b.center, b.halfExtents);
          Vec3.max(_v3_tmp4, _v3_tmp3, _v3_tmp4);
          Vec3.min(_v3_tmp3, _v3_tmp$1, _v3_tmp2$1);
          return AABB.fromPoints(out, _v3_tmp3, _v3_tmp4);
        };
        AABB.toBoundingSphere = function toBoundingSphere(out, a) {
          out.center.set(a.center);
          out.radius = a.halfExtents.length();
          return out;
        };
        AABB.transform = function transform(out, a, matrix) {
          Vec3.transformMat4(out.center, a.center, matrix);
          transform_extent_m4(out.halfExtents, a.halfExtents, matrix);
          return out;
        };
        function AABB(px, py, pz, hw, hh, hl) {
          if (px === void 0) {
            px = 0;
          }
          if (py === void 0) {
            py = 0;
          }
          if (pz === void 0) {
            pz = 0;
          }
          if (hw === void 0) {
            hw = 1;
          }
          if (hh === void 0) {
            hh = 1;
          }
          if (hl === void 0) {
            hl = 1;
          }
          this.center = void 0;
          this.halfExtents = void 0;
          this._type = void 0;
          this._type = enums.SHAPE_AABB;
          this.center = new Vec3(px, py, pz);
          this.halfExtents = new Vec3(hw, hh, hl);
        }
        var _proto = AABB.prototype;
        _proto.getBoundary = function getBoundary(minPos, maxPos) {
          Vec3.subtract(minPos, this.center, this.halfExtents);
          Vec3.add(maxPos, this.center, this.halfExtents);
        };
        _proto.transform = function transform(m, pos, rot, scale, out) {
          Vec3.transformMat4(out.center, this.center, m);
          transform_extent_m4(out.halfExtents, this.halfExtents, m);
        };
        _proto.clone = function clone() {
          return AABB.clone(this);
        };
        _proto.copy = function copy(a) {
          return AABB.copy(this, a);
        };
        _proto.mergePoint = function mergePoint(point) {
          this.getBoundary(_v3_tmp$1, _v3_tmp2$1);
          if (point.x < _v3_tmp$1.x) {
            _v3_tmp$1.x = point.x;
          }
          if (point.y < _v3_tmp$1.y) {
            _v3_tmp$1.y = point.y;
          }
          if (point.z < _v3_tmp$1.z) {
            _v3_tmp$1.z = point.z;
          }
          if (point.x > _v3_tmp2$1.x) {
            _v3_tmp2$1.x = point.x;
          }
          if (point.y > _v3_tmp2$1.y) {
            _v3_tmp2$1.y = point.y;
          }
          if (point.z > _v3_tmp2$1.z) {
            _v3_tmp2$1.z = point.z;
          }
          Vec3.add(_v3_tmp3, _v3_tmp$1, _v3_tmp2$1);
          this.center.set(Vec3.multiplyScalar(_v3_tmp3, _v3_tmp3, 0.5));
          this.halfExtents.set(_v3_tmp2$1.x - _v3_tmp3.x, _v3_tmp2$1.y - _v3_tmp3.y, _v3_tmp2$1.z - _v3_tmp3.z);
        };
        _proto.mergePoints = function mergePoints(points) {
          if (points.length < 1) {
            return;
          }
          for (var i = 0; i < points.length; i++) {
            this.mergePoint(points[i]);
          }
        };
        _proto.mergeFrustum = function mergeFrustum(frustum) {
          this.mergePoints(frustum.vertices);
        };
        _createClass(AABB, [{
          key: "type",
          get: function get() {
            return this._type;
          }
        }]);
        return AABB;
      }();

      var Capsule = function () {
        function Capsule(radius, halfHeight, axis) {
          if (radius === void 0) {
            radius = 0.5;
          }
          if (halfHeight === void 0) {
            halfHeight = 0.5;
          }
          if (axis === void 0) {
            axis = 1;
          }
          this._type = void 0;
          this.radius = void 0;
          this.halfHeight = void 0;
          this.axis = void 0;
          this.center = void 0;
          this.rotation = void 0;
          this.ellipseCenter0 = void 0;
          this.ellipseCenter1 = void 0;
          this._type = enums.SHAPE_CAPSULE;
          this.radius = radius;
          this.halfHeight = halfHeight;
          this.axis = axis;
          this.center = new Vec3();
          this.rotation = new Quat();
          this.ellipseCenter0 = new Vec3(0, halfHeight, 0);
          this.ellipseCenter1 = new Vec3(0, -halfHeight, 0);
          this.updateCache();
        }
        var _proto = Capsule.prototype;
        _proto.transform = function transform(m, pos, rot, scale, out) {
          var ws = scale;
          var s = absMaxComponent(ws);
          out.radius = this.radius * Math.abs(s);
          var halfTotalWorldHeight = (this.halfHeight + this.radius) * Math.abs(ws.y);
          var halfWorldHeight = halfTotalWorldHeight - out.radius;
          if (halfWorldHeight < 0) halfWorldHeight = 0;
          out.halfHeight = halfWorldHeight;
          Vec3.transformMat4(out.center, this.center, m);
          Quat.multiply(out.rotation, this.rotation, rot);
          out.updateCache();
        };
        _proto.updateCache = function updateCache() {
          this.updateLocalCenter();
          Vec3.transformQuat(this.ellipseCenter0, this.ellipseCenter0, this.rotation);
          Vec3.transformQuat(this.ellipseCenter1, this.ellipseCenter1, this.rotation);
          this.ellipseCenter0.add(this.center);
          this.ellipseCenter1.add(this.center);
        };
        _proto.updateLocalCenter = function updateLocalCenter() {
          var halfHeight = this.halfHeight;
          var axis = this.axis;
          switch (axis) {
            case 0:
              this.ellipseCenter0.set(halfHeight, 0, 0);
              this.ellipseCenter1.set(-halfHeight, 0, 0);
              break;
            case 1:
              this.ellipseCenter0.set(0, halfHeight, 0);
              this.ellipseCenter1.set(0, -halfHeight, 0);
              break;
            case 2:
              this.ellipseCenter0.set(0, 0, halfHeight);
              this.ellipseCenter1.set(0, 0, -halfHeight);
              break;
          }
        };
        _createClass(Capsule, [{
          key: "type",
          get: function get() {
            return this._type;
          }
        }]);
        return Capsule;
      }();

      var _v = new Array(8);
      _v[0] = new Vec3(1, 1, 1);
      _v[1] = new Vec3(-1, 1, 1);
      _v[2] = new Vec3(-1, -1, 1);
      _v[3] = new Vec3(1, -1, 1);
      _v[4] = new Vec3(1, 1, -1);
      _v[5] = new Vec3(-1, 1, -1);
      _v[6] = new Vec3(-1, -1, -1);
      _v[7] = new Vec3(1, -1, -1);
      var _nearTemp = new Vec3();
      var _farTemp = new Vec3();
      var _temp_v3 = new Vec3();
      var Frustum = function () {
        Frustum.createOrthographic = function createOrthographic(out, width, height, near, far, transform) {
          var halfWidth = width / 2;
          var halfHeight = height / 2;
          Vec3.set(_temp_v3, halfWidth, halfHeight, -near);
          Vec3.transformMat4(out.vertices[0], _temp_v3, transform);
          Vec3.set(_temp_v3, -halfWidth, halfHeight, -near);
          Vec3.transformMat4(out.vertices[1], _temp_v3, transform);
          Vec3.set(_temp_v3, -halfWidth, -halfHeight, -near);
          Vec3.transformMat4(out.vertices[2], _temp_v3, transform);
          Vec3.set(_temp_v3, halfWidth, -halfHeight, -near);
          Vec3.transformMat4(out.vertices[3], _temp_v3, transform);
          Vec3.set(_temp_v3, halfWidth, halfHeight, -far);
          Vec3.transformMat4(out.vertices[4], _temp_v3, transform);
          Vec3.set(_temp_v3, -halfWidth, halfHeight, -far);
          Vec3.transformMat4(out.vertices[5], _temp_v3, transform);
          Vec3.set(_temp_v3, -halfWidth, -halfHeight, -far);
          Vec3.transformMat4(out.vertices[6], _temp_v3, transform);
          Vec3.set(_temp_v3, halfWidth, -halfHeight, -far);
          Vec3.transformMat4(out.vertices[7], _temp_v3, transform);
          out.updatePlanes();
        };
        Frustum.createOrtho = function createOrtho(out, width, height, near, far, transform) {
          return Frustum.createOrthographic(out, width, height, near, far, transform);
        };
        Frustum.createPerspective = function createPerspective(out, aspect, fov, near, far, transform) {
          var h = Math.tan(fov * 0.5);
          var w = h * aspect;
          _nearTemp.set(near * w, near * h, near);
          _farTemp.set(far * w, far * h, far);
          var vertexes = out.vertices;
          _temp_v3.set(_nearTemp.x, _nearTemp.y, -_nearTemp.z);
          Vec3.transformMat4(vertexes[0], _temp_v3, transform);
          _temp_v3.set(-_nearTemp.x, _nearTemp.y, -_nearTemp.z);
          Vec3.transformMat4(vertexes[1], _temp_v3, transform);
          _temp_v3.set(-_nearTemp.x, -_nearTemp.y, -_nearTemp.z);
          Vec3.transformMat4(vertexes[2], _temp_v3, transform);
          _temp_v3.set(_nearTemp.x, -_nearTemp.y, -_nearTemp.z);
          Vec3.transformMat4(vertexes[3], _temp_v3, transform);
          _temp_v3.set(_farTemp.x, _farTemp.y, -_farTemp.z);
          Vec3.transformMat4(vertexes[4], _temp_v3, transform);
          _temp_v3.set(-_farTemp.x, _farTemp.y, -_farTemp.z);
          Vec3.transformMat4(vertexes[5], _temp_v3, transform);
          _temp_v3.set(-_farTemp.x, -_farTemp.y, -_farTemp.z);
          Vec3.transformMat4(vertexes[6], _temp_v3, transform);
          _temp_v3.set(_farTemp.x, -_farTemp.y, -_farTemp.z);
          Vec3.transformMat4(vertexes[7], _temp_v3, transform);
          out.updatePlanes();
        };
        Frustum.createFromAABB = function createFromAABB(out, aabb) {
          var vec3_min = new Vec3();
          var vec3_max = new Vec3();
          Vec3.subtract(vec3_min, aabb.center, aabb.halfExtents);
          Vec3.add(vec3_max, aabb.center, aabb.halfExtents);
          out.vertices[0].set(vec3_max.x, vec3_max.y, -vec3_min.z);
          out.vertices[1].set(vec3_min.x, vec3_max.y, -vec3_min.z);
          out.vertices[2].set(vec3_min.x, vec3_min.y, -vec3_min.z);
          out.vertices[3].set(vec3_max.x, vec3_min.y, -vec3_min.z);
          out.vertices[4].set(vec3_max.x, vec3_max.y, -vec3_max.z);
          out.vertices[5].set(vec3_min.x, vec3_max.y, -vec3_max.z);
          out.vertices[6].set(vec3_min.x, vec3_min.y, -vec3_max.z);
          out.vertices[7].set(vec3_max.x, vec3_min.y, -vec3_max.z);
          out.updatePlanes();
          return out;
        };
        var _proto = Frustum.prototype;
        _proto.split = function split(start, end, aspect, fov, m) {
          return Frustum.createPerspective(this, aspect, fov, start, end, m);
        };
        Frustum.create = function create() {
          return new Frustum();
        };
        Frustum.clone = function clone(f) {
          return Frustum.copy(new Frustum(), f);
        };
        Frustum.copy = function copy(out, f) {
          out._type = f.type;
          for (var i = 0; i < 6; ++i) {
            Plane.copy(out.planes[i], f.planes[i]);
          }
          for (var _i = 0; _i < 8; ++_i) {
            Vec3.copy(out.vertices[_i], f.vertices[_i]);
          }
          return out;
        };
        function Frustum() {
          this.planes = void 0;
          this.vertices = void 0;
          this._type = void 0;
          this._type = enums.SHAPE_FRUSTUM;
          this.planes = new Array(6);
          for (var i = 0; i < 6; ++i) {
            this.planes[i] = Plane.create(0, 0, 0, 0);
          }
          this.vertices = new Array(8);
          for (var _i2 = 0; _i2 < 8; ++_i2) {
            this.vertices[_i2] = new Vec3();
          }
        }
        _proto.update = function update(m, inv) {
          Vec3.set(this.planes[0].n, m.m03 + m.m00, m.m07 + m.m04, m.m11 + m.m08);
          this.planes[0].d = -(m.m15 + m.m12);
          Vec3.set(this.planes[1].n, m.m03 - m.m00, m.m07 - m.m04, m.m11 - m.m08);
          this.planes[1].d = -(m.m15 - m.m12);
          Vec3.set(this.planes[2].n, m.m03 + m.m01, m.m07 + m.m05, m.m11 + m.m09);
          this.planes[2].d = -(m.m15 + m.m13);
          Vec3.set(this.planes[3].n, m.m03 - m.m01, m.m07 - m.m05, m.m11 - m.m09);
          this.planes[3].d = -(m.m15 - m.m13);
          Vec3.set(this.planes[4].n, m.m03 + m.m02, m.m07 + m.m06, m.m11 + m.m10);
          this.planes[4].d = -(m.m15 + m.m14);
          Vec3.set(this.planes[5].n, m.m03 - m.m02, m.m07 - m.m06, m.m11 - m.m10);
          this.planes[5].d = -(m.m15 - m.m14);
          for (var i = 0; i < 6; i++) {
            var pl = this.planes[i];
            var invDist = 1 / pl.n.length();
            Vec3.multiplyScalar(pl.n, pl.n, invDist);
            pl.d *= invDist;
          }
          for (var _i3 = 0; _i3 < 8; _i3++) {
            Vec3.transformMat4(this.vertices[_i3], _v[_i3], inv);
          }
        };
        _proto.transform = function transform(mat) {
          for (var i = 0; i < 8; i++) {
            Vec3.transformMat4(this.vertices[i], this.vertices[i], mat);
          }
          this.updatePlanes();
        };
        _proto.zero = function zero() {
          for (var i = 0; i < 8; i++) {
            this.vertices[i].set(0.0, 0.0, 0.0);
          }
          for (var _i4 = 0; _i4 < 6; _i4++) {
            Plane.set(this.planes[_i4], 0, 0, 0, 0);
          }
        };
        _proto.updatePlanes = function updatePlanes() {
          Plane.fromPoints(this.planes[0], this.vertices[1], this.vertices[6], this.vertices[5]);
          Plane.fromPoints(this.planes[1], this.vertices[3], this.vertices[4], this.vertices[7]);
          Plane.fromPoints(this.planes[2], this.vertices[6], this.vertices[3], this.vertices[7]);
          Plane.fromPoints(this.planes[3], this.vertices[0], this.vertices[5], this.vertices[4]);
          Plane.fromPoints(this.planes[4], this.vertices[2], this.vertices[0], this.vertices[3]);
          Plane.fromPoints(this.planes[5], this.vertices[7], this.vertices[5], this.vertices[6]);
        };
        _createClass(Frustum, [{
          key: "accurate",
          set: function set(b) {
            this._type = b ? enums.SHAPE_FRUSTUM_ACCURATE : enums.SHAPE_FRUSTUM;
          }
        }, {
          key: "type",
          get: function get() {
            return this._type;
          }
        }]);
        return Frustum;
      }();

      var rayPlane = function () {
        return function (ray, plane) {
          var denom = Vec3.dot(ray.d, plane.n);
          if (Math.abs(denom) < Number.EPSILON) {
            return 0;
          }
          var d = point_plane(ray.o, plane);
          var t = -d / denom;
          if (t < 0) {
            return 0;
          }
          return t;
        };
      }();
      var rayTriangle = function () {
        var ab = new Vec3(0, 0, 0);
        var ac = new Vec3(0, 0, 0);
        var pvec = new Vec3(0, 0, 0);
        var tvec = new Vec3(0, 0, 0);
        var qvec = new Vec3(0, 0, 0);
        return function (ray, triangle, doubleSided) {
          Vec3.subtract(ab, triangle.b, triangle.a);
          Vec3.subtract(ac, triangle.c, triangle.a);
          Vec3.cross(pvec, ray.d, ac);
          var det = Vec3.dot(ab, pvec);
          if (det < Number.EPSILON && (!doubleSided || det > -Number.EPSILON)) {
            return 0;
          }
          var inv_det = 1 / det;
          Vec3.subtract(tvec, ray.o, triangle.a);
          var u = Vec3.dot(tvec, pvec) * inv_det;
          if (u < 0 || u > 1) {
            return 0;
          }
          Vec3.cross(qvec, tvec, ab);
          var v = Vec3.dot(ray.d, qvec) * inv_det;
          if (v < 0 || u + v > 1) {
            return 0;
          }
          var t = Vec3.dot(ac, qvec) * inv_det;
          return t < 0 ? 0 : t;
        };
      }();
      var raySphere = function () {
        var e = new Vec3(0, 0, 0);
        return function (ray, sphere) {
          var r = sphere.radius;
          var c = sphere.center;
          var o = ray.o;
          var d = ray.d;
          var rSq = r * r;
          Vec3.subtract(e, c, o);
          var eSq = e.lengthSqr();
          var aLength = Vec3.dot(e, d);
          var fSq = rSq - (eSq - aLength * aLength);
          if (fSq < 0) {
            return 0;
          }
          var f = Math.sqrt(fSq);
          var t = eSq < rSq ? aLength + f : aLength - f;
          if (t < 0) {
            return 0;
          }
          return t;
        };
      }();
      var rayAABB = function () {
        var min = new Vec3();
        var max = new Vec3();
        return function (ray, aabb) {
          Vec3.subtract(min, aabb.center, aabb.halfExtents);
          Vec3.add(max, aabb.center, aabb.halfExtents);
          return rayAABB2$1(ray, min, max);
        };
      }();
      function rayAABB2$1(ray, min, max) {
        var o = ray.o;
        var d = ray.d;
        var ix = 1 / d.x;
        var iy = 1 / d.y;
        var iz = 1 / d.z;
        var t1 = (min.x - o.x) * ix;
        var t2 = (max.x - o.x) * ix;
        var t3 = (min.y - o.y) * iy;
        var t4 = (max.y - o.y) * iy;
        var t5 = (min.z - o.z) * iz;
        var t6 = (max.z - o.z) * iz;
        var tmin = Math.max(Math.max(Math.min(t1, t2), Math.min(t3, t4)), Math.min(t5, t6));
        var tmax = Math.min(Math.min(Math.max(t1, t2), Math.max(t3, t4)), Math.max(t5, t6));
        if (tmax < 0 || tmin > tmax) {
          return 0;
        }
        return tmin > 0 ? tmin : tmax;
      }
      var rayOBB = function () {
        var center = new Vec3();
        var o = new Vec3();
        var d = new Vec3();
        var X = new Vec3();
        var Y = new Vec3();
        var Z = new Vec3();
        var p = new Vec3();
        var size = new Array(3);
        var f = new Array(3);
        var e = new Array(3);
        var t = new Array(6);
        return function (ray, obb) {
          size[0] = obb.halfExtents.x;
          size[1] = obb.halfExtents.y;
          size[2] = obb.halfExtents.z;
          center = obb.center;
          o = ray.o;
          d = ray.d;
          Vec3.set(X, obb.orientation.m00, obb.orientation.m01, obb.orientation.m02);
          Vec3.set(Y, obb.orientation.m03, obb.orientation.m04, obb.orientation.m05);
          Vec3.set(Z, obb.orientation.m06, obb.orientation.m07, obb.orientation.m08);
          Vec3.subtract(p, center, o);
          f[0] = Vec3.dot(X, d);
          f[1] = Vec3.dot(Y, d);
          f[2] = Vec3.dot(Z, d);
          e[0] = Vec3.dot(X, p);
          e[1] = Vec3.dot(Y, p);
          e[2] = Vec3.dot(Z, p);
          for (var i = 0; i < 3; ++i) {
            if (f[i] === 0) {
              if (-e[i] - size[i] > 0 || -e[i] + size[i] < 0) {
                return 0;
              }
              f[i] = 0.0000001;
            }
            t[i * 2 + 0] = (e[i] + size[i]) / f[i];
            t[i * 2 + 1] = (e[i] - size[i]) / f[i];
          }
          var tmin = Math.max(Math.max(Math.min(t[0], t[1]), Math.min(t[2], t[3])), Math.min(t[4], t[5]));
          var tmax = Math.min(Math.min(Math.max(t[0], t[1]), Math.max(t[2], t[3])), Math.max(t[4], t[5]));
          if (tmax < 0 || tmin > tmax) {
            return 0;
          }
          return tmin > 0 ? tmin : tmax;
        };
      }();
      var rayCapsule = function () {
        var v3_0 = new Vec3();
        var v3_1 = new Vec3();
        var v3_2 = new Vec3();
        var v3_3 = new Vec3();
        var v3_4 = new Vec3();
        var v3_5 = new Vec3();
        var v3_6 = new Vec3();
        var sphere_0 = new Sphere();
        return function (ray, capsule) {
          var A = capsule.ellipseCenter0;
          var B = capsule.ellipseCenter1;
          var BA = Vec3.subtract(v3_1, B, A);
          if (BA.length() < EPSILON$3) {
            sphere_0.radius = capsule.radius;
            sphere_0.center.set(capsule.ellipseCenter0);
            return intersect.raySphere(ray, sphere_0);
          }
          var O = ray.o;
          var OA = Vec3.subtract(v3_2, O, A);
          var vRayNorm = Vec3.normalize(v3_0, ray.d);
          var VxBA = Vec3.cross(v3_3, vRayNorm, BA);
          var a = VxBA.lengthSqr();
          if (a === 0) {
            sphere_0.radius = capsule.radius;
            var BO = Vec3.subtract(v3_4, B, O);
            if (OA.lengthSqr() < BO.lengthSqr()) {
              sphere_0.center.set(A);
            } else {
              sphere_0.center.set(B);
            }
            return intersect.raySphere(ray, sphere_0);
          }
          var OAxBA = Vec3.cross(v3_4, OA, BA);
          var ab2 = BA.lengthSqr();
          var b = 2 * Vec3.dot(VxBA, OAxBA);
          var radiusSqr = capsule.radius * capsule.radius;
          var c = OAxBA.lengthSqr() - radiusSqr * ab2;
          var d = b * b - 4 * a * c;
          if (d < 0) {
            return 0;
          }
          var t = (-b - Math.sqrt(d)) / (2 * a);
          if (t < 0) {
            sphere_0.radius = capsule.radius;
            var _BO = Vec3.subtract(v3_5, B, O);
            if (OA.lengthSqr() < _BO.lengthSqr()) {
              sphere_0.center.set(capsule.ellipseCenter0);
            } else {
              sphere_0.center.set(capsule.ellipseCenter1);
            }
            return intersect.raySphere(ray, sphere_0);
          } else {
            var iPos = Vec3.scaleAndAdd(v3_5, ray.o, vRayNorm, t);
            var iPosLen = Vec3.subtract(v3_6, iPos, A);
            var tLimit = Vec3.dot(iPosLen, BA) / ab2;
            if (tLimit >= 0 && tLimit <= 1) {
              return t;
            } else if (tLimit < 0) {
              sphere_0.radius = capsule.radius;
              sphere_0.center.set(capsule.ellipseCenter0);
              return intersect.raySphere(ray, sphere_0);
            } else if (tLimit > 1) {
              sphere_0.radius = capsule.radius;
              sphere_0.center.set(capsule.ellipseCenter1);
              return intersect.raySphere(ray, sphere_0);
            } else {
              return 0;
            }
          }
        };
      }();
      var linePlane = function () {
        var ab = new Vec3(0, 0, 0);
        return function (line, plane) {
          Vec3.subtract(ab, line.e, line.s);
          var t = -point_plane(line.s, plane) / Vec3.dot(ab, plane.n);
          if (t < 0 || t > 1) {
            return 0;
          }
          return t;
        };
      }();
      var lineTriangle = function () {
        var ab = new Vec3(0, 0, 0);
        var ac = new Vec3(0, 0, 0);
        var qp = new Vec3(0, 0, 0);
        var ap = new Vec3(0, 0, 0);
        var n = new Vec3(0, 0, 0);
        var e = new Vec3(0, 0, 0);
        return function (line, triangle, outPt) {
          Vec3.subtract(ab, triangle.b, triangle.a);
          Vec3.subtract(ac, triangle.c, triangle.a);
          Vec3.subtract(qp, line.s, line.e);
          Vec3.cross(n, ab, ac);
          var det = Vec3.dot(qp, n);
          if (det <= 0.0) {
            return 0;
          }
          Vec3.subtract(ap, line.s, triangle.a);
          var t = Vec3.dot(ap, n);
          if (t < 0 || t > det) {
            return 0;
          }
          Vec3.cross(e, qp, ap);
          var v = Vec3.dot(ac, e);
          if (v < 0 || v > det) {
            return 0;
          }
          var w = -Vec3.dot(ab, e);
          if (w < 0.0 || v + w > det) {
            return 0;
          }
          if (outPt) {
            var invDet = 1.0 / det;
            v *= invDet;
            w *= invDet;
            var u = 1.0 - v - w;
            Vec3.set(outPt, triangle.a.x * u + triangle.b.x * v + triangle.c.x * w, triangle.a.y * u + triangle.b.y * v + triangle.c.y * w, triangle.a.z * u + triangle.b.z * v + triangle.c.z * w);
          }
          return 1;
        };
      }();
      var r_t = new Ray();
      function lineAABB(line, aabb) {
        r_t.o.set(line.s);
        Vec3.subtract(r_t.d, line.e, line.s);
        r_t.d.normalize();
        var min = rayAABB(r_t, aabb);
        var len = line.length();
        if (min <= len) {
          return min;
        } else {
          return 0;
        }
      }
      function lineOBB(line, obb) {
        r_t.o.set(line.s);
        Vec3.subtract(r_t.d, line.e, line.s);
        r_t.d.normalize();
        var min = rayOBB(r_t, obb);
        var len = line.length();
        if (min <= len) {
          return min;
        } else {
          return 0;
        }
      }
      function lineSphere(line, sphere) {
        r_t.o.set(line.s);
        Vec3.subtract(r_t.d, line.e, line.s);
        r_t.d.normalize();
        var min = raySphere(r_t, sphere);
        var len = line.length();
        if (min <= len) {
          return min;
        } else {
          return 0;
        }
      }
      var aabbWithAABB = function () {
        var aMin = new Vec3();
        var aMax = new Vec3();
        var bMin = new Vec3();
        var bMax = new Vec3();
        return function (aabb1, aabb2) {
          Vec3.subtract(aMin, aabb1.center, aabb1.halfExtents);
          Vec3.add(aMax, aabb1.center, aabb1.halfExtents);
          Vec3.subtract(bMin, aabb2.center, aabb2.halfExtents);
          Vec3.add(bMax, aabb2.center, aabb2.halfExtents);
          return aMin.x <= bMax.x && aMax.x >= bMin.x && aMin.y <= bMax.y && aMax.y >= bMin.y && aMin.z <= bMax.z && aMax.z >= bMin.z;
        };
      }();
      function getAABBVertices(min, max, out) {
        Vec3.set(out[0], min.x, max.y, max.z);
        Vec3.set(out[1], min.x, max.y, min.z);
        Vec3.set(out[2], min.x, min.y, max.z);
        Vec3.set(out[3], min.x, min.y, min.z);
        Vec3.set(out[4], max.x, max.y, max.z);
        Vec3.set(out[5], max.x, max.y, min.z);
        Vec3.set(out[6], max.x, min.y, max.z);
        Vec3.set(out[7], max.x, min.y, min.z);
      }
      function getOBBVertices(c, e, a1, a2, a3, out) {
        Vec3.set(out[0], c.x + a1.x * e.x + a2.x * e.y + a3.x * e.z, c.y + a1.y * e.x + a2.y * e.y + a3.y * e.z, c.z + a1.z * e.x + a2.z * e.y + a3.z * e.z);
        Vec3.set(out[1], c.x - a1.x * e.x + a2.x * e.y + a3.x * e.z, c.y - a1.y * e.x + a2.y * e.y + a3.y * e.z, c.z - a1.z * e.x + a2.z * e.y + a3.z * e.z);
        Vec3.set(out[2], c.x + a1.x * e.x - a2.x * e.y + a3.x * e.z, c.y + a1.y * e.x - a2.y * e.y + a3.y * e.z, c.z + a1.z * e.x - a2.z * e.y + a3.z * e.z);
        Vec3.set(out[3], c.x + a1.x * e.x + a2.x * e.y - a3.x * e.z, c.y + a1.y * e.x + a2.y * e.y - a3.y * e.z, c.z + a1.z * e.x + a2.z * e.y - a3.z * e.z);
        Vec3.set(out[4], c.x - a1.x * e.x - a2.x * e.y - a3.x * e.z, c.y - a1.y * e.x - a2.y * e.y - a3.y * e.z, c.z - a1.z * e.x - a2.z * e.y - a3.z * e.z);
        Vec3.set(out[5], c.x + a1.x * e.x - a2.x * e.y - a3.x * e.z, c.y + a1.y * e.x - a2.y * e.y - a3.y * e.z, c.z + a1.z * e.x - a2.z * e.y - a3.z * e.z);
        Vec3.set(out[6], c.x - a1.x * e.x + a2.x * e.y - a3.x * e.z, c.y - a1.y * e.x + a2.y * e.y - a3.y * e.z, c.z - a1.z * e.x + a2.z * e.y - a3.z * e.z);
        Vec3.set(out[7], c.x - a1.x * e.x - a2.x * e.y + a3.x * e.z, c.y - a1.y * e.x - a2.y * e.y + a3.y * e.z, c.z - a1.z * e.x - a2.z * e.y + a3.z * e.z);
      }
      function getInterval(vertices, axis) {
        var min = Vec3.dot(axis, vertices[0]);
        var max = min;
        for (var i = 1; i < 8; ++i) {
          var projection = Vec3.dot(axis, vertices[i]);
          min = projection < min ? projection : min;
          max = projection > max ? projection : max;
        }
        return [min, max];
      }
      var aabbWithOBB = function () {
        var test = new Array(15);
        for (var i = 0; i < 15; i++) {
          test[i] = new Vec3(0, 0, 0);
        }
        var vertices = new Array(8);
        var vertices2 = new Array(8);
        for (var _i = 0; _i < 8; _i++) {
          vertices[_i] = new Vec3(0, 0, 0);
          vertices2[_i] = new Vec3(0, 0, 0);
        }
        var min = new Vec3();
        var max = new Vec3();
        return function (aabb, obb) {
          Vec3.set(test[0], 1, 0, 0);
          Vec3.set(test[1], 0, 1, 0);
          Vec3.set(test[2], 0, 0, 1);
          Vec3.set(test[3], obb.orientation.m00, obb.orientation.m01, obb.orientation.m02);
          Vec3.set(test[4], obb.orientation.m03, obb.orientation.m04, obb.orientation.m05);
          Vec3.set(test[5], obb.orientation.m06, obb.orientation.m07, obb.orientation.m08);
          for (var _i2 = 0; _i2 < 3; ++_i2) {
            Vec3.cross(test[6 + _i2 * 3 + 0], test[_i2], test[3]);
            Vec3.cross(test[6 + _i2 * 3 + 1], test[_i2], test[4]);
            Vec3.cross(test[6 + _i2 * 3 + 1], test[_i2], test[5]);
          }
          Vec3.subtract(min, aabb.center, aabb.halfExtents);
          Vec3.add(max, aabb.center, aabb.halfExtents);
          getAABBVertices(min, max, vertices);
          getOBBVertices(obb.center, obb.halfExtents, test[3], test[4], test[5], vertices2);
          for (var j = 0; j < 15; ++j) {
            var a = getInterval(vertices, test[j]);
            var b = getInterval(vertices2, test[j]);
            if (b[0] > a[1] || a[0] > b[1]) {
              return 0;
            }
          }
          return 1;
        };
      }();
      var aabbPlane = function aabbPlane(aabb, plane) {
        var r = aabb.halfExtents.x * Math.abs(plane.n.x) + aabb.halfExtents.y * Math.abs(plane.n.y) + aabb.halfExtents.z * Math.abs(plane.n.z);
        var dot = Vec3.dot(plane.n, aabb.center);
        if (dot + r < plane.d) {
          return -1;
        } else if (dot - r > plane.d) {
          return 0;
        }
        return 1;
      };
      var aabbFrustum = function aabbFrustum(aabb, frustum) {
        for (var i = 0; i < frustum.planes.length; i++) {
          if (aabbPlane(aabb, frustum.planes[i]) === -1) {
            return 0;
          }
        }
        return 1;
      };
      var aabbFrustumCompletelyInside = function aabbFrustumCompletelyInside(aabb, frustum) {
        for (var i = 0; i < frustum.planes.length; i++) {
          if (aabbPlane(aabb, frustum.planes[i]) !== 0) {
            return 0;
          }
        }
        return 1;
      };
      var aabbFrustumAccurate = function () {
        var tmp = new Array(8);
        var out1 = 0;
        var out2 = 0;
        for (var i = 0; i < tmp.length; i++) {
          tmp[i] = new Vec3(0, 0, 0);
        }
        return function (aabb, frustum) {
          var result = 0;
          var intersects = false;
          for (var _i3 = 0; _i3 < frustum.planes.length; _i3++) {
            result = aabbPlane(aabb, frustum.planes[_i3]);
            if (result === -1) return 0;else if (result === 1) {
              intersects = true;
            }
          }
          if (!intersects) {
            return 1;
          }
          for (var _i4 = 0; _i4 < frustum.vertices.length; _i4++) {
            Vec3.subtract(tmp[_i4], frustum.vertices[_i4], aabb.center);
          }
          out1 = 0, out2 = 0;
          for (var _i5 = 0; _i5 < frustum.vertices.length; _i5++) {
            if (tmp[_i5].x > aabb.halfExtents.x) {
              out1++;
            } else if (tmp[_i5].x < -aabb.halfExtents.x) {
              out2++;
            }
          }
          if (out1 === frustum.vertices.length || out2 === frustum.vertices.length) {
            return 0;
          }
          out1 = 0;
          out2 = 0;
          for (var _i6 = 0; _i6 < frustum.vertices.length; _i6++) {
            if (tmp[_i6].y > aabb.halfExtents.y) {
              out1++;
            } else if (tmp[_i6].y < -aabb.halfExtents.y) {
              out2++;
            }
          }
          if (out1 === frustum.vertices.length || out2 === frustum.vertices.length) {
            return 0;
          }
          out1 = 0;
          out2 = 0;
          for (var _i7 = 0; _i7 < frustum.vertices.length; _i7++) {
            if (tmp[_i7].z > aabb.halfExtents.z) {
              out1++;
            } else if (tmp[_i7].z < -aabb.halfExtents.z) {
              out2++;
            }
          }
          if (out1 === frustum.vertices.length || out2 === frustum.vertices.length) {
            return 0;
          }
          return 1;
        };
      }();
      var obbPoint = function () {
        var tmp = new Vec3(0, 0, 0);
        var m3 = new Mat3();
        var lessThan = function lessThan(a, b) {
          return Math.abs(a.x) < b.x && Math.abs(a.y) < b.y && Math.abs(a.z) < b.z;
        };
        return function (obb, point) {
          Vec3.subtract(tmp, point, obb.center);
          Vec3.transformMat3(tmp, tmp, Mat3.transpose(m3, obb.orientation));
          return lessThan(tmp, obb.halfExtents);
        };
      }();
      var obbPlane = function () {
        var absDot = function absDot(n, x, y, z) {
          return Math.abs(n.x * x + n.y * y + n.z * z);
        };
        return function (obb, plane) {
          var r = obb.halfExtents.x * absDot(plane.n, obb.orientation.m00, obb.orientation.m01, obb.orientation.m02) + obb.halfExtents.y * absDot(plane.n, obb.orientation.m03, obb.orientation.m04, obb.orientation.m05) + obb.halfExtents.z * absDot(plane.n, obb.orientation.m06, obb.orientation.m07, obb.orientation.m08);
          var dot = Vec3.dot(plane.n, obb.center);
          if (dot + r < plane.d) {
            return -1;
          } else if (dot - r > plane.d) {
            return 0;
          }
          return 1;
        };
      }();
      var obbFrustum = function obbFrustum(obb, frustum) {
        for (var i = 0; i < frustum.planes.length; i++) {
          if (obbPlane(obb, frustum.planes[i]) === -1) {
            return 0;
          }
        }
        return 1;
      };
      var obbFrustumAccurate = function () {
        var tmp = new Array(8);
        var dist = 0;
        var out1 = 0;
        var out2 = 0;
        for (var i = 0; i < tmp.length; i++) {
          tmp[i] = new Vec3(0, 0, 0);
        }
        var dot = function dot(n, x, y, z) {
          return n.x * x + n.y * y + n.z * z;
        };
        return function (obb, frustum) {
          var result = 0;
          var intersects = false;
          for (var _i8 = 0; _i8 < frustum.planes.length; _i8++) {
            result = obbPlane(obb, frustum.planes[_i8]);
            if (result === -1) return 0;else if (result === 1) {
              intersects = true;
            }
          }
          if (!intersects) {
            return 1;
          }
          for (var _i9 = 0; _i9 < frustum.vertices.length; _i9++) {
            Vec3.subtract(tmp[_i9], frustum.vertices[_i9], obb.center);
          }
          out1 = 0, out2 = 0;
          for (var _i10 = 0; _i10 < frustum.vertices.length; _i10++) {
            dist = dot(tmp[_i10], obb.orientation.m00, obb.orientation.m01, obb.orientation.m02);
            if (dist > obb.halfExtents.x) {
              out1++;
            } else if (dist < -obb.halfExtents.x) {
              out2++;
            }
          }
          if (out1 === frustum.vertices.length || out2 === frustum.vertices.length) {
            return 0;
          }
          out1 = 0;
          out2 = 0;
          for (var _i11 = 0; _i11 < frustum.vertices.length; _i11++) {
            dist = dot(tmp[_i11], obb.orientation.m03, obb.orientation.m04, obb.orientation.m05);
            if (dist > obb.halfExtents.y) {
              out1++;
            } else if (dist < -obb.halfExtents.y) {
              out2++;
            }
          }
          if (out1 === frustum.vertices.length || out2 === frustum.vertices.length) {
            return 0;
          }
          out1 = 0;
          out2 = 0;
          for (var _i12 = 0; _i12 < frustum.vertices.length; _i12++) {
            dist = dot(tmp[_i12], obb.orientation.m06, obb.orientation.m07, obb.orientation.m08);
            if (dist > obb.halfExtents.z) {
              out1++;
            } else if (dist < -obb.halfExtents.z) {
              out2++;
            }
          }
          if (out1 === frustum.vertices.length || out2 === frustum.vertices.length) {
            return 0;
          }
          return 1;
        };
      }();
      var obbWithOBB = function () {
        var test = new Array(15);
        for (var i = 0; i < 15; i++) {
          test[i] = new Vec3(0, 0, 0);
        }
        var vertices = new Array(8);
        var vertices2 = new Array(8);
        for (var _i13 = 0; _i13 < 8; _i13++) {
          vertices[_i13] = new Vec3(0, 0, 0);
          vertices2[_i13] = new Vec3(0, 0, 0);
        }
        return function (obb1, obb2) {
          Vec3.set(test[0], obb1.orientation.m00, obb1.orientation.m01, obb1.orientation.m02);
          Vec3.set(test[1], obb1.orientation.m03, obb1.orientation.m04, obb1.orientation.m05);
          Vec3.set(test[2], obb1.orientation.m06, obb1.orientation.m07, obb1.orientation.m08);
          Vec3.set(test[3], obb2.orientation.m00, obb2.orientation.m01, obb2.orientation.m02);
          Vec3.set(test[4], obb2.orientation.m03, obb2.orientation.m04, obb2.orientation.m05);
          Vec3.set(test[5], obb2.orientation.m06, obb2.orientation.m07, obb2.orientation.m08);
          for (var _i14 = 0; _i14 < 3; ++_i14) {
            Vec3.cross(test[6 + _i14 * 3 + 0], test[_i14], test[3]);
            Vec3.cross(test[6 + _i14 * 3 + 1], test[_i14], test[4]);
            Vec3.cross(test[6 + _i14 * 3 + 2], test[_i14], test[5]);
          }
          getOBBVertices(obb1.center, obb1.halfExtents, test[0], test[1], test[2], vertices);
          getOBBVertices(obb2.center, obb2.halfExtents, test[3], test[4], test[5], vertices2);
          for (var _i15 = 0; _i15 < 15; ++_i15) {
            var a = getInterval(vertices, test[_i15]);
            var b = getInterval(vertices2, test[_i15]);
            if (b[0] > a[1] || a[0] > b[1]) {
              return 0;
            }
          }
          return 1;
        };
      }();
      var obbCapsule = function () {
        var sphere_0 = new Sphere();
        var v3_0 = new Vec3();
        var v3_1 = new Vec3();
        var v3_2 = new Vec3();
        var v3_verts8 = new Array(8);
        for (var i = 0; i < 8; i++) {
          v3_verts8[i] = new Vec3();
        }
        var v3_axis8 = new Array(8);
        for (var _i16 = 0; _i16 < 8; _i16++) {
          v3_axis8[_i16] = new Vec3();
        }
        return function (obb, capsule) {
          var h = Vec3.squaredDistance(capsule.ellipseCenter0, capsule.ellipseCenter1);
          if (h === 0) {
            sphere_0.radius = capsule.radius;
            sphere_0.center.set(capsule.ellipseCenter0);
            return intersect.sphereOBB(sphere_0, obb);
          } else {
            v3_0.x = obb.orientation.m00;
            v3_0.y = obb.orientation.m01;
            v3_0.z = obb.orientation.m02;
            v3_1.x = obb.orientation.m03;
            v3_1.y = obb.orientation.m04;
            v3_1.z = obb.orientation.m05;
            v3_2.x = obb.orientation.m06;
            v3_2.y = obb.orientation.m07;
            v3_2.z = obb.orientation.m08;
            getOBBVertices(obb.center, obb.halfExtents, v3_0, v3_1, v3_2, v3_verts8);
            var axes = v3_axis8;
            var a0 = Vec3.copy(axes[0], v3_0);
            var a1 = Vec3.copy(axes[1], v3_1);
            var a2 = Vec3.copy(axes[2], v3_2);
            var C = Vec3.subtract(axes[3], capsule.center, obb.center);
            C.normalize();
            var B = Vec3.subtract(axes[4], capsule.ellipseCenter0, capsule.ellipseCenter1);
            B.normalize();
            Vec3.cross(axes[5], a0, B);
            Vec3.cross(axes[6], a1, B);
            Vec3.cross(axes[7], a2, B);
            for (var _i17 = 0; _i17 < 8; ++_i17) {
              var a = getInterval(v3_verts8, axes[_i17]);
              var d0 = Vec3.dot(axes[_i17], capsule.ellipseCenter0);
              var d1 = Vec3.dot(axes[_i17], capsule.ellipseCenter1);
              var max_d = Math.max(d0, d1);
              var min_d = Math.min(d0, d1);
              var d_min = min_d - capsule.radius;
              var d_max = max_d + capsule.radius;
              if (d_min > a[1] || a[0] > d_max) {
                return 0;
              }
            }
            return 1;
          }
        };
      }();
      var spherePlane = function spherePlane(sphere, plane) {
        var dot = Vec3.dot(plane.n, sphere.center);
        var r = sphere.radius * plane.n.length();
        if (dot + r < plane.d) {
          return -1;
        } else if (dot - r > plane.d) {
          return 0;
        }
        return 1;
      };
      var sphereFrustum = function sphereFrustum(sphere, frustum) {
        for (var i = 0; i < frustum.planes.length; i++) {
          if (spherePlane(sphere, frustum.planes[i]) === -1) {
            return 0;
          }
        }
        return 1;
      };
      var sphereFrustumAccurate = function () {
        var pt = new Vec3(0, 0, 0);
        var map = [1, -1, 1, -1, 1, -1];
        return function (sphere, frustum) {
          for (var i = 0; i < 6; i++) {
            var _plane = frustum.planes[i];
            var _r = sphere.radius;
            var c = sphere.center;
            var n = _plane.n;
            var d = _plane.d;
            var dot = Vec3.dot(n, c);
            if (dot + _r < d) return 0;else if (dot - _r > d) {
              continue;
            }
            Vec3.add(pt, c, Vec3.multiplyScalar(pt, n, _r));
            for (var j = 0; j < 6; j++) {
              if (j === i || j === i + map[i]) {
                continue;
              }
              var test = frustum.planes[j];
              if (Vec3.dot(test.n, pt) < test.d) {
                return 0;
              }
            }
          }
          return 1;
        };
      }();
      var sphereWithSphere = function sphereWithSphere(sphere0, sphere1) {
        var r = sphere0.radius + sphere1.radius;
        return Vec3.squaredDistance(sphere0.center, sphere1.center) < r * r;
      };
      var sphereAABB = function () {
        var pt = new Vec3();
        return function (sphere, aabb) {
          pt_point_aabb(pt, sphere.center, aabb);
          return Vec3.squaredDistance(sphere.center, pt) < sphere.radius * sphere.radius;
        };
      }();
      var sphereOBB = function () {
        var pt = new Vec3();
        return function (sphere, obb) {
          pt_point_obb(pt, sphere.center, obb);
          return Vec3.squaredDistance(sphere.center, pt) < sphere.radius * sphere.radius;
        };
      }();
      var sphereCapsule = function () {
        var v3_0 = new Vec3();
        var v3_1 = new Vec3();
        return function (sphere, capsule) {
          var r = sphere.radius + capsule.radius;
          var squaredR = r * r;
          var h = Vec3.squaredDistance(capsule.ellipseCenter0, capsule.ellipseCenter1);
          if (h === 0) {
            return Vec3.squaredDistance(sphere.center, capsule.center) < squaredR;
          } else {
            Vec3.subtract(v3_0, sphere.center, capsule.ellipseCenter0);
            Vec3.subtract(v3_1, capsule.ellipseCenter1, capsule.ellipseCenter0);
            var t = Vec3.dot(v3_0, v3_1) / h;
            if (t < 0) {
              return Vec3.squaredDistance(sphere.center, capsule.ellipseCenter0) < squaredR;
            } else if (t > 1) {
              return Vec3.squaredDistance(sphere.center, capsule.ellipseCenter1) < squaredR;
            } else {
              Vec3.scaleAndAdd(v3_0, capsule.ellipseCenter0, v3_1, t);
              return Vec3.squaredDistance(sphere.center, v3_0) < squaredR;
            }
          }
        };
      }();
      var capsuleWithCapsule = function () {
        var v3_0 = new Vec3();
        var v3_1 = new Vec3();
        var v3_2 = new Vec3();
        var v3_3 = new Vec3();
        var v3_4 = new Vec3();
        var v3_5 = new Vec3();
        return function capsuleWithCapsule(capsuleA, capsuleB) {
          var u = Vec3.subtract(v3_0, capsuleA.ellipseCenter1, capsuleA.ellipseCenter0);
          var v = Vec3.subtract(v3_1, capsuleB.ellipseCenter1, capsuleB.ellipseCenter0);
          var w = Vec3.subtract(v3_2, capsuleA.ellipseCenter0, capsuleB.ellipseCenter0);
          var a = Vec3.dot(u, u);
          var b = Vec3.dot(u, v);
          var c = Vec3.dot(v, v);
          var d = Vec3.dot(u, w);
          var e = Vec3.dot(v, w);
          var D = a * c - b * b;
          var sN;
          var sD = D;
          var tN;
          var tD = D;
          if (D < EPSILON$3) {
            sN = 0.0;
            sD = 1.0;
            tN = e;
            tD = c;
          } else {
            sN = b * e - c * d;
            tN = a * e - b * d;
            if (sN < 0.0) {
              sN = 0.0;
              tN = e;
              tD = c;
            } else if (sN > sD) {
              sN = sD;
              tN = e + b;
              tD = c;
            }
          }
          if (tN < 0.0) {
            tN = 0.0;
            if (-d < 0.0) {
              sN = 0.0;
            } else if (-d > a) {
              sN = sD;
            } else {
              sN = -d;
              sD = a;
            }
          } else if (tN > tD) {
            tN = tD;
            if (-d + b < 0.0) {
              sN = 0;
            } else if (-d + b > a) {
              sN = sD;
            } else {
              sN = -d + b;
              sD = a;
            }
          }
          var sc = Math.abs(sN) < EPSILON$3 ? 0.0 : sN / sD;
          var tc = Math.abs(tN) < EPSILON$3 ? 0.0 : tN / tD;
          var dP = v3_3;
          dP.set(w);
          dP.add(Vec3.multiplyScalar(v3_4, u, sc));
          dP.subtract(Vec3.multiplyScalar(v3_5, v, tc));
          var radius = capsuleA.radius + capsuleB.radius;
          return dP.lengthSqr() < radius * radius;
        };
      }();
      var intersect = {
        raySphere: raySphere,
        rayAABB: rayAABB,
        rayOBB: rayOBB,
        rayPlane: rayPlane,
        rayTriangle: rayTriangle,
        rayCapsule: rayCapsule,
        raySubMesh: null,
        rayMesh: null,
        rayModel: null,
        lineSphere: lineSphere,
        lineAABB: lineAABB,
        lineOBB: lineOBB,
        linePlane: linePlane,
        lineTriangle: lineTriangle,
        sphereWithSphere: sphereWithSphere,
        sphereAABB: sphereAABB,
        sphereOBB: sphereOBB,
        spherePlane: spherePlane,
        sphereFrustum: sphereFrustum,
        sphereFrustumAccurate: sphereFrustumAccurate,
        sphereCapsule: sphereCapsule,
        aabbWithAABB: aabbWithAABB,
        aabbWithOBB: aabbWithOBB,
        aabbPlane: aabbPlane,
        aabbFrustum: aabbFrustum,
        aabbFrustumAccurate: aabbFrustumAccurate,
        obbWithOBB: obbWithOBB,
        obbPlane: obbPlane,
        obbFrustum: obbFrustum,
        obbFrustumAccurate: obbFrustumAccurate,
        obbPoint: obbPoint,
        obbCapsule: obbCapsule,
        aabbFrustumCompletelyInside: aabbFrustumCompletelyInside,
        capsuleWithCapsule: capsuleWithCapsule,
        resolve: function resolve(g1, g2, outPt) {
          if (outPt === void 0) {
            outPt = null;
          }
          var type1 = g1._type;
          var type2 = g2._type;
          var resolver = this[type1 | type2];
          return type1 < type2 ? resolver(g1, g2, outPt) : resolver(g2, g1, outPt);
        }
      };
      intersect[enums.SHAPE_RAY | enums.SHAPE_SPHERE] = raySphere;
      intersect[enums.SHAPE_RAY | enums.SHAPE_AABB] = rayAABB;
      intersect[enums.SHAPE_RAY | enums.SHAPE_OBB] = rayOBB;
      intersect[enums.SHAPE_RAY | enums.SHAPE_PLANE] = rayPlane;
      intersect[enums.SHAPE_RAY | enums.SHAPE_TRIANGLE] = rayTriangle;
      intersect[enums.SHAPE_RAY | enums.SHAPE_CAPSULE] = rayCapsule;
      intersect[enums.SHAPE_LINE | enums.SHAPE_SPHERE] = lineSphere;
      intersect[enums.SHAPE_LINE | enums.SHAPE_AABB] = lineAABB;
      intersect[enums.SHAPE_LINE | enums.SHAPE_OBB] = lineOBB;
      intersect[enums.SHAPE_LINE | enums.SHAPE_PLANE] = linePlane;
      intersect[enums.SHAPE_LINE | enums.SHAPE_TRIANGLE] = lineTriangle;
      intersect[enums.SHAPE_SPHERE] = sphereWithSphere;
      intersect[enums.SHAPE_SPHERE | enums.SHAPE_AABB] = sphereAABB;
      intersect[enums.SHAPE_SPHERE | enums.SHAPE_OBB] = sphereOBB;
      intersect[enums.SHAPE_SPHERE | enums.SHAPE_PLANE] = spherePlane;
      intersect[enums.SHAPE_SPHERE | enums.SHAPE_FRUSTUM] = sphereFrustum;
      intersect[enums.SHAPE_SPHERE | enums.SHAPE_FRUSTUM_ACCURATE] = sphereFrustumAccurate;
      intersect[enums.SHAPE_SPHERE | enums.SHAPE_CAPSULE] = sphereCapsule;
      intersect[enums.SHAPE_AABB] = aabbWithAABB;
      intersect[enums.SHAPE_AABB | enums.SHAPE_OBB] = aabbWithOBB;
      intersect[enums.SHAPE_AABB | enums.SHAPE_PLANE] = aabbPlane;
      intersect[enums.SHAPE_AABB | enums.SHAPE_FRUSTUM] = aabbFrustum;
      intersect[enums.SHAPE_AABB | enums.SHAPE_FRUSTUM_ACCURATE] = aabbFrustumAccurate;
      intersect[enums.SHAPE_OBB] = obbWithOBB;
      intersect[enums.SHAPE_OBB | enums.SHAPE_PLANE] = obbPlane;
      intersect[enums.SHAPE_OBB | enums.SHAPE_FRUSTUM] = obbFrustum;
      intersect[enums.SHAPE_OBB | enums.SHAPE_FRUSTUM_ACCURATE] = obbFrustumAccurate;
      intersect[enums.SHAPE_OBB | enums.SHAPE_CAPSULE] = obbCapsule;
      intersect[enums.SHAPE_CAPSULE] = capsuleWithCapsule;

      var _v3_tmp = new Vec3();
      var _v3_tmp2 = new Vec3();
      var _m3_tmp = new Mat3();
      var transform_extent_m3 = function transform_extent_m3(out, extent, m3) {
        _m3_tmp.m00 = Math.abs(m3.m00);
        _m3_tmp.m01 = Math.abs(m3.m01);
        _m3_tmp.m02 = Math.abs(m3.m02);
        _m3_tmp.m03 = Math.abs(m3.m03);
        _m3_tmp.m04 = Math.abs(m3.m04);
        _m3_tmp.m05 = Math.abs(m3.m05);
        _m3_tmp.m06 = Math.abs(m3.m06);
        _m3_tmp.m07 = Math.abs(m3.m07);
        _m3_tmp.m08 = Math.abs(m3.m08);
        Vec3.transformMat3(out, extent, _m3_tmp);
      };
      var OBB = function () {
        OBB.create = function create(cx, cy, cz, hw, hh, hl, ox_1, ox_2, ox_3, oy_1, oy_2, oy_3, oz_1, oz_2, oz_3) {
          return new OBB(cx, cy, cz, hw, hh, hl, ox_1, ox_2, ox_3, oy_1, oy_2, oy_3, oz_1, oz_2, oz_3);
        };
        OBB.clone = function clone(a) {
          return new OBB(a.center.x, a.center.y, a.center.z, a.halfExtents.x, a.halfExtents.y, a.halfExtents.z, a.orientation.m00, a.orientation.m01, a.orientation.m02, a.orientation.m03, a.orientation.m04, a.orientation.m05, a.orientation.m06, a.orientation.m07, a.orientation.m08);
        };
        OBB.copy = function copy(out, a) {
          Vec3.copy(out.center, a.center);
          Vec3.copy(out.halfExtents, a.halfExtents);
          Mat3.copy(out.orientation, a.orientation);
          return out;
        };
        OBB.fromPoints = function fromPoints(out, minPos, maxPos) {
          Vec3.multiplyScalar(out.center, Vec3.add(_v3_tmp, minPos, maxPos), 0.5);
          Vec3.multiplyScalar(out.halfExtents, Vec3.subtract(_v3_tmp2, maxPos, minPos), 0.5);
          Mat3.identity(out.orientation);
          return out;
        };
        OBB.set = function set(out, cx, cy, cz, hw, hh, hl, ox_1, ox_2, ox_3, oy_1, oy_2, oy_3, oz_1, oz_2, oz_3) {
          Vec3.set(out.center, cx, cy, cz);
          Vec3.set(out.halfExtents, hw, hh, hl);
          Mat3.set(out.orientation, ox_1, ox_2, ox_3, oy_1, oy_2, oy_3, oz_1, oz_2, oz_3);
          return out;
        };
        function OBB(cx, cy, cz, hw, hh, hl, ox_1, ox_2, ox_3, oy_1, oy_2, oy_3, oz_1, oz_2, oz_3) {
          if (cx === void 0) {
            cx = 0;
          }
          if (cy === void 0) {
            cy = 0;
          }
          if (cz === void 0) {
            cz = 0;
          }
          if (hw === void 0) {
            hw = 1;
          }
          if (hh === void 0) {
            hh = 1;
          }
          if (hl === void 0) {
            hl = 1;
          }
          if (ox_1 === void 0) {
            ox_1 = 1;
          }
          if (ox_2 === void 0) {
            ox_2 = 0;
          }
          if (ox_3 === void 0) {
            ox_3 = 0;
          }
          if (oy_1 === void 0) {
            oy_1 = 0;
          }
          if (oy_2 === void 0) {
            oy_2 = 1;
          }
          if (oy_3 === void 0) {
            oy_3 = 0;
          }
          if (oz_1 === void 0) {
            oz_1 = 0;
          }
          if (oz_2 === void 0) {
            oz_2 = 0;
          }
          if (oz_3 === void 0) {
            oz_3 = 1;
          }
          this.center = void 0;
          this.halfExtents = void 0;
          this.orientation = void 0;
          this._type = void 0;
          this._type = enums.SHAPE_OBB;
          this.center = new Vec3(cx, cy, cz);
          this.halfExtents = new Vec3(hw, hh, hl);
          this.orientation = new Mat3(ox_1, ox_2, ox_3, oy_1, oy_2, oy_3, oz_1, oz_2, oz_3);
        }
        var _proto = OBB.prototype;
        _proto.getBoundary = function getBoundary(minPos, maxPos) {
          transform_extent_m3(_v3_tmp, this.halfExtents, this.orientation);
          Vec3.subtract(minPos, this.center, _v3_tmp);
          Vec3.add(maxPos, this.center, _v3_tmp);
        };
        _proto.transform = function transform(m, pos, rot, scale, out) {
          Vec3.transformMat4(out.center, this.center, m);
          Mat3.fromQuat(out.orientation, rot);
          Vec3.multiply(out.halfExtents, this.halfExtents, scale);
        };
        _proto.translateAndRotate = function translateAndRotate(m, rot, out) {
          Vec3.transformMat4(out.center, this.center, m);
          Mat3.fromQuat(out.orientation, rot);
        };
        _proto.setScale = function setScale(scale, out) {
          Vec3.multiply(out.halfExtents, this.halfExtents, scale);
        };
        _createClass(OBB, [{
          key: "type",
          get: function get() {
            return this._type;
          }
        }]);
        return OBB;
      }();

      function binarySearch(array, value) {
        return binarySearchEpsilon(array, value, 0);
      }
      function binarySearchEpsilon(array, value, EPSILON) {
        if (EPSILON === void 0) {
          EPSILON = 1e-6;
        }
        var low = 0;
        var high = array.length - 1;
        var middle = high >>> 1;
        for (; low <= high; middle = low + high >>> 1) {
          var test = array[middle];
          if (test > value + EPSILON) {
            high = middle - 1;
          } else if (test < value - EPSILON) {
            low = middle + 1;
          } else {
            return middle;
          }
        }
        return ~low;
      }
      function binarySearchBy(array, value, lessThan) {
        var low = 0;
        var high = array.length - 1;
        var middle = high >>> 1;
        for (; low <= high; middle = low + high >>> 1) {
          var test = array[middle];
          if (lessThan(test, value) < 0) {
            high = middle - 1;
          } else if (lessThan(test, value) > 0) {
            low = middle + 1;
          } else {
            return middle;
          }
        }
        return ~low;
      }

      var _Symbol$iterator$1;
      _Symbol$iterator$1 = Symbol.iterator;
      var KeyframeCurve = function () {
        function KeyframeCurve() {
          this._times = [];
          this._values = [];
        }
        var _proto = KeyframeCurve.prototype;
        _proto[_Symbol$iterator$1] = function () {
          var _this = this;
          var index = 0;
          return {
            next: function next() {
              if (index >= _this._times.length) {
                return {
                  done: true,
                  value: undefined
                };
              } else {
                var value = [_this._times[index], _this._values[index]];
                ++index;
                return {
                  done: false,
                  value: value
                };
              }
            }
          };
        };
        _proto.keyframes = function keyframes() {
          return this;
        };
        _proto.times = function times() {
          return this._times;
        };
        _proto.values = function values() {
          return this._values;
        };
        _proto.getKeyframeTime = function getKeyframeTime(index) {
          return this._times[index];
        };
        _proto.getKeyframeValue = function getKeyframeValue(index) {
          return this._values[index];
        };
        _proto.addKeyFrame = function addKeyFrame(time, keyframeValue) {
          return this._insertNewKeyframe(time, keyframeValue);
        };
        _proto.removeKeyframe = function removeKeyframe(index) {
          this._times.splice(index, 1);
          this._values.splice(index, 1);
        };
        _proto.indexOfKeyframe = function indexOfKeyframe(time) {
          return binarySearchEpsilon(this._times, time);
        };
        _proto.updateTime = function updateTime(index, time) {
          var value = this._values[index];
          this.removeKeyframe(index);
          this._insertNewKeyframe(time, value);
        };
        _proto.assignSorted = function assignSorted(times, values) {
          if (values !== undefined) {
            assertIsTrue(Array.isArray(times));
            this.setKeyframes(times.slice(), values.slice());
          } else {
            var _keyframes = Array.from(times);
            this.setKeyframes(_keyframes.map(function (_ref) {
              var time = _ref[0];
              return time;
            }), _keyframes.map(function (_ref2) {
              var value = _ref2[1];
              return value;
            }));
          }
        };
        _proto.clear = function clear() {
          this._times.length = 0;
          this._values.length = 0;
        };
        _proto.searchKeyframe = function searchKeyframe(time) {
          return binarySearchEpsilon(this._times, time);
        };
        _proto.setKeyframes = function setKeyframes(times, values) {
          assertIsTrue(times.length === values.length);
          assertIsTrue(isSorted(times));
          this._times = times;
          this._values = values;
        };
        _proto._insertNewKeyframe = function _insertNewKeyframe(time, value) {
          var times = this._times;
          var values = this._values;
          var nFrames = times.length;
          var index = binarySearchEpsilon(times, time);
          if (index >= 0) {
            return index;
          }
          var iNext = ~index;
          if (iNext === 0) {
            times.unshift(time);
            values.unshift(value);
          } else if (iNext === nFrames) {
            times.push(time);
            values.push(value);
          } else {
            assertIsTrue(nFrames > 1);
            times.splice(iNext - 1, 0, time);
            values.splice(iNext - 1, 0, value);
          }
          return iNext;
        };
        _createClass(KeyframeCurve, [{
          key: "keyFramesCount",
          get: function get() {
            return this._times.length;
          }
        }, {
          key: "rangeMin",
          get: function get() {
            return this._times[0];
          }
        }, {
          key: "rangeMax",
          get: function get() {
            return this._times[this._values.length - 1];
          }
        }]);
        return KeyframeCurve;
      }();
      CCClass.fastDefine('cc.KeyframeCurve', KeyframeCurve, {
        _times: [],
        _values: []
      });
      function isSorted(values) {
        return values.every(function (value, index, array) {
          return index === 0 || value > array[index - 1] || approx(value, array[index - 1], 1e-6);
        });
      }

      var RealInterpolationMode; exports('ch', RealInterpolationMode);
      (function (RealInterpolationMode) {
        RealInterpolationMode[RealInterpolationMode["LINEAR"] = 0] = "LINEAR";
        RealInterpolationMode[RealInterpolationMode["CONSTANT"] = 1] = "CONSTANT";
        RealInterpolationMode[RealInterpolationMode["CUBIC"] = 2] = "CUBIC";
      })(RealInterpolationMode || (exports('ch', RealInterpolationMode = {})));
      var ExtrapolationMode; exports('ci', ExtrapolationMode);
      (function (ExtrapolationMode) {
        ExtrapolationMode[ExtrapolationMode["LINEAR"] = 0] = "LINEAR";
        ExtrapolationMode[ExtrapolationMode["CLAMP"] = 1] = "CLAMP";
        ExtrapolationMode[ExtrapolationMode["LOOP"] = 2] = "LOOP";
        ExtrapolationMode[ExtrapolationMode["PING_PONG"] = 3] = "PING_PONG";
      })(ExtrapolationMode || (exports('ci', ExtrapolationMode = {})));
      var TangentWeightMode; exports('cj', TangentWeightMode);
      (function (TangentWeightMode) {
        TangentWeightMode[TangentWeightMode["NONE"] = 0] = "NONE";
        TangentWeightMode[TangentWeightMode["LEFT"] = 1] = "LEFT";
        TangentWeightMode[TangentWeightMode["RIGHT"] = 2] = "RIGHT";
        TangentWeightMode[TangentWeightMode["BOTH"] = 3] = "BOTH";
      })(TangentWeightMode || (exports('cj', TangentWeightMode = {})));

      function solveCubic(coeff0, coeff1, coeff2, coeff3, solutions) {
        var a = coeff2 / coeff3;
        var b = coeff1 / coeff3;
        var c = coeff0 / coeff3;
        var sqrA = a * a;
        var p = 1.0 / 3.0 * (-1.0 / 3 * sqrA + b);
        var q = 1.0 / 2.0 * (2.0 / 27.0 * a * sqrA - 1.0 / 3 * a * b + c);
        var cubicP = p * p * p;
        var d = q * q + cubicP;
        var nSolutions = 0;
        if (isZero(d)) {
          if (isZero(q)) {
            solutions[0] = 0;
            return 1;
          } else {
            var u = Math.cbrt(-q);
            solutions[0] = 2 * u;
            solutions[1] = -u;
            return 2;
          }
        } else if (d < 0) {
          var phi = 1.0 / 3 * Math.acos(-q / Math.sqrt(-cubicP));
          var t = 2 * Math.sqrt(-p);
          solutions[0] = t * Math.cos(phi);
          solutions[1] = -t * Math.cos(phi + Math.PI / 3);
          solutions[2] = -t * Math.cos(phi - Math.PI / 3);
          nSolutions = 3;
        } else {
          var sqrtD = Math.sqrt(d);
          var _u = Math.cbrt(sqrtD - q);
          var v = -Math.cbrt(sqrtD + q);
          solutions[0] = _u + v;
          nSolutions = 1;
        }
        var sub = 1.0 / 3 * a;
        for (var i = 0; i < nSolutions; ++i) {
          solutions[i] -= sub;
        }
        return nSolutions;
      }
      var EQN_EPS = 1e-9;
      function isZero(x) {
        return x > -EQN_EPS && x < EQN_EPS;
      }

      function applyDecoratedInitializer(target, property, decorators, initializer) {
        return decorators.slice().reverse().reduce(function (decoratedInitializer, decorator) {
          return decorator(target, property, decoratedInitializer) || decoratedInitializer;
        }, initializer);
      }

      var emptyDecorator = function emptyDecorator() {};
      var emptyDecoratorFn = function emptyDecoratorFn() {
        return emptyDecorator;
      };
      var emptySmartClassDecorator = makeSmartClassDecorator(function () {});
      function makeSmartClassDecorator(decorate) {
        return proxyFn;
        function proxyFn(target) {
          if (typeof target === 'function') {
            return decorate(target);
          } else {
            return function (constructor) {
              return decorate(constructor, target);
            };
          }
        }
      }
      function writeEditorClassProperty(constructor, propertyName, value) {
        var cache = getClassCache(constructor);
        if (cache) {
          var proto = getSubDict(cache, 'proto');
          getSubDict(proto, 'editor')[propertyName] = value;
        }
      }
      function makeEditorClassDecoratorFn(propertyName) {
        return function (value) {
          return function (constructor) {
            writeEditorClassProperty(constructor, propertyName, value);
          };
        };
      }
      var CACHE_KEY = '__ccclassCache__';
      function getClassCache(ctor, decoratorName) {
        return getSubDict(ctor, CACHE_KEY);
      }
      function getSubDict(obj, key) {
        return obj[key] || (obj[key] = {});
      }

      var ccclass$n = makeSmartClassDecorator(function (constructor, name) {
        var base = getSuper(constructor);
        if (base === Object) {
          base = null;
        }
        var proto = {
          name: name,
          "extends": base,
          ctor: constructor
        };
        var cache = constructor[CACHE_KEY];
        if (cache) {
          var decoratedProto = cache.proto;
          if (decoratedProto) {
            mixin(proto, decoratedProto);
          }
          constructor[CACHE_KEY] = undefined;
        }
        var res = CCClass(proto);
        return res;
      });

      var requireComponent = makeEditorClassDecoratorFn('requireComponent');
      var executionOrder$1 = makeEditorClassDecoratorFn('executionOrder');
      var disallowMultiple$1 = emptySmartClassDecorator;

      function property$3(target, propertyKey, descriptorOrInitializer) {
        var options = null;
        function normalized(target, propertyKey, descriptorOrInitializer) {
          var classStash = getOrCreateClassStash(target);
          var propertyStash = getOrCreateEmptyPropertyStash(target, propertyKey);
          var classConstructor = target.constructor;
          mergePropertyOptions(classStash, propertyStash, classConstructor, propertyKey, options, descriptorOrInitializer);
        }
        if (target === undefined) {
          return property$3({
            type: undefined
          });
        } else if (typeof propertyKey === 'undefined') {
          options = target;
          return normalized;
        } else {
          normalized(target, propertyKey, descriptorOrInitializer);
          return undefined;
        }
      }
      function getDefaultFromInitializer(initializer) {
        var value;
        try {
          value = initializer();
        } catch (e) {
          return initializer;
        }
        if (typeof value !== 'object' || value === null) {
          return value;
        } else {
          return initializer;
        }
      }
      function extractActualDefaultValues(classConstructor) {
        var dummyObj;
        try {
          dummyObj = new classConstructor();
        } catch (e) {
          return {};
        }
        return dummyObj;
      }
      function getOrCreateClassStash(target) {
        var cache = getClassCache(target.constructor);
        return cache;
      }
      function getOrCreateEmptyPropertyStash(target, propertyKey) {
        var _ref, _properties$_ref;
        var classStash = getClassCache(target.constructor);
        var ccclassProto = getSubDict(classStash, 'proto');
        var properties = getSubDict(ccclassProto, 'properties');
        var propertyStash = (_properties$_ref = properties[_ref = propertyKey]) !== null && _properties$_ref !== void 0 ? _properties$_ref : properties[_ref] = {};
        return propertyStash;
      }
      function getOrCreatePropertyStash(target, propertyKey, descriptorOrInitializer) {
        var _ref2, _properties$_ref2;
        var classStash = getClassCache(target.constructor);
        var ccclassProto = getSubDict(classStash, 'proto');
        var properties = getSubDict(ccclassProto, 'properties');
        var propertyStash = (_properties$_ref2 = properties[_ref2 = propertyKey]) !== null && _properties$_ref2 !== void 0 ? _properties$_ref2 : properties[_ref2] = {};
        propertyStash.__internalFlags |= PropertyStashInternalFlag.STANDALONE;
        if (descriptorOrInitializer && typeof descriptorOrInitializer !== 'function' && (descriptorOrInitializer.get || descriptorOrInitializer.set)) {
          if (descriptorOrInitializer.get) {
            propertyStash.get = descriptorOrInitializer.get;
          }
          if (descriptorOrInitializer.set) {
            propertyStash.set = descriptorOrInitializer.set;
          }
        } else {
          setDefaultValue(classStash, propertyStash, target.constructor, propertyKey, descriptorOrInitializer);
        }
        return propertyStash;
      }
      function mergePropertyOptions(cache, propertyStash, ctor, propertyKey, options, descriptorOrInitializer) {
        var fullOptions;
        var isGetset = descriptorOrInitializer && typeof descriptorOrInitializer !== 'function' && (descriptorOrInitializer.get || descriptorOrInitializer.set);
        if (options) {
          fullOptions = getFullFormOfProperty(options, isGetset);
        }
        var propertyRecord = mixin(propertyStash, fullOptions || options || {});
        if (isGetset) {
          if (descriptorOrInitializer.get) {
            propertyRecord.get = descriptorOrInitializer.get;
          }
          if (descriptorOrInitializer.set) {
            propertyRecord.set = descriptorOrInitializer.set;
          }
        } else {
          setDefaultValue(cache, propertyRecord, ctor, propertyKey, descriptorOrInitializer);
        }
      }
      function setDefaultValue(classStash, propertyStash, classConstructor, propertyKey, descriptorOrInitializer) {
        if (descriptorOrInitializer !== undefined) {
          if (typeof descriptorOrInitializer === 'function') {
            propertyStash["default"] = getDefaultFromInitializer(descriptorOrInitializer);
          } else if (descriptorOrInitializer === null) ; else if (descriptorOrInitializer.initializer) {
            propertyStash["default"] = getDefaultFromInitializer(descriptorOrInitializer.initializer);
          }
        } else {
          var actualDefaultValues = classStash["default"] || (classStash["default"] = extractActualDefaultValues(classConstructor));
          if (actualDefaultValues.hasOwnProperty(propertyKey)) {
            propertyStash["default"] = actualDefaultValues[propertyKey];
          }
        }
      }

      var sMetadataTag = Symbol('cc:SerializationMetadata');
      function getSerializationMetadata(constructor) {
        return constructor[sMetadataTag];
      }
      function getOrCreateSerializationMetadata(constructor) {
        var _ref, _ref$sMetadataTag;
        return (_ref$sMetadataTag = (_ref = constructor)[sMetadataTag]) !== null && _ref$sMetadataTag !== void 0 ? _ref$sMetadataTag : _ref[sMetadataTag] = {};
      }

      var serializable$j = exports('cJ', function serializable(target, propertyKey, descriptorOrInitializer) {
        var propertyStash = getOrCreatePropertyStash(target, propertyKey, descriptorOrInitializer);
        setImplicitSerializable(propertyStash);
      });
      function formerlySerializedAs$4(name) {
        return function (target, propertyKey, descriptorOrInitializer) {
          var propertyStash = getOrCreatePropertyStash(target, propertyKey, descriptorOrInitializer);
          propertyStash.formerlySerializedAs = name;
          setImplicitSerializable(propertyStash);
        };
      }
      var editorOnly = function editorOnly(target, propertyKey, descriptorOrInitializer) {
        var propertyStash = getOrCreatePropertyStash(target, propertyKey, descriptorOrInitializer);
        propertyStash.editorOnly = true;
        setImplicitSerializable(propertyStash);
      };
      function setImplicitSerializable(propertyStash) {
        propertyStash.__internalFlags |= PropertyStashInternalFlag.IMPLICIT_SERIALIZABLE;
      }
      var uniquelyReferenced = emptyDecorator ;

      var executeInEditMode = emptySmartClassDecorator;
      var menu = emptyDecoratorFn;
      var playOnFocus = emptySmartClassDecorator;
      var inspector = emptyDecoratorFn;
      var icon = emptyDecoratorFn;
      var help = emptyDecoratorFn;
      var editable = exports('cy', emptyDecorator );
      var visible = exports('cA', emptyDecoratorFn );
      var displayName = exports('cB', emptyDecoratorFn );
      var tooltip = exports('cz', emptyDecoratorFn );
      var range = exports('cD', emptyDecoratorFn );
      var rangeStep = exports('cE', emptyDecoratorFn );
      var slide = exports('cF', emptyDecorator );
      var displayOrder = exports('cC', emptyDecoratorFn );
      var disallowAnimation = exports('cG', emptyDecorator );

      var integer = type$7(CCInteger);
      var _float = type$7(CCFloat);
      var _boolean = type$7(CCBoolean);
      var string = type$7(CCString);
      function type$7(type) {
        return property$3({
          type: type
        });
      }

      var override = exports('cH', function override(target, propertyKey, descriptorOrInitializer) {
        var propertyStash = getOrCreatePropertyStash(target, propertyKey, descriptorOrInitializer);
        propertyStash.override = true;
      });

      var editorExtrasTag = exports('bS', '__editorExtras__');

      var Empty$1 = function Empty() {};
      var EditorExtendable = exports('bW', editorExtendableInternal());
      assertIsTrue(editorExtrasTag === '__editorExtras__', 'editorExtrasTag needs to be updated.');
      function editorExtendableInternal(Base, className) {
        {
          return Base !== null && Base !== void 0 ? Base : Empty$1;
        }
      }

      var _decorator = /*#__PURE__*/Object.freeze({
        __proto__: null,
        uniquelyReferenced: uniquelyReferenced,
        ccclass: ccclass$n,
        property: property$3,
        requireComponent: requireComponent,
        executionOrder: executionOrder$1,
        disallowMultiple: disallowMultiple$1,
        executeInEditMode: executeInEditMode,
        menu: menu,
        playOnFocus: playOnFocus,
        inspector: inspector,
        icon: icon,
        help: help,
        type: type$7,
        integer: integer,
        float: _float,
        boolean: _boolean,
        string: string,
        editable: editable,
        tooltip: tooltip,
        visible: visible,
        displayName: displayName,
        displayOrder: displayOrder,
        range: range,
        rangeStep: rangeStep,
        slide: slide,
        disallowAnimation: disallowAnimation,
        override: override,
        formerlySerializedAs: formerlySerializedAs$4,
        serializable: serializable$j
      });
      exports('bJ', _decorator);

      var Destroyed$2 = 1 << 0;
      var ToDestroy = 1 << 2;
      var DontSave = 1 << 3;
      var EditorOnly = 1 << 4;
      var Dirty = 1 << 5;
      var DontDestroy$1 = 1 << 6;
      var Destroying$1 = 1 << 7;
      var Deactivating$2 = 1 << 8;
      var LockedInEditor = 1 << 9;
      var HideInHierarchy = 1 << 10;
      var IsOnEnableCalled$2 = 1 << 11;
      var IsEditorOnEnableCalled = 1 << 12;
      var IsPreloadStarted$1 = 1 << 13;
      var IsOnLoadCalled$2 = 1 << 14;
      var IsOnLoadStarted$1 = 1 << 15;
      var IsStartCalled$1 = 1 << 16;
      var IsRotationLocked = 1 << 17;
      var IsScaleLocked = 1 << 18;
      var IsAnchorLocked = 1 << 19;
      var IsSizeLocked = 1 << 20;
      var IsPositionLocked = 1 << 21;
      var PersistentMask$2 = ~(ToDestroy | Dirty | Destroying$1 | DontDestroy$1 | Deactivating$2 | IsPreloadStarted$1 | IsOnLoadStarted$1 | IsOnLoadCalled$2 | IsStartCalled$1 | IsOnEnableCalled$2 | IsEditorOnEnableCalled | IsRotationLocked | IsScaleLocked | IsAnchorLocked | IsSizeLocked | IsPositionLocked);
      var AllHideMasks = DontSave | EditorOnly | LockedInEditor | HideInHierarchy;
      var objectsToDestroy = [];
      function compileDestruct(obj, ctor) {
        var shouldSkipId = obj instanceof legacyCC.Node || obj instanceof legacyCC.Component;
        var idToSkip = shouldSkipId ? '_id' : null;
        var key;
        var propsToReset = {};
        for (key in obj) {
          if (obj.hasOwnProperty(key)) {
            if (key === idToSkip) {
              continue;
            }
            switch (typeof obj[key]) {
              case 'string':
                propsToReset[key] = '';
                break;
              case 'object':
              case 'function':
                propsToReset[key] = null;
                break;
            }
          }
        }
        if (CCClass._isCCClass(ctor)) {
          var attrs = legacyCC.Class.Attr.getClassAttrs(ctor);
          var propList = ctor.__props__;
          for (var i = 0; i < propList.length; i++) {
            key = propList[i];
            var attrKey = "" + key;
            if (attrKey in attrs) {
              if (shouldSkipId && key === '_id') {
                continue;
              }
              switch (typeof attrs[attrKey]) {
                case 'string':
                  propsToReset[key] = '';
                  break;
                case 'object':
                case 'function':
                  propsToReset[key] = null;
                  break;
                case 'undefined':
                  propsToReset[key] = undefined;
                  break;
              }
            }
          }
        }
        {
          var func = '';
          for (key in propsToReset) {
            var statement = void 0;
            if (CCClass.IDENTIFIER_RE.test(key)) {
              statement = "o." + key + "=";
            } else {
              statement = "o[" + CCClass.escapeForJS(key) + "]=";
            }
            var val = propsToReset[key];
            if (val === '') {
              val = '""';
            }
            func += statement + val + ";\n";
          }
          return Function('o', func);
        }
      }
      var CCObject = exports('bM', function () {
        CCObject._deferredDestroy = function _deferredDestroy() {
          var deleteCount = objectsToDestroy.length;
          for (var i = 0; i < deleteCount; ++i) {
            var obj = objectsToDestroy[i];
            if (!(obj._objFlags & Destroyed$2)) {
              obj._destroyImmediate();
            }
          }
          if (deleteCount === objectsToDestroy.length) {
            objectsToDestroy.length = 0;
          } else {
            objectsToDestroy.splice(0, deleteCount);
          }
        };
        function CCObject(name) {
          if (name === void 0) {
            name = '';
          }
          this._objFlags = void 0;
          this._name = void 0;
          this._name = name;
          this._objFlags = 0;
        }
        var _proto = CCObject.prototype;
        _proto.destroy = function destroy() {
          if (this._objFlags & Destroyed$2) {
            warnID(5000);
            return false;
          }
          if (this._objFlags & ToDestroy) {
            return false;
          }
          this._objFlags |= ToDestroy;
          objectsToDestroy.push(this);
          return true;
        };
        _proto._destruct = function _destruct() {
          var ctor = this.constructor;
          var destruct = ctor.__destruct__;
          if (!destruct) {
            destruct = compileDestruct(this, ctor);
            value(ctor, '__destruct__', destruct, true);
          }
          destruct(this);
        };
        _proto._destroyImmediate = function _destroyImmediate() {
          var _onPreDestroy, _ref;
          if (this._objFlags & Destroyed$2) {
            errorID(5000);
            return;
          }
          (_onPreDestroy = (_ref = this)._onPreDestroy) === null || _onPreDestroy === void 0 ? void 0 : _onPreDestroy.call(_ref);
          {
            this._destruct();
          }
          this._objFlags |= Destroyed$2;
        };
        _createClass(CCObject, [{
          key: "name",
          get: function get() {
            return this._name;
          },
          set: function set(value) {
            this._name = value;
          }
        }, {
          key: "hideFlags",
          get: function get() {
            return this._objFlags & CCObject.Flags.AllHideMasks;
          },
          set: function set(hideFlags) {
            var flags = hideFlags & CCObject.Flags.AllHideMasks;
            this._objFlags = this._objFlags & ~CCObject.Flags.AllHideMasks | flags;
          }
        }, {
          key: "isValid",
          get: function get() {
            return !(this._objFlags & Destroyed$2);
          }
        }]);
        return CCObject;
      }());
      var prototype = CCObject.prototype;
      prototype._deserialize = null;
      {
        CCClass.fastDefine('cc.Object', CCObject, {
          _name: '',
          _objFlags: 0
        });
      }
      value(CCObject, 'Flags', {
        Destroyed: Destroyed$2,
        DontSave: DontSave,
        EditorOnly: EditorOnly,
        Dirty: Dirty,
        DontDestroy: DontDestroy$1,
        PersistentMask: PersistentMask$2,
        Destroying: Destroying$1,
        Deactivating: Deactivating$2,
        LockedInEditor: LockedInEditor,
        HideInHierarchy: HideInHierarchy,
        AllHideMasks: AllHideMasks,
        IsPreloadStarted: IsPreloadStarted$1,
        IsOnLoadStarted: IsOnLoadStarted$1,
        IsOnLoadCalled: IsOnLoadCalled$2,
        IsOnEnableCalled: IsOnEnableCalled$2,
        IsStartCalled: IsStartCalled$1,
        IsEditorOnEnableCalled: IsEditorOnEnableCalled,
        IsPositionLocked: IsPositionLocked,
        IsRotationLocked: IsRotationLocked,
        IsScaleLocked: IsScaleLocked,
        IsAnchorLocked: IsAnchorLocked,
        IsSizeLocked: IsSizeLocked
      });
      function isCCObject(object) {
        return object instanceof CCObject;
      }
      function isValid(value, strictMode) {
        if (typeof value === 'object') {
          return !!value && !(value._objFlags & (strictMode ? Destroyed$2 | ToDestroy : Destroyed$2));
        } else {
          return typeof value !== 'undefined';
        }
      }
      legacyCC.isValid = isValid;
      legacyCC.Object = CCObject;

      var _dec$35, _class$32, _class2$2M, _initializer$2s, _initializer2$1T, _initializer3$1i, _initializer4$10, _class3$R, _BuiltinElementTypeTr;
      var StorageUnit;
      (function (StorageUnit) {
        StorageUnit[StorageUnit["Uint8"] = 0] = "Uint8";
        StorageUnit[StorageUnit["Uint16"] = 1] = "Uint16";
        StorageUnit[StorageUnit["Uint32"] = 2] = "Uint32";
        StorageUnit[StorageUnit["Int8"] = 3] = "Int8";
        StorageUnit[StorageUnit["Int16"] = 4] = "Int16";
        StorageUnit[StorageUnit["Int32"] = 5] = "Int32";
        StorageUnit[StorageUnit["Float32"] = 6] = "Float32";
        StorageUnit[StorageUnit["Float64"] = 7] = "Float64";
      })(StorageUnit || (StorageUnit = {}));
      var ElementType;
      (function (ElementType) {
        ElementType[ElementType["Scalar"] = 0] = "Scalar";
        ElementType[ElementType["Vec2"] = 1] = "Vec2";
        ElementType[ElementType["Vec3"] = 2] = "Vec3";
        ElementType[ElementType["Vec4"] = 3] = "Vec4";
        ElementType[ElementType["Quat"] = 4] = "Quat";
        ElementType[ElementType["Mat4"] = 5] = "Mat4";
      })(ElementType || (ElementType = {}));
      var elementTypeBits = 3;
      function combineStorageUnitElementType(unit, elementType) {
        return (elementType << elementTypeBits) + unit;
      }
      function extractStorageUnitElementType(combined) {
        return {
          storageUnit: ~(-1 << elementTypeBits) & combined,
          elementType: combined >> elementTypeBits
        };
      }
      var CompactValueTypeArray = exports('bR', (_dec$35 = ccclass$n('cc.CompactValueTypeArray'), _dec$35(_class$32 = (_class2$2M = (_class3$R = function () {
        function CompactValueTypeArray() {
          this._byteOffset = _initializer$2s && _initializer$2s();
          this._unitCount = _initializer2$1T && _initializer2$1T();
          this._unitElement = _initializer3$1i && _initializer3$1i();
          this._length = _initializer4$10 && _initializer4$10();
        }
        CompactValueTypeArray.lengthFor = function lengthFor(values, elementType, unit) {
          var elementTraits = getElementTraits(elementType);
          return elementTraits.requiredUnits * values.length * getStorageConstructor(unit).BYTES_PER_ELEMENT;
        };
        CompactValueTypeArray.compress = function compress(values, elementType, unit, arrayBuffer, byteOffset, presumedByteOffset) {
          var elementTraits = getElementTraits(elementType);
          var storageConstructor = getStorageConstructor(unit);
          var unitCount = elementTraits.requiredUnits * values.length;
          var storage = new storageConstructor(arrayBuffer, byteOffset, unitCount);
          for (var i = 0; i < values.length; ++i) {
            elementTraits.compress(storage, i, values[i]);
          }
          var result = new CompactValueTypeArray();
          result._unitElement = combineStorageUnitElementType(unit, elementType);
          result._byteOffset = presumedByteOffset;
          result._unitCount = unitCount;
          result._length = values.length;
          return result;
        };
        var _proto = CompactValueTypeArray.prototype;
        _proto.decompress = function decompress(arrayBuffer) {
          var _extractStorageUnitEl = extractStorageUnitElementType(this._unitElement),
            storageUnit = _extractStorageUnitEl.storageUnit,
            elementType = _extractStorageUnitEl.elementType;
          var elementTraits = getElementTraits(elementType);
          var storageConstructor = getStorageConstructor(storageUnit);
          var storage = new storageConstructor(arrayBuffer, this._byteOffset, this._unitCount);
          var result = new Array(this._length);
          for (var i = 0; i < this._length; ++i) {
            result[i] = elementTraits.decompress(storage, i);
          }
          return result;
        };
        return CompactValueTypeArray;
      }(), _class3$R.StorageUnit = StorageUnit, _class3$R.ElementType = ElementType, _class3$R), (_initializer$2s = applyDecoratedInitializer(_class2$2M.prototype, "_byteOffset", [serializable$j], function () {
        return 0;
      }), _initializer2$1T = applyDecoratedInitializer(_class2$2M.prototype, "_unitCount", [serializable$j], function () {
        return 0;
      }), _initializer3$1i = applyDecoratedInitializer(_class2$2M.prototype, "_unitElement", [serializable$j], function () {
        return combineStorageUnitElementType(StorageUnit.Uint8, ElementType.Scalar);
      }), _initializer4$10 = applyDecoratedInitializer(_class2$2M.prototype, "_length", [serializable$j], function () {
        return 0;
      })), _class2$2M)) || _class$32));
      function getElementTraits(elementType) {
        return BuiltinElementTypeTraits[elementType];
      }
      function getStorageConstructor(unit) {
        switch (unit) {
          case StorageUnit.Uint8:
            return Uint8Array;
          case StorageUnit.Uint16:
            return Uint16Array;
          case StorageUnit.Uint32:
            return Uint32Array;
          case StorageUnit.Int8:
            return Int8Array;
          case StorageUnit.Int16:
            return Int16Array;
          case StorageUnit.Int32:
            return Int32Array;
          case StorageUnit.Float32:
            return Float32Array;
          case StorageUnit.Float64:
            return Float64Array;
        }
      }
      var BuiltinElementTypeTraits = (_BuiltinElementTypeTr = {}, _BuiltinElementTypeTr[ElementType.Scalar] = {
        requiredUnits: 1,
        compress: function compress(storage, index, value) {
          storage[index] = value;
        },
        decompress: function decompress(storage, index) {
          return storage[index];
        }
      }, _BuiltinElementTypeTr[ElementType.Vec2] = {
        requiredUnits: 2,
        compress: function compress(storage, index, value) {
          storage[index * 2] = value.x;
          storage[index * 2 + 1] = value.y;
        },
        decompress: function decompress(storage, index) {
          return new Vec3(storage[index * 2], storage[index * 2 + 1]);
        }
      }, _BuiltinElementTypeTr[ElementType.Vec3] = {
        requiredUnits: 3,
        compress: function compress(storage, index, value) {
          storage[index * 3] = value.x;
          storage[index * 3 + 1] = value.y;
          storage[index * 3 + 2] = value.z;
        },
        decompress: function decompress(storage, index) {
          return new Vec3(storage[index * 3], storage[index * 3 + 1], storage[index * 3 + 2]);
        }
      }, _BuiltinElementTypeTr[ElementType.Vec4] = {
        requiredUnits: 4,
        compress: function compress(storage, index, value) {
          storage[index * 4] = value.x;
          storage[index * 4 + 1] = value.y;
          storage[index * 4 + 2] = value.z;
          storage[index * 4 + 3] = value.w;
        },
        decompress: function decompress(storage, index) {
          return new Vec4(storage[index * 4], storage[index * 4 + 1], storage[index * 4 + 2], storage[index * 4 + 3]);
        }
      }, _BuiltinElementTypeTr[ElementType.Quat] = {
        requiredUnits: 4,
        compress: function compress(storage, index, value) {
          storage[index * 4] = value.x;
          storage[index * 4 + 1] = value.y;
          storage[index * 4 + 2] = value.z;
          storage[index * 4 + 3] = value.w;
        },
        decompress: function decompress(storage, index) {
          return new Quat(storage[index * 4], storage[index * 4 + 1], storage[index * 4 + 2], storage[index * 4 + 3]);
        }
      }, _BuiltinElementTypeTr[ElementType.Mat4] = {
        requiredUnits: 16,
        compress: function compress(storage, index, value) {
          Mat4.toArray(storage, value, index * 16);
        },
        decompress: function decompress(storage, index) {
          return Mat4.fromArray(new Mat4(), storage, index * 16);
        }
      }, _BuiltinElementTypeTr);

      var serializeTag = exports('bU', Symbol('[[Serialize]]'));
      var deserializeTag = exports('bT', Symbol('[[Deserialize]]'));

      legacyCC._decorator = _decorator;

      function constant() {
        return 0;
      }
      function linear(k) {
        return k;
      }
      function quadIn(k) {
        return k * k;
      }
      function quadOut(k) {
        return k * (2 - k);
      }
      function quadInOut(k) {
        k *= 2;
        if (k < 1) {
          return 0.5 * k * k;
        }
        return -0.5 * (--k * (k - 2) - 1);
      }
      function cubicIn(k) {
        return k * k * k;
      }
      function cubicOut(k) {
        return --k * k * k + 1;
      }
      function cubicInOut(k) {
        k *= 2;
        if (k < 1) {
          return 0.5 * k * k * k;
        }
        return 0.5 * ((k -= 2) * k * k + 2);
      }
      function quartIn(k) {
        return k * k * k * k;
      }
      function quartOut(k) {
        return 1 - --k * k * k * k;
      }
      function quartInOut(k) {
        k *= 2;
        if (k < 1) {
          return 0.5 * k * k * k * k;
        }
        return -0.5 * ((k -= 2) * k * k * k - 2);
      }
      function quintIn(k) {
        return k * k * k * k * k;
      }
      function quintOut(k) {
        return --k * k * k * k * k + 1;
      }
      function quintInOut(k) {
        k *= 2;
        if (k < 1) {
          return 0.5 * k * k * k * k * k;
        }
        return 0.5 * ((k -= 2) * k * k * k * k + 2);
      }
      function sineIn(k) {
        if (k === 1) {
          return 1;
        }
        return 1 - Math.cos(k * Math.PI / 2);
      }
      function sineOut(k) {
        return Math.sin(k * Math.PI / 2);
      }
      function sineInOut(k) {
        return 0.5 * (1 - Math.cos(Math.PI * k));
      }
      function expoIn(k) {
        return k === 0 ? 0 : Math.pow(1024, k - 1);
      }
      function expoOut(k) {
        return k === 1 ? 1 : 1 - Math.pow(2, -10 * k);
      }
      function expoInOut(k) {
        if (k === 0) {
          return 0;
        }
        if (k === 1) {
          return 1;
        }
        k *= 2;
        if (k < 1) {
          return 0.5 * Math.pow(1024, k - 1);
        }
        return 0.5 * (-Math.pow(2, -10 * (k - 1)) + 2);
      }
      function circIn(k) {
        return 1 - Math.sqrt(1 - k * k);
      }
      function circOut(k) {
        return Math.sqrt(1 - --k * k);
      }
      function circInOut(k) {
        k *= 2;
        if (k < 1) {
          return -0.5 * (Math.sqrt(1 - k * k) - 1);
        }
        return 0.5 * (Math.sqrt(1 - (k -= 2) * k) + 1);
      }
      function elasticIn(k) {
        var s;
        var a = 0.1;
        var p = 0.4;
        if (k === 0) {
          return 0;
        }
        if (k === 1) {
          return 1;
        }
        if (!a || a < 1) {
          a = 1;
          s = p / 4;
        } else {
          s = p * Math.asin(1 / a) / (2 * Math.PI);
        }
        return -(a * Math.pow(2, 10 * (k -= 1)) * Math.sin((k - s) * (2 * Math.PI) / p));
      }
      function elasticOut(k) {
        var s;
        var a = 0.1;
        var p = 0.4;
        if (k === 0) {
          return 0;
        }
        if (k === 1) {
          return 1;
        }
        if (!a || a < 1) {
          a = 1;
          s = p / 4;
        } else {
          s = p * Math.asin(1 / a) / (2 * Math.PI);
        }
        return a * Math.pow(2, -10 * k) * Math.sin((k - s) * (2 * Math.PI) / p) + 1;
      }
      function elasticInOut(k) {
        var s;
        var a = 0.1;
        var p = 0.4;
        if (k === 0) {
          return 0;
        }
        if (k === 1) {
          return 1;
        }
        if (!a || a < 1) {
          a = 1;
          s = p / 4;
        } else {
          s = p * Math.asin(1 / a) / (2 * Math.PI);
        }
        k *= 2;
        if (k < 1) {
          return -0.5 * (a * Math.pow(2, 10 * (k -= 1)) * Math.sin((k - s) * (2 * Math.PI) / p));
        }
        return a * Math.pow(2, -10 * (k -= 1)) * Math.sin((k - s) * (2 * Math.PI) / p) * 0.5 + 1;
      }
      function backIn(k) {
        if (k === 1) {
          return 1;
        }
        var s = 1.70158;
        return k * k * ((s + 1) * k - s);
      }
      function backOut(k) {
        if (k === 0) {
          return 0;
        }
        var s = 1.70158;
        return --k * k * ((s + 1) * k + s) + 1;
      }
      function backInOut(k) {
        var s = 1.70158 * 1.525;
        k *= 2;
        if (k < 1) {
          return 0.5 * (k * k * ((s + 1) * k - s));
        }
        return 0.5 * ((k -= 2) * k * ((s + 1) * k + s) + 2);
      }
      function bounceIn(k) {
        return 1 - bounceOut(1 - k);
      }
      function bounceOut(k) {
        if (k < 1 / 2.75) {
          return 7.5625 * k * k;
        } else if (k < 2 / 2.75) {
          return 7.5625 * (k -= 1.5 / 2.75) * k + 0.75;
        } else if (k < 2.5 / 2.75) {
          return 7.5625 * (k -= 2.25 / 2.75) * k + 0.9375;
        } else {
          return 7.5625 * (k -= 2.625 / 2.75) * k + 0.984375;
        }
      }
      function bounceInOut(k) {
        if (k < 0.5) {
          return bounceIn(k * 2) * 0.5;
        }
        return bounceOut(k * 2 - 1) * 0.5 + 0.5;
      }
      function smooth(k) {
        if (k <= 0) {
          return 0;
        }
        if (k >= 1) {
          return 1;
        }
        return k * k * (3 - 2 * k);
      }
      function fade(k) {
        if (k <= 0) {
          return 0;
        }
        if (k >= 1) {
          return 1;
        }
        return k * k * k * (k * (k * 6 - 15) + 10);
      }
      var quadOutIn = _makeOutIn(quadIn, quadOut);
      var cubicOutIn = _makeOutIn(cubicIn, cubicOut);
      var quartOutIn = _makeOutIn(quartIn, quartOut);
      var quintOutIn = _makeOutIn(quintIn, quintOut);
      var sineOutIn = _makeOutIn(sineIn, sineOut);
      var expoOutIn = _makeOutIn(expoIn, expoOut);
      var circOutIn = _makeOutIn(circIn, circOut);
      var elasticOutIn = _makeOutIn(elasticIn, elasticOut);
      var backOutIn = _makeOutIn(backIn, backOut);
      var bounceOutIn = _makeOutIn(bounceIn, bounceOut);
      function _makeOutIn(fnIn, fnOut) {
        return function (k) {
          if (k < 0.5) {
            return fnOut(k * 2) / 2;
          }
          return fnIn(2 * k - 1) / 2 + 0.5;
        };
      }

      var easing = /*#__PURE__*/Object.freeze({
        __proto__: null,
        constant: constant,
        linear: linear,
        quadIn: quadIn,
        quadOut: quadOut,
        quadInOut: quadInOut,
        cubicIn: cubicIn,
        cubicOut: cubicOut,
        cubicInOut: cubicInOut,
        quartIn: quartIn,
        quartOut: quartOut,
        quartInOut: quartInOut,
        quintIn: quintIn,
        quintOut: quintOut,
        quintInOut: quintInOut,
        sineIn: sineIn,
        sineOut: sineOut,
        sineInOut: sineInOut,
        expoIn: expoIn,
        expoOut: expoOut,
        expoInOut: expoInOut,
        circIn: circIn,
        circOut: circOut,
        circInOut: circInOut,
        elasticIn: elasticIn,
        elasticOut: elasticOut,
        elasticInOut: elasticInOut,
        backIn: backIn,
        backOut: backOut,
        backInOut: backInOut,
        bounceIn: bounceIn,
        bounceOut: bounceOut,
        bounceInOut: bounceInOut,
        smooth: smooth,
        fade: fade,
        quadOutIn: quadOutIn,
        cubicOutIn: cubicOutIn,
        quartOutIn: quartOutIn,
        quintOutIn: quintOutIn,
        sineOutIn: sineOutIn,
        expoOutIn: expoOutIn,
        circOutIn: circOutIn,
        elasticOutIn: elasticOutIn,
        backOutIn: backOutIn,
        bounceOutIn: bounceOutIn
      });
      exports('ct', easing);

      var _easingMethodFnMap;
      var EasingMethod; exports('cT', EasingMethod);
      (function (EasingMethod) {
        EasingMethod[EasingMethod["LINEAR"] = 0] = "LINEAR";
        EasingMethod[EasingMethod["CONSTANT"] = 1] = "CONSTANT";
        EasingMethod[EasingMethod["QUAD_IN"] = 2] = "QUAD_IN";
        EasingMethod[EasingMethod["QUAD_OUT"] = 3] = "QUAD_OUT";
        EasingMethod[EasingMethod["QUAD_IN_OUT"] = 4] = "QUAD_IN_OUT";
        EasingMethod[EasingMethod["QUAD_OUT_IN"] = 5] = "QUAD_OUT_IN";
        EasingMethod[EasingMethod["CUBIC_IN"] = 6] = "CUBIC_IN";
        EasingMethod[EasingMethod["CUBIC_OUT"] = 7] = "CUBIC_OUT";
        EasingMethod[EasingMethod["CUBIC_IN_OUT"] = 8] = "CUBIC_IN_OUT";
        EasingMethod[EasingMethod["CUBIC_OUT_IN"] = 9] = "CUBIC_OUT_IN";
        EasingMethod[EasingMethod["QUART_IN"] = 10] = "QUART_IN";
        EasingMethod[EasingMethod["QUART_OUT"] = 11] = "QUART_OUT";
        EasingMethod[EasingMethod["QUART_IN_OUT"] = 12] = "QUART_IN_OUT";
        EasingMethod[EasingMethod["QUART_OUT_IN"] = 13] = "QUART_OUT_IN";
        EasingMethod[EasingMethod["QUINT_IN"] = 14] = "QUINT_IN";
        EasingMethod[EasingMethod["QUINT_OUT"] = 15] = "QUINT_OUT";
        EasingMethod[EasingMethod["QUINT_IN_OUT"] = 16] = "QUINT_IN_OUT";
        EasingMethod[EasingMethod["QUINT_OUT_IN"] = 17] = "QUINT_OUT_IN";
        EasingMethod[EasingMethod["SINE_IN"] = 18] = "SINE_IN";
        EasingMethod[EasingMethod["SINE_OUT"] = 19] = "SINE_OUT";
        EasingMethod[EasingMethod["SINE_IN_OUT"] = 20] = "SINE_IN_OUT";
        EasingMethod[EasingMethod["SINE_OUT_IN"] = 21] = "SINE_OUT_IN";
        EasingMethod[EasingMethod["EXPO_IN"] = 22] = "EXPO_IN";
        EasingMethod[EasingMethod["EXPO_OUT"] = 23] = "EXPO_OUT";
        EasingMethod[EasingMethod["EXPO_IN_OUT"] = 24] = "EXPO_IN_OUT";
        EasingMethod[EasingMethod["EXPO_OUT_IN"] = 25] = "EXPO_OUT_IN";
        EasingMethod[EasingMethod["CIRC_IN"] = 26] = "CIRC_IN";
        EasingMethod[EasingMethod["CIRC_OUT"] = 27] = "CIRC_OUT";
        EasingMethod[EasingMethod["CIRC_IN_OUT"] = 28] = "CIRC_IN_OUT";
        EasingMethod[EasingMethod["CIRC_OUT_IN"] = 29] = "CIRC_OUT_IN";
        EasingMethod[EasingMethod["ELASTIC_IN"] = 30] = "ELASTIC_IN";
        EasingMethod[EasingMethod["ELASTIC_OUT"] = 31] = "ELASTIC_OUT";
        EasingMethod[EasingMethod["ELASTIC_IN_OUT"] = 32] = "ELASTIC_IN_OUT";
        EasingMethod[EasingMethod["ELASTIC_OUT_IN"] = 33] = "ELASTIC_OUT_IN";
        EasingMethod[EasingMethod["BACK_IN"] = 34] = "BACK_IN";
        EasingMethod[EasingMethod["BACK_OUT"] = 35] = "BACK_OUT";
        EasingMethod[EasingMethod["BACK_IN_OUT"] = 36] = "BACK_IN_OUT";
        EasingMethod[EasingMethod["BACK_OUT_IN"] = 37] = "BACK_OUT_IN";
        EasingMethod[EasingMethod["BOUNCE_IN"] = 38] = "BOUNCE_IN";
        EasingMethod[EasingMethod["BOUNCE_OUT"] = 39] = "BOUNCE_OUT";
        EasingMethod[EasingMethod["BOUNCE_IN_OUT"] = 40] = "BOUNCE_IN_OUT";
        EasingMethod[EasingMethod["BOUNCE_OUT_IN"] = 41] = "BOUNCE_OUT_IN";
        EasingMethod[EasingMethod["SMOOTH"] = 42] = "SMOOTH";
        EasingMethod[EasingMethod["FADE"] = 43] = "FADE";
      })(EasingMethod || (exports('cT', EasingMethod = {})));
      var easingMethodFnMap = (_easingMethodFnMap = {}, _easingMethodFnMap[EasingMethod.CONSTANT] = constant, _easingMethodFnMap[EasingMethod.LINEAR] = linear, _easingMethodFnMap[EasingMethod.QUAD_IN] = quadIn, _easingMethodFnMap[EasingMethod.QUAD_OUT] = quadOut, _easingMethodFnMap[EasingMethod.QUAD_IN_OUT] = quadInOut, _easingMethodFnMap[EasingMethod.QUAD_OUT_IN] = quadOutIn, _easingMethodFnMap[EasingMethod.CUBIC_IN] = cubicIn, _easingMethodFnMap[EasingMethod.CUBIC_OUT] = cubicOut, _easingMethodFnMap[EasingMethod.CUBIC_IN_OUT] = cubicInOut, _easingMethodFnMap[EasingMethod.CUBIC_OUT_IN] = cubicOutIn, _easingMethodFnMap[EasingMethod.QUART_IN] = quartIn, _easingMethodFnMap[EasingMethod.QUART_OUT] = quartOut, _easingMethodFnMap[EasingMethod.QUART_IN_OUT] = quartInOut, _easingMethodFnMap[EasingMethod.QUART_OUT_IN] = quartOutIn, _easingMethodFnMap[EasingMethod.QUINT_IN] = quintIn, _easingMethodFnMap[EasingMethod.QUINT_OUT] = quintOut, _easingMethodFnMap[EasingMethod.QUINT_IN_OUT] = quintInOut, _easingMethodFnMap[EasingMethod.QUINT_OUT_IN] = quintOutIn, _easingMethodFnMap[EasingMethod.SINE_IN] = sineIn, _easingMethodFnMap[EasingMethod.SINE_OUT] = sineOut, _easingMethodFnMap[EasingMethod.SINE_IN_OUT] = sineInOut, _easingMethodFnMap[EasingMethod.SINE_OUT_IN] = sineOutIn, _easingMethodFnMap[EasingMethod.EXPO_IN] = expoIn, _easingMethodFnMap[EasingMethod.EXPO_OUT] = expoOut, _easingMethodFnMap[EasingMethod.EXPO_IN_OUT] = expoInOut, _easingMethodFnMap[EasingMethod.EXPO_OUT_IN] = expoOutIn, _easingMethodFnMap[EasingMethod.CIRC_IN] = circIn, _easingMethodFnMap[EasingMethod.CIRC_OUT] = circOut, _easingMethodFnMap[EasingMethod.CIRC_IN_OUT] = circInOut, _easingMethodFnMap[EasingMethod.CIRC_OUT_IN] = circOutIn, _easingMethodFnMap[EasingMethod.ELASTIC_IN] = elasticIn, _easingMethodFnMap[EasingMethod.ELASTIC_OUT] = elasticOut, _easingMethodFnMap[EasingMethod.ELASTIC_IN_OUT] = elasticInOut, _easingMethodFnMap[EasingMethod.ELASTIC_OUT_IN] = elasticOutIn, _easingMethodFnMap[EasingMethod.BACK_IN] = backIn, _easingMethodFnMap[EasingMethod.BACK_OUT] = backOut, _easingMethodFnMap[EasingMethod.BACK_IN_OUT] = backInOut, _easingMethodFnMap[EasingMethod.BACK_OUT_IN] = backOutIn, _easingMethodFnMap[EasingMethod.BOUNCE_IN] = bounceIn, _easingMethodFnMap[EasingMethod.BOUNCE_OUT] = bounceOut, _easingMethodFnMap[EasingMethod.BOUNCE_IN_OUT] = bounceInOut, _easingMethodFnMap[EasingMethod.BOUNCE_OUT_IN] = bounceOutIn, _easingMethodFnMap[EasingMethod.SMOOTH] = smooth, _easingMethodFnMap[EasingMethod.FADE] = fade, _easingMethodFnMap);
      function getEasingFn(easingMethod) {
        assertIsTrue(easingMethod in easingMethodFnMap);
        return easingMethodFnMap[easingMethod];
      }

      var _CCClass$fastDefine;
      var REAL_KEYFRAME_VALUE_FLAGS_INTERPOLATION_MODE_START = 0;
      var REAL_KEYFRAME_VALUE_FLAGS_INTERPOLATION_MODE_MASK = 0xFF << REAL_KEYFRAME_VALUE_FLAGS_INTERPOLATION_MODE_START;
      var REAL_KEYFRAME_VALUE_FLAGS_TANGENT_WEIGHT_MODE_START = 8;
      var REAL_KEYFRAME_VALUE_FLAGS_TANGENT_WEIGHT_MODE_MASK = 0xFF << REAL_KEYFRAME_VALUE_FLAGS_TANGENT_WEIGHT_MODE_START;
      var REAL_KEYFRAME_VALUE_FLAGS_EASING_METHOD_START = 16;
      var REAL_KEYFRAME_VALUE_FLAGS_EASING_METHOD_MASK = 0xFF << REAL_KEYFRAME_VALUE_FLAGS_EASING_METHOD_START;
      assertIsTrue(REAL_KEYFRAME_VALUE_FLAGS_TANGENT_WEIGHT_MODE_START === REAL_KEYFRAME_VALUE_FLAGS_INTERPOLATION_MODE_START + popCount(REAL_KEYFRAME_VALUE_FLAGS_INTERPOLATION_MODE_MASK));
      assertIsTrue(REAL_KEYFRAME_VALUE_FLAGS_EASING_METHOD_START === REAL_KEYFRAME_VALUE_FLAGS_TANGENT_WEIGHT_MODE_START + popCount(REAL_KEYFRAME_VALUE_FLAGS_TANGENT_WEIGHT_MODE_MASK));
      var REAL_KEYFRAME_VALUE_DEFAULT_FLAGS = RealInterpolationMode.LINEAR << REAL_KEYFRAME_VALUE_FLAGS_INTERPOLATION_MODE_START | TangentWeightMode.NONE << REAL_KEYFRAME_VALUE_FLAGS_TANGENT_WEIGHT_MODE_START | EasingMethod.LINEAR << REAL_KEYFRAME_VALUE_FLAGS_EASING_METHOD_START;
      var RealKeyframeValue = function (_EditorExtendable) {
        _inheritsLoose(RealKeyframeValue, _EditorExtendable);
        function RealKeyframeValue() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _EditorExtendable.call.apply(_EditorExtendable, [this].concat(args)) || this;
          _this.value = 0.0;
          _this.rightTangent = 0.0;
          _this.rightTangentWeight = 0.0;
          _this.leftTangent = 0.0;
          _this.leftTangentWeight = 0.0;
          _this._flags = REAL_KEYFRAME_VALUE_DEFAULT_FLAGS;
          return _this;
        }
        _createClass(RealKeyframeValue, [{
          key: "interpolationMode",
          get: function get() {
            return (this._flags & REAL_KEYFRAME_VALUE_FLAGS_INTERPOLATION_MODE_MASK) >> REAL_KEYFRAME_VALUE_FLAGS_INTERPOLATION_MODE_START;
          },
          set: function set(value) {
            this._flags &= ~REAL_KEYFRAME_VALUE_FLAGS_INTERPOLATION_MODE_MASK;
            this._flags |= value << REAL_KEYFRAME_VALUE_FLAGS_INTERPOLATION_MODE_START;
          }
        }, {
          key: "tangentWeightMode",
          get: function get() {
            return (this._flags & REAL_KEYFRAME_VALUE_FLAGS_TANGENT_WEIGHT_MODE_MASK) >> REAL_KEYFRAME_VALUE_FLAGS_TANGENT_WEIGHT_MODE_START;
          },
          set: function set(value) {
            this._flags &= ~REAL_KEYFRAME_VALUE_FLAGS_TANGENT_WEIGHT_MODE_MASK;
            this._flags |= value << REAL_KEYFRAME_VALUE_FLAGS_TANGENT_WEIGHT_MODE_START;
          }
        }, {
          key: "easingMethod",
          get: function get() {
            return (this._flags & REAL_KEYFRAME_VALUE_FLAGS_EASING_METHOD_MASK) >> REAL_KEYFRAME_VALUE_FLAGS_EASING_METHOD_START;
          },
          set: function set(value) {
            this._flags &= ~REAL_KEYFRAME_VALUE_FLAGS_EASING_METHOD_MASK;
            this._flags |= value << REAL_KEYFRAME_VALUE_FLAGS_EASING_METHOD_START;
          }
        }]);
        return RealKeyframeValue;
      }(EditorExtendable);
      CCClass.fastDefine('cc.RealKeyframeValue', RealKeyframeValue, (_CCClass$fastDefine = {
        interpolationMode: RealInterpolationMode.LINEAR,
        tangentWeightMode: TangentWeightMode.NONE,
        value: 0.0,
        rightTangent: 0.0,
        rightTangentWeight: 0.0,
        leftTangent: 0.0,
        leftTangentWeight: 0.0,
        easingMethod: EasingMethod.LINEAR
      }, _CCClass$fastDefine[editorExtrasTag] = undefined, _CCClass$fastDefine));
      CCClass.Attr.setClassAttr(RealKeyframeValue, editorExtrasTag, 'editorOnly', true);
      getOrCreateSerializationMetadata(RealKeyframeValue).uniquelyReferenced = true;
      function createRealKeyframeValue(params) {
        var realKeyframeValue = new RealKeyframeValue();
        if (typeof params === 'number') {
          realKeyframeValue.value = params;
        } else {
          var interpolationMode = params.interpolationMode,
            tangentWeightMode = params.tangentWeightMode,
            value = params.value,
            rightTangent = params.rightTangent,
            rightTangentWeight = params.rightTangentWeight,
            leftTangent = params.leftTangent,
            leftTangentWeight = params.leftTangentWeight,
            easingMethod = params.easingMethod,
            editorExtras = params[editorExtrasTag];
          realKeyframeValue.value = value !== null && value !== void 0 ? value : realKeyframeValue.value;
          realKeyframeValue.rightTangent = rightTangent !== null && rightTangent !== void 0 ? rightTangent : realKeyframeValue.rightTangent;
          realKeyframeValue.rightTangentWeight = rightTangentWeight !== null && rightTangentWeight !== void 0 ? rightTangentWeight : realKeyframeValue.rightTangentWeight;
          realKeyframeValue.leftTangent = leftTangent !== null && leftTangent !== void 0 ? leftTangent : realKeyframeValue.leftTangent;
          realKeyframeValue.leftTangentWeight = leftTangentWeight !== null && leftTangentWeight !== void 0 ? leftTangentWeight : realKeyframeValue.leftTangentWeight;
          realKeyframeValue.interpolationMode = interpolationMode !== null && interpolationMode !== void 0 ? interpolationMode : realKeyframeValue.interpolationMode;
          realKeyframeValue.tangentWeightMode = tangentWeightMode !== null && tangentWeightMode !== void 0 ? tangentWeightMode : realKeyframeValue.tangentWeightMode;
          realKeyframeValue.easingMethod = easingMethod !== null && easingMethod !== void 0 ? easingMethod : realKeyframeValue.easingMethod;
          if (editorExtras) {
            realKeyframeValue[editorExtrasTag] = editorExtras;
          }
        }
        return realKeyframeValue;
      }
      var RealCurve = exports('cg', function (_KeyframeCurve) {
        _inheritsLoose(RealCurve, _KeyframeCurve);
        function RealCurve() {
          var _this2;
          for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
            args[_key2] = arguments[_key2];
          }
          _this2 = _KeyframeCurve.call.apply(_KeyframeCurve, [this].concat(args)) || this;
          _this2.preExtrapolation = ExtrapolationMode.CLAMP;
          _this2.postExtrapolation = ExtrapolationMode.CLAMP;
          return _this2;
        }
        var _proto = RealCurve.prototype;
        _proto.evaluate = function evaluate(time) {
          var times = this._times,
            values = this._values;
          var nFrames = times.length;
          if (nFrames === 0) {
            return 0.0;
          }
          var firstTime = times[0];
          var lastTime = times[nFrames - 1];
          if (time < firstTime) {
            var preExtrapolation = this.preExtrapolation;
            var _preValue = values[0];
            if (preExtrapolation === ExtrapolationMode.CLAMP || nFrames < 2) {
              return _preValue.value;
            }
            switch (preExtrapolation) {
              case ExtrapolationMode.LINEAR:
                return linearTrend(firstTime, values[0].value, times[1], values[1].value, time);
              case ExtrapolationMode.LOOP:
                time = wrapRepeat(time, firstTime, lastTime);
                break;
              case ExtrapolationMode.PING_PONG:
                time = wrapPingPong(time, firstTime, lastTime);
                break;
              default:
                return _preValue.value;
            }
          } else if (time > lastTime) {
            var postExtrapolation = this.postExtrapolation;
            var preFrame = values[nFrames - 1];
            if (postExtrapolation === ExtrapolationMode.CLAMP || nFrames < 2) {
              return preFrame.value;
            }
            switch (postExtrapolation) {
              case ExtrapolationMode.LINEAR:
                return linearTrend(lastTime, preFrame.value, times[nFrames - 2], values[nFrames - 2].value, time);
              case ExtrapolationMode.LOOP:
                time = wrapRepeat(time, firstTime, lastTime);
                break;
              case ExtrapolationMode.PING_PONG:
                time = wrapPingPong(time, firstTime, lastTime);
                break;
              default:
                return preFrame.value;
            }
          }
          var index = binarySearchEpsilon(times, time);
          if (index >= 0) {
            return values[index].value;
          }
          var iNext = ~index;
          {
            assertIsTrue(iNext !== 0 && iNext !== nFrames && nFrames > 1);
          }
          var iPre = iNext - 1;
          var preTime = times[iPre];
          var preValue = values[iPre];
          var nextTime = times[iNext];
          var nextValue = values[iNext];
          {
            assertIsTrue(nextTime > time && time > preTime);
          }
          var dt = nextTime - preTime;
          var ratio = (time - preTime) / dt;
          return evalBetweenTwoKeyFrames(preTime, preValue, nextTime, nextValue, ratio);
        };
        _proto.addKeyFrame = function addKeyFrame(time, value) {
          return _KeyframeCurve.prototype.addKeyFrame.call(this, time, createRealKeyframeValue(value));
        };
        _proto.assignSorted = function assignSorted(times, values) {
          if (values !== undefined) {
            assertIsTrue(Array.isArray(times));
            this.setKeyframes(times.slice(), values.map(function (value) {
              return createRealKeyframeValue(value);
            }));
          } else {
            var _keyframes = Array.from(times);
            this.setKeyframes(_keyframes.map(function (_ref) {
              var time = _ref[0];
              return time;
            }), _keyframes.map(function (_ref2) {
              var value = _ref2[1];
              return createRealKeyframeValue(value);
            }));
          }
        };
        _proto.isConstant = function isConstant(tolerance) {
          if (this._values.length <= 1) {
            return true;
          }
          var firstVal = this._values[0].value;
          return this._values.every(function (frame) {
            return approx(frame.value, firstVal, tolerance);
          });
        };
        _proto[serializeTag] = function (output, context) {
          if (!context.toCCON) {
            output.writeThis();
            return;
          }
          var times = this._times,
            keyframeValues = this._values;
          var nKeyframes = times.length;
          var dataSize = 0 + OVERFLOW_BYTES + OVERFLOW_BYTES + FRAME_COUNT_BYTES$1 + TIME_BYTES$1 * nKeyframes + REAL_KEY_FRAME_VALUE_MAX_SIZE * nKeyframes;
          var dataView = new DataView(new ArrayBuffer(dataSize));
          var currentOffset = 0;
          dataView.setUint8(currentOffset, this.preExtrapolation);
          currentOffset += OVERFLOW_BYTES;
          dataView.setUint8(currentOffset, this.postExtrapolation);
          currentOffset += OVERFLOW_BYTES;
          dataView.setUint32(currentOffset, nKeyframes, true);
          currentOffset += FRAME_COUNT_BYTES$1;
          times.forEach(function (time, index) {
            return dataView.setFloat32(currentOffset + TIME_BYTES$1 * index, time, true);
          });
          currentOffset += TIME_BYTES$1 * nKeyframes;
          for (var _iterator = _createForOfIteratorHelperLoose(keyframeValues), _step; !(_step = _iterator()).done;) {
            var keyframeValue = _step.value;
            currentOffset = saveRealKeyFrameValue(dataView, keyframeValue, currentOffset);
          }
          var bytes = new Uint8Array(dataView.buffer, 0, currentOffset);
          output.writeProperty('bytes', bytes);
          var keyframeValueEditorExtras = keyframeValues.map(function (keyframeValue) {
            return keyframeValue[editorExtrasTag];
          });
          if (keyframeValueEditorExtras.some(function (extras) {
            return extras !== undefined;
          })) {
            output.writeProperty("keyframeValueEditorExtras", keyframeValueEditorExtras);
          }
        };
        _proto[deserializeTag] = function (input, context) {
          if (!context.fromCCON) {
            input.readThis();
            return;
          }
          var bytes = input.readProperty('bytes');
          var dataView = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
          var currentOffset = 0;
          this.preExtrapolation = dataView.getUint8(currentOffset);
          currentOffset += OVERFLOW_BYTES;
          this.postExtrapolation = dataView.getUint8(currentOffset);
          currentOffset += OVERFLOW_BYTES;
          var nKeyframes = dataView.getUint32(currentOffset, true);
          currentOffset += FRAME_COUNT_BYTES$1;
          var times = Array.from({
            length: nKeyframes
          }, function (_, index) {
            return dataView.getFloat32(currentOffset + TIME_BYTES$1 * index, true);
          });
          currentOffset += TIME_BYTES$1 * nKeyframes;
          var keyframeValues = new Array(nKeyframes);
          for (var iKeyFrame = 0; iKeyFrame < nKeyframes; ++iKeyFrame) {
            var keyframeValue = createRealKeyframeValue({});
            currentOffset = loadRealKeyFrameValue(dataView, keyframeValue, currentOffset);
            keyframeValues[iKeyFrame] = keyframeValue;
          }
          assertIsTrue(currentOffset === bytes.byteLength);
          var keyframeValueEditorExtras = input.readProperty("keyframeValueEditorExtras");
          if (keyframeValueEditorExtras) {
            assertIsTrue(keyframeValueEditorExtras.length === nKeyframes);
            keyframeValueEditorExtras.forEach(function (extras, index) {
              return keyframeValues[index][editorExtrasTag] = extras;
            });
          }
          this._times = times;
          this._values = keyframeValues;
        };
        return RealCurve;
      }(KeyframeCurve));
      CCClass.fastDefine('cc.RealCurve', RealCurve, {
        _times: [],
        _values: [],
        preExtrapolation: ExtrapolationMode.CLAMP,
        postExtrapolation: ExtrapolationMode.CLAMP
      });
      var FLAGS_EASING_METHOD_BITS_START = 8;
      var FLAG_EASING_METHOD_MASK = 0xFF << FLAGS_EASING_METHOD_BITS_START;
      var KeyframeValueFlagMask$1;
      (function (KeyframeValueFlagMask) {
        KeyframeValueFlagMask[KeyframeValueFlagMask["VALUE"] = 1] = "VALUE";
        KeyframeValueFlagMask[KeyframeValueFlagMask["INTERPOLATION_MODE"] = 2] = "INTERPOLATION_MODE";
        KeyframeValueFlagMask[KeyframeValueFlagMask["TANGENT_WEIGHT_MODE"] = 4] = "TANGENT_WEIGHT_MODE";
        KeyframeValueFlagMask[KeyframeValueFlagMask["LEFT_TANGENT"] = 8] = "LEFT_TANGENT";
        KeyframeValueFlagMask[KeyframeValueFlagMask["LEFT_TANGENT_WEIGHT"] = 16] = "LEFT_TANGENT_WEIGHT";
        KeyframeValueFlagMask[KeyframeValueFlagMask["RIGHT_TANGENT"] = 32] = "RIGHT_TANGENT";
        KeyframeValueFlagMask[KeyframeValueFlagMask["RIGHT_TANGENT_WEIGHT"] = 64] = "RIGHT_TANGENT_WEIGHT";
      })(KeyframeValueFlagMask$1 || (KeyframeValueFlagMask$1 = {}));
      var OVERFLOW_BYTES = 1;
      var FRAME_COUNT_BYTES$1 = 4;
      var TIME_BYTES$1 = 4;
      var KEY_FRAME_VALUE_FLAGS_BYTES = 4;
      var VALUE_BYTES$1 = 4;
      var INTERPOLATION_MODE_BYTES$1 = 1;
      var TANGENT_WEIGHT_MODE_BYTES = 1;
      var LEFT_TANGENT_BYTES = 4;
      var LEFT_TANGENT_WEIGHT_BYTES = 4;
      var RIGHT_TANGENT_BYTES = 4;
      var RIGHT_TANGENT_WEIGHT_BYTES = 4;
      var _createRealKeyframeVa = createRealKeyframeValue({}),
        DEFAULT_INTERPOLATION_MODE = _createRealKeyframeVa.interpolationMode,
        DEFAULT_TANGENT_WEIGHT_MODE = _createRealKeyframeVa.tangentWeightMode,
        DEFAULT_LEFT_TANGENT = _createRealKeyframeVa.leftTangent,
        DEFAULT_LEFT_TANGENT_WEIGHT = _createRealKeyframeVa.leftTangentWeight,
        DEFAULT_RIGHT_TANGENT = _createRealKeyframeVa.rightTangent,
        DEFAULT_RIGHT_TANGENT_WEIGHT = _createRealKeyframeVa.rightTangentWeight;
      var REAL_KEY_FRAME_VALUE_MAX_SIZE = KEY_FRAME_VALUE_FLAGS_BYTES + VALUE_BYTES$1 + INTERPOLATION_MODE_BYTES$1 + TANGENT_WEIGHT_MODE_BYTES + LEFT_TANGENT_BYTES + LEFT_TANGENT_WEIGHT_BYTES + RIGHT_TANGENT_BYTES + RIGHT_TANGENT_WEIGHT_BYTES + 0;
      function saveRealKeyFrameValue(dataView, keyframeValue, offset) {
        var flags = 0;
        var currentOffset = offset;
        var pFlags = currentOffset;
        currentOffset += KEY_FRAME_VALUE_FLAGS_BYTES;
        var value = keyframeValue.value,
          interpolationMode = keyframeValue.interpolationMode,
          tangentWeightMode = keyframeValue.tangentWeightMode,
          rightTangent = keyframeValue.rightTangent,
          rightTangentWeight = keyframeValue.rightTangentWeight,
          leftTangent = keyframeValue.leftTangent,
          leftTangentWeight = keyframeValue.leftTangentWeight,
          easingMethod = keyframeValue.easingMethod;
        dataView.setFloat32(currentOffset, value, true);
        currentOffset += VALUE_BYTES$1;
        if (interpolationMode !== DEFAULT_INTERPOLATION_MODE) {
          flags |= KeyframeValueFlagMask$1.INTERPOLATION_MODE;
          dataView.setUint8(currentOffset, interpolationMode);
          currentOffset += INTERPOLATION_MODE_BYTES$1;
        }
        if (tangentWeightMode !== DEFAULT_TANGENT_WEIGHT_MODE) {
          flags |= KeyframeValueFlagMask$1.TANGENT_WEIGHT_MODE;
          dataView.setUint8(currentOffset, tangentWeightMode);
          currentOffset += TANGENT_WEIGHT_MODE_BYTES;
        }
        if (leftTangent !== DEFAULT_LEFT_TANGENT) {
          flags |= KeyframeValueFlagMask$1.LEFT_TANGENT;
          dataView.setFloat32(currentOffset, leftTangent, true);
          currentOffset += LEFT_TANGENT_BYTES;
        }
        if (leftTangentWeight !== DEFAULT_LEFT_TANGENT_WEIGHT) {
          flags |= KeyframeValueFlagMask$1.LEFT_TANGENT_WEIGHT;
          dataView.setFloat32(currentOffset, leftTangentWeight, true);
          currentOffset += LEFT_TANGENT_WEIGHT_BYTES;
        }
        if (rightTangent !== DEFAULT_RIGHT_TANGENT) {
          flags |= KeyframeValueFlagMask$1.RIGHT_TANGENT;
          dataView.setFloat32(currentOffset, rightTangent, true);
          currentOffset += RIGHT_TANGENT_BYTES;
        }
        if (rightTangentWeight !== DEFAULT_RIGHT_TANGENT_WEIGHT) {
          flags |= KeyframeValueFlagMask$1.RIGHT_TANGENT_WEIGHT;
          dataView.setFloat32(currentOffset, rightTangentWeight, true);
          currentOffset += RIGHT_TANGENT_WEIGHT_BYTES;
        }
        flags |= easingMethod << FLAGS_EASING_METHOD_BITS_START;
        dataView.setUint32(pFlags, flags, true);
        return currentOffset;
      }
      function loadRealKeyFrameValue(dataView, keyframeValue, offset) {
        var currentOffset = offset;
        var flags = dataView.getUint32(currentOffset, true);
        currentOffset += KEY_FRAME_VALUE_FLAGS_BYTES;
        keyframeValue.value = dataView.getFloat32(currentOffset, true);
        currentOffset += VALUE_BYTES$1;
        if (flags & KeyframeValueFlagMask$1.INTERPOLATION_MODE) {
          keyframeValue.interpolationMode = dataView.getUint8(currentOffset);
          currentOffset += INTERPOLATION_MODE_BYTES$1;
        }
        if (flags & KeyframeValueFlagMask$1.TANGENT_WEIGHT_MODE) {
          keyframeValue.tangentWeightMode = dataView.getUint8(currentOffset);
          currentOffset += TANGENT_WEIGHT_MODE_BYTES;
        }
        if (flags & KeyframeValueFlagMask$1.LEFT_TANGENT) {
          keyframeValue.leftTangent = dataView.getFloat32(currentOffset, true);
          currentOffset += LEFT_TANGENT_BYTES;
        }
        if (flags & KeyframeValueFlagMask$1.LEFT_TANGENT_WEIGHT) {
          keyframeValue.leftTangentWeight = dataView.getFloat32(currentOffset, true);
          currentOffset += LEFT_TANGENT_WEIGHT_BYTES;
        }
        if (flags & KeyframeValueFlagMask$1.RIGHT_TANGENT) {
          keyframeValue.rightTangent = dataView.getFloat32(currentOffset, true);
          currentOffset += RIGHT_TANGENT_BYTES;
        }
        if (flags & KeyframeValueFlagMask$1.RIGHT_TANGENT_WEIGHT) {
          keyframeValue.rightTangentWeight = dataView.getFloat32(currentOffset, true);
          currentOffset += RIGHT_TANGENT_WEIGHT_BYTES;
        }
        var easingMethod = (flags & FLAG_EASING_METHOD_MASK) >> FLAGS_EASING_METHOD_BITS_START;
        keyframeValue.easingMethod = easingMethod;
        return currentOffset;
      }
      function wrapRepeat(time, prevTime, nextTime) {
        return prevTime + repeat$2(time - prevTime, nextTime - prevTime);
      }
      function wrapPingPong(time, prevTime, nextTime) {
        return prevTime + pingPong(time - prevTime, nextTime - prevTime);
      }
      function linearTrend(prevTime, prevValue, nextTime, nextValue, time) {
        var slope = (nextValue - prevValue) / (nextTime - prevTime);
        return prevValue + (time - prevTime) * slope;
      }
      function evalBetweenTwoKeyFrames(prevTime, prevValue, nextTime, nextValue, ratio) {
        var dt = nextTime - prevTime;
        switch (prevValue.interpolationMode) {
          default:
          case RealInterpolationMode.CONSTANT:
            return prevValue.value;
          case RealInterpolationMode.LINEAR:
            {
              var transformedRatio = prevValue.easingMethod === EasingMethod.LINEAR ? ratio : getEasingFn(prevValue.easingMethod)(ratio);
              return lerp(prevValue.value, nextValue.value, transformedRatio);
            }
          case RealInterpolationMode.CUBIC:
            {
              var ONE_THIRD = 1.0 / 3.0;
              var prevTangent = prevValue.rightTangent,
                prevTangentWeightSpecified = prevValue.rightTangentWeight;
              var prevTangentWeightEnabled = isRightTangentWeightEnabled(prevValue.tangentWeightMode);
              var nextTangent = nextValue.leftTangent,
                nextTangentWeightSpecified = nextValue.leftTangentWeight;
              var nextTangentWeightEnabled = isLeftTangentWeightEnabled(nextValue.tangentWeightMode);
              if (!prevTangentWeightEnabled && !nextTangentWeightEnabled) {
                var p1 = prevValue.value + ONE_THIRD * prevTangent * dt;
                var p2 = nextValue.value - ONE_THIRD * nextTangent * dt;
                return bezierInterpolate(prevValue.value, p1, p2, nextValue.value, ratio);
              } else {
                var prevTangentWeight = 0.0;
                if (prevTangentWeightEnabled) {
                  prevTangentWeight = prevTangentWeightSpecified;
                } else {
                  var x = dt;
                  var _y = dt * prevTangent;
                  prevTangentWeight = Math.sqrt(x * x + _y * _y) * ONE_THIRD;
                }
                var angle0 = Math.atan(prevTangent);
                var tx0 = Math.cos(angle0) * prevTangentWeight + prevTime;
                var ty0 = Math.sin(angle0) * prevTangentWeight + prevValue.value;
                var nextTangentWeight = 0.0;
                if (nextTangentWeightEnabled) {
                  nextTangentWeight = nextTangentWeightSpecified;
                } else {
                  var _x = dt;
                  var _y2 = dt * nextTangent;
                  nextTangentWeight = Math.sqrt(_x * _x + _y2 * _y2) * ONE_THIRD;
                }
                var angle1 = Math.atan(nextTangent);
                var tx1 = -Math.cos(angle1) * nextTangentWeight + nextTime;
                var ty1 = -Math.sin(angle1) * nextTangentWeight + nextValue.value;
                var dx = dt;
                var u0x = (tx0 - prevTime) / dx;
                var u1x = (tx1 - prevTime) / dx;
                var u0y = ty0;
                var u1y = ty1;
                var coeff0 = 0.0;
                var coeff1 = 3.0 * u0x;
                var coeff2 = 3.0 * u1x - 6.0 * u0x;
                var coeff3 = 3.0 * (u0x - u1x) + 1.0;
                var solutions = [0.0, 0.0, 0.0];
                var nSolutions = solveCubic(coeff0 - ratio, coeff1, coeff2, coeff3, solutions);
                var param = getParamFromCubicSolution(solutions, nSolutions, ratio);
                var y = bezierInterpolate(prevValue.value, u0y, u1y, nextValue.value, param);
                return y;
              }
            }
        }
      }
      function isLeftTangentWeightEnabled(tangentWeightMode) {
        return (tangentWeightMode & TangentWeightMode.LEFT) !== 0;
      }
      function isRightTangentWeightEnabled(tangentWeightMode) {
        return (tangentWeightMode & TangentWeightMode.RIGHT) !== 0;
      }
      function bezierInterpolate(p0, p1, p2, p3, t) {
        var u = 1 - t;
        var coeff0 = u * u * u;
        var coeff1 = 3 * u * u * t;
        var coeff2 = 3 * u * t * t;
        var coeff3 = t * t * t;
        return coeff0 * p0 + coeff1 * p1 + coeff2 * p2 + coeff3 * p3;
      }
      function getParamFromCubicSolution(solutions, solutionsCount, x) {
        var param = x;
        if (solutionsCount === 1) {
          param = solutions[0];
        } else {
          param = -Infinity;
          for (var iSolution = 0; iSolution < solutionsCount; ++iSolution) {
            var solution = solutions[iSolution];
            if (solution >= 0.0 && solution <= 1.0) {
              if (solution > param) {
                param = solution;
              }
            }
          }
          if (param === -Infinity) {
            param = 0.0;
          }
        }
        return param;
      }

      function bezier(C1, C2, C3, C4, t) {
        var t1 = 1 - t;
        return t1 * (t1 * (C1 + (C2 * 3 - C1) * t) + C3 * 3 * t * t) + C4 * t * t * t;
      }
      legacyCC.bezier = bezier;
      var cos$2 = Math.cos;
      var acos$1 = Math.acos;
      var max$2 = Math.max;
      var pi = Math.PI;
      var tau = 2 * pi;
      var sqrt = Math.sqrt;
      function crt(v) {
        if (v < 0) {
          return -Math.pow(-v, 1 / 3);
        } else {
          return Math.pow(v, 1 / 3);
        }
      }
      function cardano(curve, x) {
        var pa = x - 0;
        var pb = x - curve[0];
        var pc = x - curve[2];
        var pd = x - 1;
        var pa3 = pa * 3;
        var pb3 = pb * 3;
        var pc3 = pc * 3;
        var d = -pa + pb3 - pc3 + pd;
        var rd = 1 / d;
        var r3 = 1 / 3;
        var a = (pa3 - 6 * pb + pc3) * rd;
        var a3 = a * r3;
        var b = (-pa3 + pb3) * rd;
        var c = pa * rd;
        var p = (3 * b - a * a) * r3;
        var p3 = p * r3;
        var q = (2 * a * a * a - 9 * a * b + 27 * c) / 27;
        var q2 = q / 2;
        var discriminant = q2 * q2 + p3 * p3 * p3;
        var u1;
        var v1;
        var x1;
        var x2;
        var x3;
        if (discriminant < 0) {
          var mp3 = -p * r3;
          var mp33 = mp3 * mp3 * mp3;
          var r = sqrt(mp33);
          var t = -q / (2 * r);
          var cosphi = t < -1 ? -1 : t > 1 ? 1 : t;
          var phi = acos$1(cosphi);
          var crtr = crt(r);
          var t1 = 2 * crtr;
          x1 = t1 * cos$2(phi * r3) - a3;
          x2 = t1 * cos$2((phi + tau) * r3) - a3;
          x3 = t1 * cos$2((phi + 2 * tau) * r3) - a3;
          if (x1 >= 0 && x1 <= 1) {
            if (x2 >= 0 && x2 <= 1) {
              if (x3 >= 0 && x3 <= 1) {
                return max$2(x1, x2, x3);
              } else {
                return max$2(x1, x2);
              }
            } else if (x3 >= 0 && x3 <= 1) {
              return max$2(x1, x3);
            } else {
              return x1;
            }
          } else if (x2 >= 0 && x2 <= 1) {
            if (x3 >= 0 && x3 <= 1) {
              return max$2(x2, x3);
            } else {
              return x2;
            }
          } else {
            return x3;
          }
        } else if (discriminant === 0) {
          u1 = q2 < 0 ? crt(-q2) : -crt(q2);
          x1 = 2 * u1 - a3;
          x2 = -u1 - a3;
          if (x1 >= 0 && x1 <= 1) {
            if (x2 >= 0 && x2 <= 1) {
              return max$2(x1, x2);
            } else {
              return x1;
            }
          } else {
            return x2;
          }
        } else {
          var sd = sqrt(discriminant);
          u1 = crt(-q2 + sd);
          v1 = crt(q2 + sd);
          x1 = u1 - v1 - a3;
          return x1;
        }
      }
      function bezierByTime(controlPoints, x) {
        var percent = cardano(controlPoints, x);
        var p1y = controlPoints[1];
        var p2y = controlPoints[3];
        return ((1 - percent) * (p1y + (p2y - p1y) * percent) * 3 + percent * percent) * percent;
      }
      legacyCC.bezierByTime = bezierByTime;

      var _dec$34, _class$31, _class2$2L, _initializer$2r, _initializer2$1S, _initializer3$1h, _dec2$27, _class4$x, _class5$y, _initializer4$$, _initializer5$K;
      var QuatInterpolationMode; exports('cl', QuatInterpolationMode);
      (function (QuatInterpolationMode) {
        QuatInterpolationMode[QuatInterpolationMode["SLERP"] = 0] = "SLERP";
        QuatInterpolationMode[QuatInterpolationMode["CONSTANT"] = 1] = "CONSTANT";
      })(QuatInterpolationMode || (exports('cl', QuatInterpolationMode = {})));
      var QuatKeyframeValue = (_dec$34 = ccclass$n('cc.QuatKeyframeValue'), _dec$34(_class$31 = uniquelyReferenced(_class$31 = (_class2$2L = function QuatKeyframeValue(_temp) {
        var _ref = _temp === void 0 ? {} : _temp,
          value = _ref.value,
          interpolationMode = _ref.interpolationMode,
          easingMethod = _ref.easingMethod;
        this.interpolationMode = _initializer$2r && _initializer$2r();
        this.value = _initializer2$1S && _initializer2$1S();
        this.easingMethod = _initializer3$1h && _initializer3$1h();
        this.value = value ? Quat.clone(value) : this.value;
        this.interpolationMode = interpolationMode !== null && interpolationMode !== void 0 ? interpolationMode : this.interpolationMode;
        this.easingMethod = easingMethod !== null && easingMethod !== void 0 ? easingMethod : this.easingMethod;
      }, (_initializer$2r = applyDecoratedInitializer(_class2$2L.prototype, "interpolationMode", [serializable$j], function () {
        return QuatInterpolationMode.SLERP;
      }), _initializer2$1S = applyDecoratedInitializer(_class2$2L.prototype, "value", [serializable$j], function () {
        return Quat.clone(Quat.IDENTITY);
      }), _initializer3$1h = applyDecoratedInitializer(_class2$2L.prototype, "easingMethod", [serializable$j], function () {
        return EasingMethod.LINEAR;
      })), _class2$2L)) || _class$31) || _class$31);
      function createQuatKeyframeValue(params) {
        return new QuatKeyframeValue(params);
      }
      var QuatCurve = exports('ck', (_dec2$27 = ccclass$n('cc.QuatCurve'), _dec2$27(_class4$x = (_class5$y = function (_KeyframeCurve) {
        _inheritsLoose(QuatCurve, _KeyframeCurve);
        function QuatCurve() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _KeyframeCurve.call.apply(_KeyframeCurve, [this].concat(args)) || this;
          _this.preExtrapolation = _initializer4$$ && _initializer4$$();
          _this.postExtrapolation = _initializer5$K && _initializer5$K();
          return _this;
        }
        var _proto = QuatCurve.prototype;
        _proto.evaluate = function evaluate(time, quat) {
          var _quat;
          (_quat = quat) !== null && _quat !== void 0 ? _quat : quat = new Quat();
          var times = this._times,
            values = this._values,
            postExtrapolation = this.postExtrapolation,
            preExtrapolation = this.preExtrapolation;
          var nFrames = times.length;
          if (nFrames === 0) {
            return quat;
          }
          var firstTime = times[0];
          var lastTime = times[nFrames - 1];
          if (time < firstTime) {
            var _preValue = values[0];
            switch (preExtrapolation) {
              case ExtrapolationMode.LOOP:
                time = firstTime + repeat$2(time - firstTime, lastTime - firstTime);
                break;
              case ExtrapolationMode.PING_PONG:
                time = firstTime + pingPong(time - firstTime, lastTime - firstTime);
                break;
              case ExtrapolationMode.CLAMP:
              default:
                return Quat.copy(quat, _preValue.value);
            }
          } else if (time > lastTime) {
            var _preValue2 = values[nFrames - 1];
            switch (postExtrapolation) {
              case ExtrapolationMode.LOOP:
                time = firstTime + repeat$2(time - firstTime, lastTime - firstTime);
                break;
              case ExtrapolationMode.PING_PONG:
                time = firstTime + pingPong(time - firstTime, lastTime - firstTime);
                break;
              case ExtrapolationMode.CLAMP:
              default:
                return Quat.copy(quat, _preValue2.value);
            }
          }
          var index = binarySearchEpsilon(times, time);
          if (index >= 0) {
            return Quat.copy(quat, values[index].value);
          }
          var iNext = ~index;
          assertIsTrue(iNext !== 0 && iNext !== nFrames && nFrames > 1);
          var iPre = iNext - 1;
          var preTime = times[iPre];
          var preValue = values[iPre];
          var nextTime = times[iNext];
          var nextValue = values[iNext];
          assertIsTrue(nextTime > time && time > preTime);
          var dt = nextTime - preTime;
          var ratio = (time - preTime) / dt;
          switch (preValue.interpolationMode) {
            default:
            case QuatInterpolationMode.CONSTANT:
              return Quat.copy(quat, preValue.value);
            case QuatInterpolationMode.SLERP:
              {
                var easingMethod = preValue.easingMethod;
                var transformedRatio = easingMethod === EasingMethod.LINEAR ? ratio : Array.isArray(easingMethod) ? bezierByTime(easingMethod, ratio) : getEasingFn(easingMethod)(ratio);
                return Quat.slerp(quat, preValue.value, nextValue.value, transformedRatio);
              }
          }
        };
        _proto.addKeyFrame = function addKeyFrame(time, value) {
          var keyframeValue = new QuatKeyframeValue(value);
          return _KeyframeCurve.prototype.addKeyFrame.call(this, time, keyframeValue);
        };
        _proto.assignSorted = function assignSorted(times, values) {
          if (values !== undefined) {
            assertIsTrue(Array.isArray(times));
            this.setKeyframes(times.slice(), values.map(function (value) {
              return createQuatKeyframeValue(value);
            }));
          } else {
            var _keyframes = Array.from(times);
            this.setKeyframes(_keyframes.map(function (_ref2) {
              var time = _ref2[0];
              return time;
            }), _keyframes.map(function (_ref3) {
              var value = _ref3[1];
              return createQuatKeyframeValue(value);
            }));
          }
        };
        _proto[serializeTag] = function (output, context) {
          if (!context.toCCON) {
            output.writeThis();
            return;
          }
          var times = this._times,
            keyframeValues = this._values;
          var interpolationModeRepeated = true;
          keyframeValues.forEach(function (keyframeValue, _index, _ref4) {
            var firstKeyframeValue = _ref4[0];
            if (interpolationModeRepeated && keyframeValue.interpolationMode !== firstKeyframeValue.interpolationMode) {
              interpolationModeRepeated = false;
            }
          });
          var nKeyframes = times.length;
          var nFrames = nKeyframes;
          var interpolationModesSize = INTERPOLATION_MODE_BYTES * (interpolationModeRepeated ? 1 : nFrames);
          var easingMethodsSize = keyframeValues.reduce(function (result, _ref5) {
            var easingMethod = _ref5.easingMethod;
            return result += Array.isArray(easingMethod) ? EASING_METHOD_BYTES + EASING_METHOD_BEZIER_COMPONENT_BYTES * 4 : EASING_METHOD_BYTES;
          }, 0);
          var dataSize = 0;
          dataSize += FLAGS_BYTES + FRAME_COUNT_BYTES + TIME_BYTES * nFrames + VALUE_BYTES * 4 * nFrames + easingMethodsSize + interpolationModesSize + 0;
          var dataView = new DataView(new ArrayBuffer(dataSize));
          var P = 0;
          var flags = 0;
          if (interpolationModeRepeated) {
            flags |= KeyframeValueFlagMask.INTERPOLATION_MODE;
          }
          dataView.setUint32(P, flags, true);
          P += FLAGS_BYTES;
          dataView.setUint32(P, nFrames, true);
          P += FRAME_COUNT_BYTES;
          times.forEach(function (time, index) {
            return dataView.setFloat32(P + TIME_BYTES * index, time, true);
          });
          P += TIME_BYTES * nFrames;
          keyframeValues.forEach(function (_ref6, index) {
            var _ref6$value = _ref6.value,
              x = _ref6$value.x,
              y = _ref6$value.y,
              z = _ref6$value.z,
              w = _ref6$value.w;
            var pQuat = P + VALUE_BYTES * 4 * index;
            dataView.setFloat32(pQuat + VALUE_BYTES * 0, x, true);
            dataView.setFloat32(pQuat + VALUE_BYTES * 1, y, true);
            dataView.setFloat32(pQuat + VALUE_BYTES * 2, z, true);
            dataView.setFloat32(pQuat + VALUE_BYTES * 3, w, true);
          });
          P += VALUE_BYTES * 4 * nFrames;
          keyframeValues.forEach(function (_ref7, index) {
            var easingMethod = _ref7.easingMethod;
            if (!Array.isArray(easingMethod)) {
              dataView.setUint8(P, easingMethod);
              ++P;
            } else {
              dataView.setUint8(P, EASING_METHOD_BEZIER_TAG);
              ++P;
              dataView.setFloat32(P + EASING_METHOD_BEZIER_COMPONENT_BYTES * 0, easingMethod[0], true);
              dataView.setFloat32(P + EASING_METHOD_BEZIER_COMPONENT_BYTES * 1, easingMethod[1], true);
              dataView.setFloat32(P + EASING_METHOD_BEZIER_COMPONENT_BYTES * 2, easingMethod[2], true);
              dataView.setFloat32(P + EASING_METHOD_BEZIER_COMPONENT_BYTES * 3, easingMethod[3], true);
              P += EASING_METHOD_BEZIER_COMPONENT_BYTES * 4;
            }
          });
          var INTERPOLATION_MODES_START = P;
          P += interpolationModesSize;
          var pInterpolationMode = INTERPOLATION_MODES_START;
          keyframeValues.forEach(function (_ref8) {
            var interpolationMode = _ref8.interpolationMode;
            dataView.setUint8(pInterpolationMode, interpolationMode);
            if (!interpolationModeRepeated) {
              pInterpolationMode += INTERPOLATION_MODE_BYTES;
            }
          });
          var bytes = new Uint8Array(dataView.buffer);
          output.writeProperty('bytes', bytes);
        };
        _proto[deserializeTag] = function (input, context) {
          if (!context.fromCCON) {
            input.readThis();
            return;
          }
          var bytes = input.readProperty('bytes');
          var dataView = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
          var P = 0;
          var flags = dataView.getUint32(P, true);
          P += FLAGS_BYTES;
          var interpolationModeRepeated = flags & KeyframeValueFlagMask.INTERPOLATION_MODE;
          var nFrames = dataView.getUint32(P, true);
          P += FRAME_COUNT_BYTES;
          var times = Array.from({
            length: nFrames
          }, function (_, index) {
            return dataView.getFloat32(P + TIME_BYTES * index, true);
          });
          P += TIME_BYTES * nFrames;
          var P_VALUES = P;
          P += VALUE_BYTES * 4 * nFrames;
          var keyframeValues = Array.from({
            length: nFrames
          }, function (_, index) {
            var pQuat = P_VALUES + VALUE_BYTES * 4 * index;
            var x = dataView.getFloat32(pQuat + VALUE_BYTES * 0, true);
            var y = dataView.getFloat32(pQuat + VALUE_BYTES * 1, true);
            var z = dataView.getFloat32(pQuat + VALUE_BYTES * 2, true);
            var w = dataView.getFloat32(pQuat + VALUE_BYTES * 3, true);
            var easingMethod = dataView.getUint8(P);
            ++P;
            var keyframeValue = createQuatKeyframeValue({
              value: {
                x: x,
                y: y,
                z: z,
                w: w
              }
            });
            if (easingMethod !== EASING_METHOD_BEZIER_TAG) {
              keyframeValue.easingMethod = easingMethod;
            } else {
              keyframeValue.easingMethod = [dataView.getFloat32(P + EASING_METHOD_BEZIER_COMPONENT_BYTES * 0, true), dataView.getFloat32(P + EASING_METHOD_BEZIER_COMPONENT_BYTES * 1, true), dataView.getFloat32(P + EASING_METHOD_BEZIER_COMPONENT_BYTES * 2, true), dataView.getFloat32(P + EASING_METHOD_BEZIER_COMPONENT_BYTES * 3, true)];
              P += EASING_METHOD_BEZIER_COMPONENT_BYTES * 4;
            }
            return keyframeValue;
          });
          if (interpolationModeRepeated) {
            var interpolationMode = dataView.getUint8(P);
            ++P;
            for (var iKeyframe = 0; iKeyframe < nFrames; ++iKeyframe) {
              keyframeValues[iKeyframe].interpolationMode = interpolationMode;
            }
          } else {
            for (var _iKeyframe = 0; _iKeyframe < nFrames; ++_iKeyframe) {
              var _interpolationMode = dataView.getUint8(P + _iKeyframe);
              keyframeValues[_iKeyframe].interpolationMode = _interpolationMode;
            }
            P += nFrames;
          }
          this._times = times;
          this._values = keyframeValues;
        };
        return QuatCurve;
      }(KeyframeCurve), (_initializer4$$ = applyDecoratedInitializer(_class5$y.prototype, "preExtrapolation", [serializable$j], function () {
        return ExtrapolationMode.CLAMP;
      }), _initializer5$K = applyDecoratedInitializer(_class5$y.prototype, "postExtrapolation", [serializable$j], function () {
        return ExtrapolationMode.CLAMP;
      })), _class5$y)) || _class4$x));
      var KeyframeValueFlagMask;
      (function (KeyframeValueFlagMask) {
        KeyframeValueFlagMask[KeyframeValueFlagMask["INTERPOLATION_MODE"] = 1] = "INTERPOLATION_MODE";
      })(KeyframeValueFlagMask || (KeyframeValueFlagMask = {}));
      var FLAGS_BYTES = 1;
      var FRAME_COUNT_BYTES = 4;
      var TIME_BYTES = 4;
      var VALUE_BYTES = 4;
      var INTERPOLATION_MODE_BYTES = 1;
      var EASING_METHOD_BYTES = 1;
      var EASING_METHOD_BEZIER_TAG = 255;
      var EASING_METHOD_BEZIER_COMPONENT_BYTES = 4;

      var _dec$33, _class$30;
      var ObjectCurve = exports('cm', (_dec$33 = ccclass$n('cc.ObjectCurve'), _dec$33(_class$30 = function (_KeyframeCurve) {
        _inheritsLoose(ObjectCurve, _KeyframeCurve);
        function ObjectCurve() {
          return _KeyframeCurve.apply(this, arguments) || this;
        }
        var _proto = ObjectCurve.prototype;
        _proto.evaluate = function evaluate(time) {
          var iSearch = this.searchKeyframe(time);
          if (iSearch >= 0) {
            return this._values[iSearch];
          }
          var iPrev = clamp$1(~iSearch - 1, 0, this._values.length - 1);
          return this._values[iPrev];
        };
        return ObjectCurve;
      }(KeyframeCurve)) || _class$30));

      var Mode$1 = Enum({
        Blend: 0,
        Fixed: 1
      });
      var ColorKey = exports('cn', function ColorKey() {
        this.color = Color$1.WHITE.clone();
        this.time = 0;
      });
      CCClass.fastDefine('cc.ColorKey', ColorKey, {
        color: Color$1.WHITE.clone(),
        time: 0
      });
      CCClass.Attr.setClassAttr(ColorKey, 'color', 'visible', true);
      CCClass.Attr.setClassAttr(ColorKey, 'time', 'visible', true);
      var AlphaKey = exports('co', function AlphaKey() {
        this.alpha = 1;
        this.time = 0;
      });
      CCClass.fastDefine('cc.AlphaKey', AlphaKey, {
        alpha: 1,
        time: 0
      });
      CCClass.Attr.setClassAttr(AlphaKey, 'alpha', 'visible', true);
      CCClass.Attr.setClassAttr(AlphaKey, 'time', 'visible', true);
      var Gradient = exports('cp', function () {
        function Gradient() {
          this.colorKeys = [];
          this.alphaKeys = [];
          this.mode = Mode$1.Blend;
        }
        var _proto = Gradient.prototype;
        _proto.setKeys = function setKeys(colorKeys, alphaKeys) {
          this.colorKeys = colorKeys;
          this.alphaKeys = alphaKeys;
        };
        _proto.sortKeys = function sortKeys() {
          if (this.colorKeys.length > 1) {
            this.colorKeys.sort(function (a, b) {
              return a.time - b.time;
            });
          }
          if (this.alphaKeys.length > 1) {
            this.alphaKeys.sort(function (a, b) {
              return a.time - b.time;
            });
          }
        };
        _proto.evaluate = function evaluate(time) {
          return this.evaluateFast(new Color$1(), time);
        };
        _proto.evaluateFast = function evaluateFast(out, time) {
          this.getRGB(out, time);
          out._set_a_unsafe(this.getAlpha(time));
          return out;
        };
        _proto.randomColor = function randomColor() {
          return this.getRandomColor(new Color$1());
        };
        _proto.getRandomColor = function getRandomColor(out) {
          var c = this.colorKeys[Math.trunc(random() * this.colorKeys.length)];
          var a = this.alphaKeys[Math.trunc(random() * this.alphaKeys.length)];
          out.set(c.color);
          out._set_a_unsafe(a.alpha);
          return out;
        };
        _proto.getRGB = function getRGB(out, time) {
          var colorKeys = this.colorKeys;
          var length = colorKeys.length;
          if (length > 1) {
            time = repeat$2(time, 1.0 + EPSILON$3);
            for (var i = 1; i < length; ++i) {
              var preTime = colorKeys[i - 1].time;
              var curTime = colorKeys[i].time;
              if (time >= preTime && time < curTime) {
                if (this.mode === Mode$1.Fixed) {
                  Color$1.copy(out, colorKeys[i].color);
                  return out;
                }
                var factor = (time - preTime) / (curTime - preTime);
                Color$1.lerp(out, colorKeys[i - 1].color, colorKeys[i].color, factor);
                return out;
              }
            }
            var lastIndex = length - 1;
            if (approx(time, colorKeys[lastIndex].time, EPSILON$3)) {
              Color$1.copy(out, colorKeys[lastIndex].color);
            } else if (time < colorKeys[0].time) {
              Color$1.lerp(out, Color$1.BLACK, colorKeys[0].color, time / colorKeys[0].time);
            } else if (time > colorKeys[lastIndex].time) {
              Color$1.lerp(out, colorKeys[lastIndex].color, Color$1.BLACK, (time - colorKeys[lastIndex].time) / (1 - colorKeys[lastIndex].time));
            }
          } else if (length === 1) {
            Color$1.copy(out, colorKeys[0].color);
          } else {
            Color$1.copy(out, Color$1.WHITE);
          }
          return out;
        };
        _proto.getAlpha = function getAlpha(time) {
          var basicAlpha = 0;
          var alphaKeys = this.alphaKeys;
          var length = alphaKeys.length;
          if (length > 1) {
            time = repeat$2(time, 1.0 + EPSILON$3);
            for (var i = 1; i < length; ++i) {
              var preTime = alphaKeys[i - 1].time;
              var curTime = alphaKeys[i].time;
              if (time >= preTime && time < curTime) {
                if (this.mode === Mode$1.Fixed) {
                  return alphaKeys[i].alpha;
                }
                var factor = (time - preTime) / (curTime - preTime);
                return lerp(alphaKeys[i - 1].alpha, alphaKeys[i].alpha, factor);
              }
            }
            var lastIndex = length - 1;
            if (approx(time, alphaKeys[lastIndex].time, EPSILON$3)) {
              return alphaKeys[lastIndex].alpha;
            } else if (time < alphaKeys[0].time) {
              return lerp(basicAlpha, alphaKeys[0].alpha, time / alphaKeys[0].time);
            } else if (time > alphaKeys[lastIndex].time) {
              return lerp(alphaKeys[lastIndex].alpha, basicAlpha, (time - alphaKeys[lastIndex].time) / (1 - alphaKeys[lastIndex].time));
            }
            return 255;
          } else if (length === 1) {
            return alphaKeys[0].alpha;
          } else {
            return 255;
          }
        };
        return Gradient;
      }());
      Gradient.Mode = Mode$1;
      CCClass.fastDefine('cc.Gradient', Gradient, {
        colorKeys: [],
        alphaKeys: [],
        mode: Mode$1.Blend
      });
      CCClass.Attr.setClassAttr(Gradient, 'colorKeys', 'visible', true);
      CCClass.Attr.setClassAttr(Gradient, 'alphaKeys', 'visible', true);
      CCClass.Attr.setClassAttr(Gradient, 'mode', 'visible', true);

      var LOOK_FORWARD = 3;
      var Keyframe = function Keyframe() {
        this.time = 0;
        this.value = 0;
        this.inTangent = 0;
        this.outTangent = 0;
      };
      CCClass.fastDefine('cc.Keyframe', Keyframe, {
        time: 0,
        value: 0,
        inTangent: 0,
        outTangent: 0
      });
      var OptimizedKey = function () {
        function OptimizedKey() {
          this.index = void 0;
          this.time = void 0;
          this.endTime = void 0;
          this.coefficient = void 0;
          this.index = -1;
          this.time = 0;
          this.endTime = 0;
          this.coefficient = new Float32Array(4);
        }
        var _proto = OptimizedKey.prototype;
        _proto.evaluate = function evaluate(T) {
          var t = T - this.time;
          return evalOptCurve(t, this.coefficient);
        };
        return OptimizedKey;
      }();
      function evalOptCurve(t, coefs) {
        return t * (t * (t * coefs[0] + coefs[1]) + coefs[2]) + coefs[3];
      }
      var AnimationCurve = function () {
        function AnimationCurve(keyFrames) {
          if (keyFrames === void 0) {
            keyFrames = null;
          }
          this._curve = void 0;
          this.cachedKey = void 0;
          if (keyFrames instanceof RealCurve) {
            this._curve = keyFrames;
          } else {
            var curve = new RealCurve();
            this._curve = curve;
            curve.preExtrapolation = ExtrapolationMode.LOOP;
            curve.postExtrapolation = ExtrapolationMode.CLAMP;
            if (!keyFrames) {
              curve.assignSorted([[0.0, {
                interpolationMode: RealInterpolationMode.CUBIC,
                value: 1.0
              }], [1.0, {
                interpolationMode: RealInterpolationMode.CUBIC,
                value: 1.0
              }]]);
            } else {
              curve.assignSorted(keyFrames.map(function (legacyKeyframe) {
                return [legacyKeyframe.time, {
                  interpolationMode: RealInterpolationMode.CUBIC,
                  value: legacyKeyframe.value,
                  leftTangent: legacyKeyframe.inTangent,
                  rightTangent: legacyKeyframe.outTangent
                }];
              }));
            }
          }
          this.cachedKey = new OptimizedKey();
        }
        var _proto2 = AnimationCurve.prototype;
        _proto2.addKey = function addKey(keyFrame) {
          if (!keyFrame) {
            this._curve.clear();
          } else {
            this._curve.addKeyFrame(keyFrame.time, {
              interpolationMode: RealInterpolationMode.CUBIC,
              value: keyFrame.value,
              leftTangent: keyFrame.inTangent,
              rightTangent: keyFrame.outTangent
            });
          }
        };
        _proto2.evaluate_slow = function evaluate_slow(time) {
          return this._curve.evaluate(time);
        };
        _proto2.evaluate = function evaluate(time) {
          var cachedKey = this.cachedKey,
            curve = this._curve;
          var nKeyframes = curve.keyFramesCount;
          var lastKeyframeIndex = nKeyframes - 1;
          var wrappedTime = time;
          var extrapolationMode = time < 0 ? curve.preExtrapolation : curve.postExtrapolation;
          var startTime = curve.getKeyframeTime(0);
          var endTime = curve.getKeyframeTime(lastKeyframeIndex);
          switch (extrapolationMode) {
            case ExtrapolationMode.LOOP:
              wrappedTime = repeat$2(time - startTime, endTime - startTime) + startTime;
              break;
            case ExtrapolationMode.PING_PONG:
              wrappedTime = pingPong(time - startTime, endTime - startTime) + startTime;
              break;
            case ExtrapolationMode.CLAMP:
            default:
              wrappedTime = clamp$1(time, startTime, endTime);
              break;
          }
          if (wrappedTime >= cachedKey.time && wrappedTime < cachedKey.endTime) {
            return cachedKey.evaluate(wrappedTime);
          }
          var leftIndex = this.findIndex(cachedKey, wrappedTime);
          var rightIndex = Math.min(leftIndex + 1, lastKeyframeIndex);
          this.calcOptimizedKey(cachedKey, leftIndex, rightIndex);
          return cachedKey.evaluate(wrappedTime);
        };
        _proto2.calcOptimizedKey = function calcOptimizedKey(optKey, leftIndex, rightIndex) {
          var lhsTime = this._curve.getKeyframeTime(leftIndex);
          var rhsTime = this._curve.getKeyframeTime(rightIndex);
          var _this$_curve$getKeyfr = this._curve.getKeyframeValue(leftIndex),
            lhsValue = _this$_curve$getKeyfr.value,
            lhsOutTangent = _this$_curve$getKeyfr.leftTangent;
          var _this$_curve$getKeyfr2 = this._curve.getKeyframeValue(rightIndex),
            rhsValue = _this$_curve$getKeyfr2.value,
            rhsInTangent = _this$_curve$getKeyfr2.rightTangent;
          optKey.index = leftIndex;
          optKey.time = lhsTime;
          optKey.endTime = rhsTime;
          var dx = rhsTime - lhsTime;
          var dy = rhsValue - lhsValue;
          var length = 1 / (dx * dx);
          var d1 = lhsOutTangent * dx;
          var d2 = rhsInTangent * dx;
          optKey.coefficient[0] = (d1 + d2 - dy - dy) * length / dx;
          optKey.coefficient[1] = (dy + dy + dy - d1 - d1 - d2) * length;
          optKey.coefficient[2] = lhsOutTangent;
          optKey.coefficient[3] = lhsValue;
        };
        _proto2.findIndex = function findIndex(optKey, t) {
          var curve = this._curve;
          var nKeyframes = curve.keyFramesCount;
          var cachedIndex = optKey.index;
          if (cachedIndex !== -1) {
            var cachedTime = curve.getKeyframeTime(cachedIndex);
            if (t > cachedTime) {
              for (var i = 0; i < LOOK_FORWARD; i++) {
                var currIndex = cachedIndex + i;
                if (currIndex + 1 < nKeyframes && curve.getKeyframeTime(currIndex + 1) > t) {
                  return currIndex;
                }
              }
            } else {
              for (var _i = 0; _i < LOOK_FORWARD; _i++) {
                var _currIndex = cachedIndex - _i;
                if (_currIndex >= 0 && curve.getKeyframeTime(_currIndex - 1) <= t) {
                  return _currIndex - 1;
                }
              }
            }
          }
          var left = 0;
          var right = nKeyframes;
          var mid;
          while (right - left > 1) {
            mid = Math.floor((left + right) / 2);
            if (curve.getKeyframeTime(mid) >= t) {
              right = mid;
            } else {
              left = mid;
            }
          }
          return left;
        };
        _createClass(AnimationCurve, [{
          key: "_internalCurve",
          get: function get() {
            return this._curve;
          }
        }, {
          key: "keyFrames",
          get: function get() {
            return Array.from(this._curve.keyframes()).map(function (_ref) {
              var time = _ref[0],
                value = _ref[1];
              var legacyKeyframe = new Keyframe();
              legacyKeyframe.time = time;
              legacyKeyframe.value = value.value;
              legacyKeyframe.inTangent = value.leftTangent;
              legacyKeyframe.outTangent = value.rightTangent;
              return legacyKeyframe;
            });
          },
          set: function set(value) {
            this._curve.assignSorted(value.map(function (legacyCurve) {
              return [legacyCurve.time, {
                interpolationMode: RealInterpolationMode.CUBIC,
                value: legacyCurve.value,
                leftTangent: legacyCurve.inTangent,
                rightTangent: legacyCurve.outTangent
              }];
            }));
          }
        }, {
          key: "preWrapMode",
          get: function get() {
            return toLegacyWrapMode(this._curve.preExtrapolation);
          },
          set: function set(value) {
            this._curve.preExtrapolation = fromLegacyWrapMode(value);
          }
        }, {
          key: "postWrapMode",
          get: function get() {
            return toLegacyWrapMode(this._curve.postExtrapolation);
          },
          set: function set(value) {
            this._curve.postExtrapolation = fromLegacyWrapMode(value);
          }
        }]);
        return AnimationCurve;
      }();
      AnimationCurve.defaultKF = [{
        time: 0,
        value: 1,
        inTangent: 0,
        outTangent: 0
      }, {
        time: 1,
        value: 1,
        inTangent: 0,
        outTangent: 0
      }];
      CCClass.fastDefine('cc.AnimationCurve', AnimationCurve, {
        _curve: null
      });
      var WrapModeMask;
      (function (WrapModeMask) {
        WrapModeMask[WrapModeMask["Default"] = 0] = "Default";
        WrapModeMask[WrapModeMask["Normal"] = 1] = "Normal";
        WrapModeMask[WrapModeMask["Loop"] = 2] = "Loop";
        WrapModeMask[WrapModeMask["ShouldWrap"] = 4] = "ShouldWrap";
        WrapModeMask[WrapModeMask["Clamp"] = 8] = "Clamp";
        WrapModeMask[WrapModeMask["PingPong"] = 22] = "PingPong";
        WrapModeMask[WrapModeMask["Reverse"] = 36] = "Reverse";
      })(WrapModeMask || (WrapModeMask = {}));
      function fromLegacyWrapMode(legacyWrapMode) {
        switch (legacyWrapMode) {
          default:
          case WrapModeMask.Default:
          case WrapModeMask.Normal:
          case WrapModeMask.Clamp:
            return ExtrapolationMode.CLAMP;
          case WrapModeMask.PingPong:
            return ExtrapolationMode.PING_PONG;
          case WrapModeMask.Loop:
            return ExtrapolationMode.LOOP;
        }
      }
      function toLegacyWrapMode(extrapolationMode) {
        switch (extrapolationMode) {
          default:
          case ExtrapolationMode.LINEAR:
          case ExtrapolationMode.CLAMP:
            return WrapModeMask.Clamp;
          case ExtrapolationMode.PING_PONG:
            return WrapModeMask.PingPong;
          case ExtrapolationMode.LOOP:
            return WrapModeMask.Loop;
        }
      }
      function constructLegacyCurveAndConvert() {
        var curve = new RealCurve();
        curve.assignSorted([[0.0, {
          interpolationMode: RealInterpolationMode.CUBIC,
          value: 1.0
        }], [1.0, {
          interpolationMode: RealInterpolationMode.CUBIC,
          value: 1.0
        }]]);
        return curve;
      }

      var SplineMode;
      (function (SplineMode) {
        SplineMode[SplineMode["LINEAR"] = 0] = "LINEAR";
        SplineMode[SplineMode["BEZIER"] = 1] = "BEZIER";
        SplineMode[SplineMode["CATMULL_ROM"] = 2] = "CATMULL_ROM";
      })(SplineMode || (SplineMode = {}));
      var SPLINE_WHOLE_INDEX = 0xffffffff;
      var _v0 = new Vec3();
      var _v1 = new Vec3();
      var _v2 = new Vec3();
      var _v3$4 = new Vec3();
      var Spline = function () {
        function Spline(mode, knots) {
          if (mode === void 0) {
            mode = SplineMode.CATMULL_ROM;
          }
          if (knots === void 0) {
            knots = [];
          }
          this._type = void 0;
          this._mode = SplineMode.CATMULL_ROM;
          this._knots = [];
          this._type = enums.SHAPE_SPLINE;
          this._mode = mode;
          for (var i = 0; i < knots.length; i++) {
            this._knots[i] = new Vec3(knots[i]);
          }
        }
        Spline.create = function create(mode, knots) {
          if (knots === void 0) {
            knots = [];
          }
          return new Spline(mode, knots);
        };
        Spline.clone = function clone(s) {
          return new Spline(s.mode, s.knots);
        };
        Spline.copy = function copy(out, s) {
          out._mode = s.mode;
          out._knots.length = 0;
          var knots = s.knots;
          var length = knots.length;
          for (var i = 0; i < length; i++) {
            out._knots[i] = new Vec3(knots[i]);
          }
          return out;
        };
        var _proto = Spline.prototype;
        _proto.setModeAndKnots = function setModeAndKnots(mode, knots) {
          this._mode = mode;
          this._knots.length = 0;
          for (var i = 0; i < knots.length; i++) {
            this._knots[i] = new Vec3(knots[i]);
          }
        };
        _proto.clearKnots = function clearKnots() {
          this._knots.length = 0;
        };
        _proto.getKnotCount = function getKnotCount() {
          return this._knots.length;
        };
        _proto.addKnot = function addKnot(knot) {
          this._knots.push(new Vec3(knot));
        };
        _proto.insertKnot = function insertKnot(index, knot) {
          var item = new Vec3(knot);
          if (index >= this._knots.length) {
            this._knots.push(item);
            return;
          }
          this._knots.splice(index, 0, item);
        };
        _proto.removeKnot = function removeKnot(index) {
          assertIsTrue(index >= 0 && index < this._knots.length, 'Spline: invalid index');
          this._knots.splice(index, 1);
        };
        _proto.setKnot = function setKnot(index, knot) {
          assertIsTrue(index >= 0 && index < this._knots.length, 'Spline: invalid index');
          this._knots[index].set(knot);
        };
        _proto.getKnot = function getKnot(index) {
          assertIsTrue(index >= 0 && index < this._knots.length, 'Spline: invalid index');
          return this._knots[index];
        };
        _proto.getPoint = function getPoint(t, index) {
          if (index === void 0) {
            index = SPLINE_WHOLE_INDEX;
          }
          t = clamp$1(t, 0.0, 1.0);
          var segments = this.getSegments();
          if (segments === 0) {
            return new Vec3(0.0, 0.0, 0.0);
          }
          if (index === SPLINE_WHOLE_INDEX) {
            var deltaT = 1.0 / segments;
            index = Math.floor(t / deltaT);
            t = t % deltaT / deltaT;
          }
          if (index >= segments) {
            return new Vec3(this._knots[this._knots.length - 1]);
          }
          switch (this._mode) {
            case SplineMode.LINEAR:
              return Spline.calcLinear(this._knots[index], this._knots[index + 1], t);
            case SplineMode.BEZIER:
              return Spline.calcBezier(this._knots[index * 4], this._knots[index * 4 + 1], this._knots[index * 4 + 2], this._knots[index * 4 + 3], t);
            case SplineMode.CATMULL_ROM:
              {
                var v0 = index > 0 ? this._knots[index - 1] : this._knots[index];
                var v3 = index + 2 < this._knots.length ? this._knots[index + 2] : this._knots[index + 1];
                return Spline.calcCatmullRom(v0, this._knots[index], this._knots[index + 1], v3, t);
              }
            default:
              return new Vec3(0.0, 0.0, 0.0);
          }
        };
        _proto.getPoints = function getPoints(num, index) {
          if (index === void 0) {
            index = SPLINE_WHOLE_INDEX;
          }
          if (num === 0) {
            return [];
          }
          if (num === 1) {
            var point = this.getPoint(0.0, index);
            return [point];
          }
          var points = [];
          var deltaT = 1.0 / (num - 1.0);
          for (var i = 0; i < num; i++) {
            var t = i * deltaT;
            var _point = this.getPoint(t, index);
            points.push(_point);
          }
          return points;
        };
        _proto.getSegments = function getSegments() {
          var count = this._knots.length;
          switch (this._mode) {
            case SplineMode.LINEAR:
            case SplineMode.CATMULL_ROM:
              if (count < 2) {
                warnID(14300);
                return 0;
              }
              return count - 1;
            case SplineMode.BEZIER:
              if (count < 4 || count % 4 != 0) {
                warnID(14301);
                return 0;
              }
              return count / 4;
            default:
              assertIsTrue(false, 'Spline error: invalid mode');
          }
        };
        Spline.calcLinear = function calcLinear(v0, v1, t) {
          var result = new Vec3();
          Vec3.multiplyScalar(_v0, v0, 1.0 - t);
          Vec3.multiplyScalar(_v1, v1, t);
          Vec3.add(result, _v0, _v1);
          return result;
        };
        Spline.calcBezier = function calcBezier(v0, v1, v2, v3, t) {
          var result = new Vec3();
          var s = 1.0 - t;
          Vec3.multiplyScalar(_v0, v0, s * s * s);
          Vec3.multiplyScalar(_v1, v1, 3.0 * t * s * s);
          Vec3.multiplyScalar(_v2, v2, 3.0 * t * t * s);
          Vec3.multiplyScalar(_v3$4, v3, t * t * t);
          Vec3.add(_v0, _v0, _v1);
          Vec3.add(_v2, _v2, _v3$4);
          Vec3.add(result, _v0, _v2);
          return result;
        };
        Spline.calcCatmullRom = function calcCatmullRom(v0, v1, v2, v3, t) {
          var result = new Vec3();
          var t2 = t * t;
          var t3 = t2 * t;
          Vec3.multiplyScalar(_v0, v0, -0.5 * t3 + t2 - 0.5 * t);
          Vec3.multiplyScalar(_v1, v1, 1.5 * t3 - 2.5 * t2 + 1.0);
          Vec3.multiplyScalar(_v2, v2, -1.5 * t3 + 2.0 * t2 + 0.5 * t);
          Vec3.multiplyScalar(_v3$4, v3, 0.5 * t3 - 0.5 * t2);
          Vec3.add(_v0, _v0, _v1);
          Vec3.add(_v2, _v2, _v3$4);
          Vec3.add(result, _v0, _v2);
          return result;
        };
        _createClass(Spline, [{
          key: "type",
          get: function get() {
            return this._type;
          }
        }, {
          key: "mode",
          get: function get() {
            return this._mode;
          }
        }, {
          key: "knots",
          get: function get() {
            return this._knots;
          }
        }]);
        return Spline;
      }();

      var ERaycastMode;
      (function (ERaycastMode) {
        ERaycastMode[ERaycastMode["ALL"] = 0] = "ALL";
        ERaycastMode[ERaycastMode["CLOSEST"] = 1] = "CLOSEST";
        ERaycastMode[ERaycastMode["ANY"] = 2] = "ANY";
      })(ERaycastMode || (ERaycastMode = {}));

      var geometry = /*#__PURE__*/Object.freeze({
        __proto__: null,
        distance: distance,
        enums: enums,
        intersect: intersect,
        Line: Line,
        Plane: Plane,
        Ray: Ray,
        Triangle: Triangle,
        Sphere: Sphere,
        AABB: AABB,
        OBB: OBB,
        Capsule: Capsule,
        Frustum: Frustum,
        Keyframe: Keyframe,
        AnimationCurve: AnimationCurve,
        get WrapModeMask () { return WrapModeMask; },
        get SplineMode () { return SplineMode; },
        Spline: Spline,
        constructLegacyCurveAndConvert: constructLegacyCurveAndConvert,
        OptimizedKey: OptimizedKey,
        evalOptCurve: evalOptCurve,
        get ERaycastMode () { return ERaycastMode; }
      });
      exports('aC', geometry);

      var ScalableContainer = function () {
        function ScalableContainer() {
          this._poolHandle = -1;
          scalableContainerManager.addContainer(this);
        }
        var _proto = ScalableContainer.prototype;
        _proto.destroy = function destroy() {
          scalableContainerManager.removeContainer(this);
        };
        return ScalableContainer;
      }();
      var ScalableContainerManager = function () {
        function ScalableContainerManager() {
          this._pools = [];
          this._lastShrinkPassed = 0;
          this.shrinkTimeSpan = 5;
        }
        var _proto2 = ScalableContainerManager.prototype;
        _proto2.addContainer = function addContainer(pool) {
          if (pool._poolHandle !== -1) return;
          pool._poolHandle = this._pools.length;
          this._pools.push(pool);
        };
        _proto2.removeContainer = function removeContainer(pool) {
          if (pool._poolHandle === -1) return;
          this._pools[this._pools.length - 1]._poolHandle = pool._poolHandle;
          fastRemoveAt$2(this._pools, pool._poolHandle);
          pool._poolHandle = -1;
        };
        _proto2.tryShrink = function tryShrink() {
          for (var i = 0; i < this._pools.length; i++) {
            this._pools[i].tryShrink();
          }
        };
        _proto2.update = function update(dt) {
          this._lastShrinkPassed += dt;
          if (this._lastShrinkPassed > this.shrinkTimeSpan) {
            this.tryShrink();
            this._lastShrinkPassed -= this.shrinkTimeSpan;
          }
        };
        return ScalableContainerManager;
      }();
      var scalableContainerManager = new ScalableContainerManager();

      var Pool = exports('bp', function (_ScalableContainer) {
        _inheritsLoose(Pool, _ScalableContainer);
        function Pool(ctor, elementsPerBatch, dtor) {
          var _this;
          _this = _ScalableContainer.call(this) || this;
          _this._ctor = void 0;
          _this._elementsPerBatch = void 0;
          _this._nextAvail = void 0;
          _this._freePool = [];
          _this._dtor = void 0;
          _this._ctor = ctor;
          _this._dtor = dtor || null;
          _this._elementsPerBatch = Math.max(elementsPerBatch, 1);
          _this._nextAvail = _this._elementsPerBatch - 1;
          for (var i = 0; i < _this._elementsPerBatch; ++i) {
            _this._freePool.push(ctor());
          }
          return _this;
        }
        var _proto = Pool.prototype;
        _proto.alloc = function alloc() {
          if (this._nextAvail < 0) {
            this._freePool.length = this._elementsPerBatch;
            for (var i = 0; i < this._elementsPerBatch; i++) {
              this._freePool[i] = this._ctor();
            }
            this._nextAvail = this._elementsPerBatch - 1;
          }
          return this._freePool[this._nextAvail--];
        };
        _proto.free = function free(obj) {
          this._freePool[++this._nextAvail] = obj;
        };
        _proto.freeArray = function freeArray(objs) {
          this._freePool.length = this._nextAvail + 1;
          Array.prototype.push.apply(this._freePool, objs);
          this._nextAvail += objs.length;
        };
        _proto.tryShrink = function tryShrink() {
          if (this._nextAvail >> 1 > this._elementsPerBatch) {
            if (this._dtor) {
              for (var i = this._nextAvail >> 1; i <= this._nextAvail; i++) {
                this._dtor(this._freePool[i]);
              }
            }
            this._freePool.length = this._nextAvail >> 1;
            this._nextAvail = this._freePool.length - 1;
          }
        };
        _proto.destroy = function destroy() {
          var dtor = arguments.length > 0 ? arguments[0] : null;
          if (dtor) {
            warnID(14100);
          }
          var readDtor = dtor || this._dtor;
          if (readDtor) {
            for (var i = 0; i <= this._nextAvail; i++) {
              readDtor(this._freePool[i]);
            }
          }
          this._freePool.length = 0;
          this._nextAvail = -1;
          _ScalableContainer.prototype.destroy.call(this);
        };
        return Pool;
      }(ScalableContainer));

      var RecyclePool = exports('bq', function (_ScalableContainer) {
        _inheritsLoose(RecyclePool, _ScalableContainer);
        function RecyclePool(fn, size, dtor) {
          var _this;
          _this = _ScalableContainer.call(this) || this;
          _this._fn = void 0;
          _this._dtor = null;
          _this._count = 0;
          _this._data = void 0;
          _this._initSize = 0;
          _this._fn = fn;
          _this._dtor = dtor || null;
          _this._data = new Array(size);
          _this._initSize = size;
          for (var i = 0; i < size; ++i) {
            _this._data[i] = fn();
          }
          return _this;
        }
        var _proto = RecyclePool.prototype;
        _proto.reset = function reset() {
          this._count = 0;
        };
        _proto.resize = function resize(size) {
          if (size > this._data.length) {
            for (var i = this._data.length; i < size; ++i) {
              this._data[i] = this._fn();
            }
          }
        };
        _proto.add = function add() {
          if (this._count >= this._data.length) {
            this.resize(this._data.length << 1);
          }
          return this._data[this._count++];
        };
        _proto.destroy = function destroy() {
          if (this._dtor) {
            for (var i = 0; i < this._data.length; i++) {
              this._dtor(this._data[i]);
            }
          }
          this._data.length = 0;
          this._count = 0;
          _ScalableContainer.prototype.destroy.call(this);
        };
        _proto.tryShrink = function tryShrink() {
          if (this._data.length >> 2 > this._count) {
            var length = Math.max(this._initSize, this._data.length >> 1);
            if (this._dtor) {
              for (var i = length; i < this._data.length; i++) {
                this._dtor(this._data[i]);
              }
            }
            this._data.length = length;
          }
        };
        _proto.removeAt = function removeAt(idx) {
          if (idx >= this._count) {
            return;
          }
          var last = this._count - 1;
          var tmp = this._data[idx];
          this._data[idx] = this._data[last];
          this._data[last] = tmp;
          this._count -= 1;
        };
        _createClass(RecyclePool, [{
          key: "length",
          get: function get() {
            return this._count;
          }
        }, {
          key: "data",
          get: function get() {
            return this._data;
          }
        }]);
        return RecyclePool;
      }(ScalableContainer));

      var CachedArray = exports('br', function (_ScalableContainer) {
        _inheritsLoose(CachedArray, _ScalableContainer);
        function CachedArray(length, compareFn) {
          var _this;
          _this = _ScalableContainer.call(this) || this;
          _this.array = void 0;
          _this.length = 0;
          _this._compareFn = void 0;
          _this._initSize = 0;
          _this.array = new Array(length);
          _this._initSize = length;
          _this.length = 0;
          _this._compareFn = compareFn;
          return _this;
        }
        var _proto = CachedArray.prototype;
        _proto.push = function push(item) {
          this.array[this.length++] = item;
        };
        _proto.pop = function pop() {
          return this.array[--this.length];
        };
        _proto.get = function get(idx) {
          return this.array[idx];
        };
        _proto.clear = function clear() {
          this.length = 0;
        };
        _proto.destroy = function destroy() {
          this.length = 0;
          this.array.length = 0;
          _ScalableContainer.prototype.destroy.call(this);
        };
        _proto.tryShrink = function tryShrink() {
          if (this.array.length >> 2 > this.length) {
            this.array.length = Math.max(this._initSize, this.array.length >> 1);
          }
        };
        _proto.sort = function sort() {
          this.array.length = this.length;
          this.array.sort(this._compareFn);
        };
        _proto.concat = function concat(array) {
          for (var i = 0; i < array.length; ++i) {
            this.array[this.length++] = array[i];
          }
        };
        _proto.fastRemove = function fastRemove(idx) {
          if (idx >= this.length || idx < 0) {
            return;
          }
          var last = --this.length;
          this.array[idx] = this.array[last];
        };
        _proto.indexOf = function indexOf(val) {
          for (var i = 0, len = this.length; i < len; ++i) {
            if (this.array[i] === val) {
              return i;
            }
          }
          return -1;
        };
        return CachedArray;
      }(ScalableContainer));

      var index$2 = /*#__PURE__*/Object.freeze({
        __proto__: null,
        Pool: Pool,
        RecyclePool: RecyclePool,
        CachedArray: CachedArray
      });
      exports('aB', index$2);

      var fastRemoveAt$1 = fastRemoveAt$2;
      function empty() {}
      var CallbackInfo = function () {
        function CallbackInfo() {
          this.callback = empty;
          this.target = undefined;
          this.once = false;
        }
        var _proto = CallbackInfo.prototype;
        _proto.set = function set(callback, target, once) {
          this.callback = callback || empty;
          this.target = target;
          this.once = !!once;
        };
        _proto.reset = function reset() {
          this.target = undefined;
          this.callback = empty;
          this.once = false;
        };
        _proto.check = function check() {
          if (isCCObject(this.target) && !isValid(this.target, true)) {
            return false;
          } else {
            return true;
          }
        };
        return CallbackInfo;
      }();
      var callbackInfoPool = new Pool(function () {
        return new CallbackInfo();
      }, 32);
      var CallbackList = function () {
        function CallbackList() {
          this.callbackInfos = [];
          this.isInvoking = false;
          this.containCanceled = false;
        }
        var _proto2 = CallbackList.prototype;
        _proto2.removeByCallback = function removeByCallback(cb) {
          for (var i = 0; i < this.callbackInfos.length; ++i) {
            var info = this.callbackInfos[i];
            if (info && info.callback === cb) {
              info.reset();
              callbackInfoPool.free(info);
              fastRemoveAt$1(this.callbackInfos, i);
              --i;
            }
          }
        };
        _proto2.removeByTarget = function removeByTarget(target) {
          for (var i = 0; i < this.callbackInfos.length; ++i) {
            var info = this.callbackInfos[i];
            if (info && info.target === target) {
              info.reset();
              callbackInfoPool.free(info);
              fastRemoveAt$1(this.callbackInfos, i);
              --i;
            }
          }
        };
        _proto2.cancel = function cancel(index) {
          var info = this.callbackInfos[index];
          if (info) {
            info.reset();
            if (this.isInvoking) {
              this.callbackInfos[index] = null;
            } else {
              fastRemoveAt$1(this.callbackInfos, index);
            }
            callbackInfoPool.free(info);
          }
          this.containCanceled = true;
        };
        _proto2.cancelAll = function cancelAll() {
          for (var i = 0; i < this.callbackInfos.length; i++) {
            var info = this.callbackInfos[i];
            if (info) {
              info.reset();
              callbackInfoPool.free(info);
              this.callbackInfos[i] = null;
            }
          }
          this.containCanceled = true;
        };
        _proto2.purgeCanceled = function purgeCanceled() {
          for (var i = this.callbackInfos.length - 1; i >= 0; --i) {
            var info = this.callbackInfos[i];
            if (!info) {
              fastRemoveAt$1(this.callbackInfos, i);
            }
          }
          this.containCanceled = false;
        };
        _proto2.clear = function clear() {
          this.cancelAll();
          this.callbackInfos.length = 0;
          this.isInvoking = false;
          this.containCanceled = false;
        };
        return CallbackList;
      }();
      var MAX_SIZE$1 = 16;
      var callbackListPool = new Pool(function () {
        return new CallbackList();
      }, MAX_SIZE$1);
      var CallbacksInvoker = exports('cU', function () {
        function CallbacksInvoker() {
          this._callbackTable = createMap(true);
          this._offCallback = void 0;
        }
        var _proto3 = CallbacksInvoker.prototype;
        _proto3.on = function on(key, callback, target, once) {
          if (!this.hasEventListener(key, callback, target)) {
            var list = this._callbackTable[key];
            if (!list) {
              list = this._callbackTable[key] = callbackListPool.alloc();
            }
            var info = callbackInfoPool.alloc();
            info.set(callback, target, once);
            list.callbackInfos.push(info);
          }
          return callback;
        };
        _proto3.hasEventListener = function hasEventListener(key, callback, target) {
          var list = this._callbackTable && this._callbackTable[key];
          if (!list) {
            return false;
          }
          var infos = list.callbackInfos;
          if (!callback) {
            if (list.isInvoking) {
              for (var i = 0; i < infos.length; ++i) {
                if (infos[i]) {
                  return true;
                }
              }
              return false;
            } else {
              return infos.length > 0;
            }
          }
          for (var _i = 0; _i < infos.length; ++_i) {
            var info = infos[_i];
            if (info && info.check() && info.callback === callback && info.target === target) {
              return true;
            }
          }
          return false;
        };
        _proto3.removeAll = function removeAll(keyOrTarget) {
          var type = typeof keyOrTarget;
          if (type === 'string' || type === 'number') {
            var list = this._callbackTable && this._callbackTable[keyOrTarget];
            if (list) {
              if (list.isInvoking) {
                list.cancelAll();
              } else {
                list.clear();
                callbackListPool.free(list);
                delete this._callbackTable[keyOrTarget];
              }
            }
          } else if (keyOrTarget) {
            for (var key in this._callbackTable) {
              var _list = this._callbackTable[key];
              if (_list.isInvoking) {
                var infos = _list.callbackInfos;
                for (var i = 0; i < infos.length; ++i) {
                  var info = infos[i];
                  if (info && info.target === keyOrTarget) {
                    _list.cancel(i);
                  }
                }
              } else {
                _list.removeByTarget(keyOrTarget);
              }
            }
          }
        };
        _proto3.off = function off(key, callback, target) {
          var _this$_offCallback;
          var list = this._callbackTable && this._callbackTable[key];
          if (list) {
            var infos = list.callbackInfos;
            if (callback) {
              for (var i = 0; i < infos.length; ++i) {
                var info = infos[i];
                if (info && info.callback === callback && info.target === target) {
                  list.cancel(i);
                  break;
                }
              }
            } else {
              this.removeAll(key);
            }
          }
          (_this$_offCallback = this._offCallback) === null || _this$_offCallback === void 0 ? void 0 : _this$_offCallback.call(this);
        };
        _proto3.emit = function emit(key, arg0, arg1, arg2, arg3, arg4) {
          var list = this._callbackTable && this._callbackTable[key];
          if (list) {
            var rootInvoker = !list.isInvoking;
            list.isInvoking = true;
            var infos = list.callbackInfos;
            for (var i = 0, len = infos.length; i < len; ++i) {
              var info = infos[i];
              if (info) {
                var callback = info.callback;
                var target = info.target;
                if (info.once) {
                  this.off(key, callback, target);
                }
                if (!info.check()) {
                  this.off(key, callback, target);
                } else if (target) {
                  callback.call(target, arg0, arg1, arg2, arg3, arg4);
                } else {
                  callback(arg0, arg1, arg2, arg3, arg4);
                }
              }
            }
            if (rootInvoker) {
              list.isInvoking = false;
              if (list.containCanceled) {
                list.purgeCanceled();
              }
            }
          }
        };
        _proto3.clear = function clear() {
          for (var key in this._callbackTable) {
            var list = this._callbackTable[key];
            if (list) {
              list.clear();
              callbackListPool.free(list);
              delete this._callbackTable[key];
            }
          }
        };
        _proto3._registerOffCallback = function _registerOffCallback(cb) {
          this._offCallback = cb;
        };
        return CallbacksInvoker;
      }());

      function Eventify(base) {
        var Eventified = function (_ref) {
          _inheritsLoose(Eventified, _ref);
          function Eventified() {
            var _this;
            for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
              args[_key] = arguments[_key];
            }
            _this = _ref.call.apply(_ref, [this].concat(args)) || this;
            _this._callbackTable = createMap(true);
            return _this;
          }
          var _proto = Eventified.prototype;
          _proto.once = function once(type, callback, target) {
            return this.on(type, callback, target, true);
          };
          _proto.targetOff = function targetOff(typeOrTarget) {
            this.removeAll(typeOrTarget);
          };
          return Eventified;
        }(base);
        var callbacksInvokerPrototype = CallbacksInvoker.prototype;
        var propertyKeys = Object.getOwnPropertyNames(callbacksInvokerPrototype).concat(Object.getOwnPropertySymbols(callbacksInvokerPrototype));
        for (var iPropertyKey = 0; iPropertyKey < propertyKeys.length; ++iPropertyKey) {
          var propertyKey = propertyKeys[iPropertyKey];
          if (!(propertyKey in Eventified.prototype)) {
            var propertyDescriptor = Object.getOwnPropertyDescriptor(callbacksInvokerPrototype, propertyKey);
            if (propertyDescriptor) {
              Object.defineProperty(Eventified.prototype, propertyKey, propertyDescriptor);
            }
          }
        }
        return Eventified;
      }

      var Empty = function Empty() {};
      var EventTarget = exports('bX', Eventify(Empty));
      legacyCC.EventTarget = EventTarget;

      var AsyncDelegate = exports('bZ', function () {
        function AsyncDelegate() {
          this._delegates = [];
        }
        var _proto = AsyncDelegate.prototype;
        _proto.add = function add(callback) {
          if (!this._delegates.includes(callback)) {
            this._delegates.push(callback);
          }
        };
        _proto.hasListener = function hasListener(callback) {
          return this._delegates.includes(callback);
        };
        _proto.remove = function remove(callback) {
          fastRemove(this._delegates, callback);
        };
        _proto.dispatch = function dispatch() {
          var _arguments = arguments;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          return Promise.all(this._delegates.map(function (func) {
            return func.apply(void 0, _arguments);
          }).filter(Boolean));
        };
        return AsyncDelegate;
      }());

      var BrowserType;
      (function (BrowserType) {
        BrowserType["UNKNOWN"] = "unknown";
        BrowserType["WECHAT"] = "wechat";
        BrowserType["ANDROID"] = "androidbrowser";
        BrowserType["IE"] = "ie";
        BrowserType["EDGE"] = "edge";
        BrowserType["QQ"] = "qqbrowser";
        BrowserType["MOBILE_QQ"] = "mqqbrowser";
        BrowserType["UC"] = "ucbrowser";
        BrowserType["UCBS"] = "ucbs";
        BrowserType["BROWSER_360"] = "360browser";
        BrowserType["BAIDU_APP"] = "baiduboxapp";
        BrowserType["BAIDU"] = "baidubrowser";
        BrowserType["MAXTHON"] = "maxthon";
        BrowserType["OPERA"] = "opera";
        BrowserType["OUPENG"] = "oupeng";
        BrowserType["MIUI"] = "miuibrowser";
        BrowserType["FIREFOX"] = "firefox";
        BrowserType["SAFARI"] = "safari";
        BrowserType["CHROME"] = "chrome";
        BrowserType["LIEBAO"] = "liebao";
        BrowserType["QZONE"] = "qzone";
        BrowserType["SOUGOU"] = "sogou";
        BrowserType["HUAWEI"] = "huawei";
      })(BrowserType || (BrowserType = {}));

      var Language;
      (function (Language) {
        Language["UNKNOWN"] = "unknown";
        Language["ENGLISH"] = "en";
        Language["CHINESE"] = "zh";
        Language["FRENCH"] = "fr";
        Language["ITALIAN"] = "it";
        Language["GERMAN"] = "de";
        Language["SPANISH"] = "es";
        Language["DUTCH"] = "du";
        Language["RUSSIAN"] = "ru";
        Language["KOREAN"] = "ko";
        Language["JAPANESE"] = "ja";
        Language["HUNGARIAN"] = "hu";
        Language["PORTUGUESE"] = "pt";
        Language["ARABIC"] = "ar";
        Language["NORWEGIAN"] = "no";
        Language["POLISH"] = "pl";
        Language["TURKISH"] = "tr";
        Language["UKRAINIAN"] = "uk";
        Language["ROMANIAN"] = "ro";
        Language["BULGARIAN"] = "bg";
        Language["HINDI"] = "hi";
      })(Language || (Language = {}));

      var NetworkType;
      (function (NetworkType) {
        NetworkType[NetworkType["NONE"] = 0] = "NONE";
        NetworkType[NetworkType["LAN"] = 1] = "LAN";
        NetworkType[NetworkType["WWAN"] = 2] = "WWAN";
      })(NetworkType || (NetworkType = {}));

      var OS;
      (function (OS) {
        OS["UNKNOWN"] = "Unknown";
        OS["IOS"] = "iOS";
        OS["ANDROID"] = "Android";
        OS["WINDOWS"] = "Windows";
        OS["LINUX"] = "Linux";
        OS["OSX"] = "OS X";
        OS["OHOS"] = "OHOS";
        OS["OPENHARMONY"] = "OpenHarmony";
      })(OS || (OS = {}));

      var Platform;
      (function (Platform) {
        Platform["UNKNOWN"] = "UNKNOWN";
        Platform["EDITOR_PAGE"] = "EDITOR_PAGE";
        Platform["EDITOR_CORE"] = "EDITOR_CORE";
        Platform["MOBILE_BROWSER"] = "MOBILE_BROWSER";
        Platform["DESKTOP_BROWSER"] = "DESKTOP_BROWSER";
        Platform["WIN32"] = "WIN32";
        Platform["ANDROID"] = "ANDROID";
        Platform["IOS"] = "IOS";
        Platform["MACOS"] = "MACOS";
        Platform["OHOS"] = "OHOS";
        Platform["OPENHARMONY"] = "OPENHARMONY";
        Platform["WECHAT_GAME"] = "WECHAT_GAME";
        Platform["WECHAT_MINI_PROGRAM"] = "WECHAT_MINI_PROGRAM";
        Platform["BAIDU_MINI_GAME"] = "BAIDU_MINI_GAME";
        Platform["XIAOMI_QUICK_GAME"] = "XIAOMI_QUICK_GAME";
        Platform["ALIPAY_MINI_GAME"] = "ALIPAY_MINI_GAME";
        Platform["TAOBAO_CREATIVE_APP"] = "TAOBAO_CREATIVE_APP";
        Platform["TAOBAO_MINI_GAME"] = "TAOBAO_MINI_GAME";
        Platform["BYTEDANCE_MINI_GAME"] = "BYTEDANCE_MINI_GAME";
        Platform["OPPO_MINI_GAME"] = "OPPO_MINI_GAME";
        Platform["VIVO_MINI_GAME"] = "VIVO_MINI_GAME";
        Platform["HUAWEI_QUICK_GAME"] = "HUAWEI_QUICK_GAME";
        Platform["COCOSPLAY"] = "COCOSPLAY";
        Platform["LINKSURE_MINI_GAME"] = "LINKSURE_MINI_GAME";
        Platform["QTT_MINI_GAME"] = "QTT_MINI_GAME";
      })(Platform || (Platform = {}));

      var Feature$1;
      (function (Feature) {
        Feature["WEBP"] = "WEBP";
        Feature["IMAGE_BITMAP"] = "IMAGE_BITMAP";
        Feature["WEB_VIEW"] = "WEB_VIEW";
        Feature["VIDEO_PLAYER"] = "VIDEO_PLAYER";
        Feature["SAFE_AREA"] = "SAFE_AREA";
        Feature["HPE"] = "HPE";
        Feature["INPUT_TOUCH"] = "INPUT_TOUCH";
        Feature["EVENT_KEYBOARD"] = "EVENT_KEYBOARD";
        Feature["EVENT_MOUSE"] = "EVENT_MOUSE";
        Feature["EVENT_TOUCH"] = "EVENT_TOUCH";
        Feature["EVENT_ACCELEROMETER"] = "EVENT_ACCELEROMETER";
        Feature["EVENT_GAMEPAD"] = "EVENT_GAMEPAD";
        Feature["EVENT_HANDLE"] = "EVENT_HANDLE";
        Feature["EVENT_HMD"] = "EVENT_HMD";
        Feature["EVENT_HANDHELD"] = "EVENT_HANDHELD";
        Feature["WASM"] = "WASM";
      })(Feature$1 || (Feature$1 = {}));

      var SystemInfo = function (_EventTarget) {
        _inheritsLoose(SystemInfo, _EventTarget);
        function SystemInfo() {
          var _getBattery, _ref, _this$_featureMap;
          var _this;
          _this = _EventTarget.call(this) || this;
          _this.networkType = void 0;
          _this.isNative = void 0;
          _this.isBrowser = void 0;
          _this.isMobile = void 0;
          _this.isLittleEndian = void 0;
          _this.platform = void 0;
          _this.language = void 0;
          _this.nativeLanguage = void 0;
          _this.os = void 0;
          _this.osVersion = void 0;
          _this.osMainVersion = void 0;
          _this.browserType = void 0;
          _this.browserVersion = void 0;
          _this.isXR = void 0;
          _this._battery = void 0;
          _this._featureMap = void 0;
          _this._initPromise = void 0;
          var nav = window.navigator;
          var ua = nav.userAgent.toLowerCase();
          (_getBattery = (_ref = nav).getBattery) === null || _getBattery === void 0 ? void 0 : _getBattery.call(_ref).then(function (battery) {
            _this._battery = battery;
          });
          _this.networkType = NetworkType.LAN;
          _this.isNative = false;
          _this.isBrowser = true;
          {
            _this.isMobile = /mobile|android|iphone|ipad/.test(ua);
            _this.platform = _this.isMobile ? Platform.MOBILE_BROWSER : Platform.DESKTOP_BROWSER;
          }
          _this.isLittleEndian = function () {
            var buffer = new ArrayBuffer(2);
            new DataView(buffer).setInt16(0, 256, true);
            return new Int16Array(buffer)[0] === 256;
          }();
          var currLanguage = nav.language;
          _this.nativeLanguage = currLanguage.toLowerCase();
          currLanguage = currLanguage || nav.browserLanguage;
          currLanguage = currLanguage ? currLanguage.split('-')[0] : Language.ENGLISH;
          _this.language = currLanguage;
          var isAndroid = false;
          var iOS = false;
          var osVersion = '';
          var osMajorVersion = 0;
          var uaResult = /android\s*(\d+(?:\.\d+)*)/i.exec(ua) || /android\s*(\d+(?:\.\d+)*)/i.exec(nav.platform);
          if (uaResult) {
            isAndroid = true;
            osVersion = uaResult[1] || '';
            osMajorVersion = parseInt(osVersion) || 0;
          }
          uaResult = /(iPad|iPhone|iPod).*OS ((\d+_?){2,3})/i.exec(ua);
          if (uaResult) {
            iOS = true;
            osVersion = uaResult[2] || '';
            osMajorVersion = parseInt(osVersion) || 0;
          } else if (/(iPhone|iPad|iPod)/.exec(nav.platform) || nav.platform === 'MacIntel' && nav.maxTouchPoints && nav.maxTouchPoints > 1) {
            iOS = true;
            osVersion = '';
            osMajorVersion = 0;
          }
          var osName = OS.UNKNOWN;
          if (nav.appVersion.indexOf('Win') !== -1) {
            osName = OS.WINDOWS;
          } else if (iOS) {
            osName = OS.IOS;
          } else if (nav.appVersion.indexOf('Mac') !== -1) {
            osName = OS.OSX;
          } else if (nav.appVersion.indexOf('X11') !== -1 && nav.appVersion.indexOf('Linux') === -1) {
            osName = OS.LINUX;
          } else if (isAndroid) {
            osName = OS.ANDROID;
          } else if (nav.appVersion.indexOf('Linux') !== -1 || ua.indexOf('ubuntu') !== -1) {
            osName = OS.LINUX;
          }
          _this.os = osName;
          _this.osVersion = osVersion;
          _this.osMainVersion = osMajorVersion;
          _this.browserType = BrowserType.UNKNOWN;
          var typeReg0 = /wechat|weixin|micromessenger/i;
          var typeReg1 = /mqqbrowser|micromessenger|qqbrowser|sogou|qzone|liebao|maxthon|ucbs|360 aphone|360browser|baiduboxapp|baidubrowser|maxthon|mxbrowser|miuibrowser/i;
          var typeReg2 = /qq|qqbrowser|ucbrowser|ubrowser|edge|HuaweiBrowser/i;
          var typeReg3 = /chrome|safari|firefox|trident|opera|opr\/|oupeng/i;
          var browserTypes = typeReg0.exec(ua) || typeReg1.exec(ua) || typeReg2.exec(ua) || typeReg3.exec(ua);
          var browserType = browserTypes ? browserTypes[0].toLowerCase() : OS.UNKNOWN;
          if (browserType === 'safari' && isAndroid) {
            browserType = BrowserType.ANDROID;
          } else if (browserType === 'qq' && /android.*applewebkit/i.test(ua)) {
            browserType = BrowserType.ANDROID;
          }
          var typeMap = {
            micromessenger: BrowserType.WECHAT,
            wechat: BrowserType.WECHAT,
            weixin: BrowserType.WECHAT,
            trident: BrowserType.IE,
            edge: BrowserType.EDGE,
            '360 aphone': BrowserType.BROWSER_360,
            mxbrowser: BrowserType.MAXTHON,
            'opr/': BrowserType.OPERA,
            ubrowser: BrowserType.UC,
            huaweibrowser: BrowserType.HUAWEI
          };
          _this.browserType = typeMap[browserType] || browserType;
          _this.browserVersion = '';
          var versionReg1 = /(mqqbrowser|micromessenger|qqbrowser|sogou|qzone|liebao|maxthon|uc|ucbs|360 aphone|360|baiduboxapp|baidu|maxthon|mxbrowser|miui(?:.hybrid)?)(mobile)?(browser)?\/?([\d.]+)/i;
          var versionReg2 = /(qq|chrome|safari|firefox|trident|opera|opr\/|oupeng)(mobile)?(browser)?\/?([\d.]+)/i;
          var tmp = versionReg1.exec(ua);
          if (!tmp) {
            tmp = versionReg2.exec(ua);
          }
          _this.browserVersion = tmp ? tmp[4] : '';
          _this.isXR = false;
          var _tmpCanvas1 = document.createElement('canvas');
          !!_tmpCanvas1.getContext('2d');
          var supportWebp;
          try {
            supportWebp = TEST ? false : _tmpCanvas1.toDataURL('image/webp').startsWith('data:image/webp');
          } catch (e) {
            supportWebp = false;
          }
          if (_this.browserType === BrowserType.SAFARI) {
            var _exec;
            var result = (_exec = / version\/(\d+)/.exec(ua)) === null || _exec === void 0 ? void 0 : _exec[1];
            if (typeof result === 'string') {
              if (Number.parseInt(result) >= 14) {
                supportWebp = true;
              }
            }
          }
          var supportTouch = document.documentElement.ontouchstart !== undefined || document.ontouchstart !== undefined || EDITOR;
          var supportMouse = document.documentElement.onmouseup !== undefined || EDITOR;
          var supportXR = typeof navigator.xr !== 'undefined';
          var supportWasm = function () {
            var isSafari_15_4 = (_this.os === OS.IOS || _this.os === OS.OSX) && /(OS 15_4)|(Version\/15.4)/.test(window.navigator.userAgent);
            if (isSafari_15_4) {
              return false;
            }
            try {
              if (typeof WebAssembly === 'object' && typeof WebAssembly.instantiate === 'function') {
                var module = new WebAssembly.Module(new Uint8Array([0x0, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00]));
                if (module instanceof WebAssembly.Module) {
                  return new WebAssembly.Instance(module) instanceof WebAssembly.Instance;
                }
              }
            } catch (e) {
              return false;
            }
            return false;
          }();
          _this._featureMap = (_this$_featureMap = {}, _this$_featureMap[Feature$1.WEBP] = supportWebp, _this$_featureMap[Feature$1.IMAGE_BITMAP] = false, _this$_featureMap[Feature$1.WEB_VIEW] = true, _this$_featureMap[Feature$1.VIDEO_PLAYER] = true, _this$_featureMap[Feature$1.SAFE_AREA] = false, _this$_featureMap[Feature$1.HPE] = false, _this$_featureMap[Feature$1.INPUT_TOUCH] = supportTouch, _this$_featureMap[Feature$1.EVENT_KEYBOARD] = document.documentElement.onkeyup !== undefined || EDITOR, _this$_featureMap[Feature$1.EVENT_MOUSE] = supportMouse, _this$_featureMap[Feature$1.EVENT_TOUCH] = supportTouch || supportMouse, _this$_featureMap[Feature$1.EVENT_ACCELEROMETER] = window.DeviceMotionEvent !== undefined || window.DeviceOrientationEvent !== undefined, _this$_featureMap[Feature$1.EVENT_GAMEPAD] = navigator.getGamepads !== undefined || navigator.webkitGetGamepads !== undefined || supportXR, _this$_featureMap[Feature$1.EVENT_HANDLE] = PREVIEW, _this$_featureMap[Feature$1.EVENT_HMD] = supportXR, _this$_featureMap[Feature$1.EVENT_HANDHELD] = supportXR, _this$_featureMap[Feature$1.WASM] = supportWasm, _this$_featureMap);
          _this._initPromise = [];
          _this._initPromise.push(_this._supportsImageBitmapPromise());
          _this._registerEvent();
          return _this;
        }
        var _proto = SystemInfo.prototype;
        _proto._supportsImageBitmapPromise = function _supportsImageBitmapPromise() {
          var _this2 = this;
          if (typeof createImageBitmap !== 'undefined' && typeof Blob !== 'undefined') {
            var canvas = document.createElement('canvas');
            canvas.width = canvas.height = 2;
            var promise = createImageBitmap(canvas, {});
            if (promise instanceof Promise) {
              return promise.then(function (imageBitmap) {
                _this2._setFeature(Feature$1.IMAGE_BITMAP, true);
                imageBitmap === null || imageBitmap === void 0 ? void 0 : imageBitmap.close();
              });
            } else {
              console.warn('The return value of createImageBitmap is not Promise.');
            }
          }
          return Promise.resolve();
        };
        _proto._registerEvent = function _registerEvent() {
          var _this3 = this;
          var hiddenPropName;
          if (typeof document.hidden !== 'undefined') {
            hiddenPropName = 'hidden';
          } else if (typeof document.mozHidden !== 'undefined') {
            hiddenPropName = 'mozHidden';
          } else if (typeof document.msHidden !== 'undefined') {
            hiddenPropName = 'msHidden';
          } else if (typeof document.webkitHidden !== 'undefined') {
            hiddenPropName = 'webkitHidden';
          } else {
            hiddenPropName = 'hidden';
          }
          var hidden = false;
          var onHidden = function onHidden() {
            if (!hidden) {
              hidden = true;
              _this3.emit('hide');
            }
          };
          var onShown = function onShown(arg0, arg1, arg2, arg3, arg4) {
            if (hidden) {
              hidden = false;
              _this3.emit('show', arg0, arg1, arg2, arg3, arg4);
            }
          };
          if (hiddenPropName) {
            var changeList = ['visibilitychange', 'mozvisibilitychange', 'msvisibilitychange', 'webkitvisibilitychange', 'qbrowserVisibilityChange'];
            for (var i = 0; i < changeList.length; i++) {
              document.addEventListener(changeList[i], function (event) {
                var visible = document[hiddenPropName];
                visible = visible || event.hidden;
                if (visible) {
                  onHidden();
                } else {
                  onShown();
                }
              });
            }
          } else {
            window.addEventListener('blur', onHidden);
            window.addEventListener('focus', onShown);
          }
          if (window.navigator.userAgent.indexOf('MicroMessenger') > -1) {
            window.onfocus = onShown;
          }
          if ('onpageshow' in window && 'onpagehide' in window) {
            window.addEventListener('pagehide', onHidden);
            window.addEventListener('pageshow', onShown);
            document.addEventListener('pagehide', onHidden);
            document.addEventListener('pageshow', onShown);
          }
        };
        _proto._setFeature = function _setFeature(feature, value) {
          return this._featureMap[feature] = value;
        };
        _proto.init = function init() {
          return Promise.all(this._initPromise);
        };
        _proto.hasFeature = function hasFeature(feature) {
          return this._featureMap[feature];
        };
        _proto.getBatteryLevel = function getBatteryLevel() {
          if (this._battery) {
            return this._battery.level;
          } else {
            {
              console.warn('getBatteryLevel is not supported');
            }
            return 1;
          }
        };
        _proto.triggerGC = function triggerGC() {
          {
            console.warn('triggerGC is not supported.');
          }
        };
        _proto.openURL = function openURL(url) {
          window.open(url);
        };
        _proto.now = function now() {
          if (Date.now) {
            return Date.now();
          }
          return +new Date();
        };
        _proto.restartJSVM = function restartJSVM() {
          {
            console.warn('restartJSVM is not supported.');
          }
        };
        _proto.exit = function exit() {
          window.close();
        };
        _proto.close = function close() {
          this.emit('close');
        };
        return SystemInfo;
      }(EventTarget);
      var systemInfo = new SystemInfo();

      var EXTNAME_RE = /(\.[^\.\/\?\\]*)(\?.*)?$/;
      var DIRNAME_RE = /((.*)(\/|\\|\\\\))?(.*?\..*$)?/;
      var NORMALIZE_RE = /[^\.\/]+\/\.\.\//;
      function join() {
        var result = '';
        for (var _len = arguments.length, segments = new Array(_len), _key = 0; _key < _len; _key++) {
          segments[_key] = arguments[_key];
        }
        for (var _i = 0, _segments = segments; _i < _segments.length; _i++) {
          var segment = _segments[_i];
          result = (result + (result === '' ? '' : '/') + segment).replace(/(\/|\\\\)$/, '');
        }
        return result;
      }
      function extname(path) {
        var temp = EXTNAME_RE.exec(path);
        return temp ? temp[1] : '';
      }
      function mainFileName(fileName) {
        if (fileName) {
          var idx = fileName.lastIndexOf('.');
          if (idx !== -1) {
            return fileName.substring(0, idx);
          }
        }
        return fileName;
      }
      function basename(path, extName) {
        var index = path.indexOf('?');
        if (index > 0) {
          path = path.substring(0, index);
        }
        var reg = /(\/|\\)([^\/\\]+)$/g;
        var result = reg.exec(path.replace(/(\/|\\)$/, ''));
        if (!result) {
          return path;
        }
        var baseName = result[2];
        if (extName && path.substring(path.length - extName.length).toLowerCase() === extName.toLowerCase()) {
          return baseName.substring(0, baseName.length - extName.length);
        }
        return baseName;
      }
      function dirname(path) {
        var temp = DIRNAME_RE.exec(path);
        return temp ? temp[2] : '';
      }
      function changeExtname(path, extName) {
        extName = extName || '';
        var index = path.indexOf('?');
        var tempStr = '';
        if (index > 0) {
          tempStr = path.substring(index);
          path = path.substring(0, index);
        }
        index = path.lastIndexOf('.');
        if (index < 0) {
          return path + extName + tempStr;
        }
        return path.substring(0, index) + extName + tempStr;
      }
      function changeBasename(path, newBaseName, keepExt) {
        if (newBaseName.indexOf('.') === 0) {
          return changeExtname(path, newBaseName);
        }
        var index = path.indexOf('?');
        var tempStr = '';
        var ext = keepExt ? extname(path) : '';
        if (index > 0) {
          tempStr = path.substring(index);
          path = path.substring(0, index);
        }
        index = path.lastIndexOf('/');
        index = index <= 0 ? 0 : index + 1;
        return path.substring(0, index) + newBaseName + ext + tempStr;
      }
      function _normalize(url) {
        var oldUrl = url = String(url);
        do {
          oldUrl = url;
          url = url.replace(NORMALIZE_RE, '');
        } while (oldUrl.length !== url.length);
        return url;
      }
      function stripSep(path) {
        return path.replace(/[\/\\]$/, '');
      }
      function getSeperator() {
        return systemInfo.os === OS.WINDOWS ? '\\' : '/';
      }

      var path = /*#__PURE__*/Object.freeze({
        __proto__: null,
        join: join,
        extname: extname,
        mainFileName: mainFileName,
        basename: basename,
        dirname: dirname,
        changeExtname: changeExtname,
        changeBasename: changeBasename,
        _normalize: _normalize,
        stripSep: stripSep,
        getSeperator: getSeperator
      });
      exports('by', path);

      var defaultLogTimes = 10;
      function setDefaultLogTimes(times) {
        if (times > 0) {
          defaultLogTimes = times;
        }
      }
      var replaceProperty; exports('bA', replaceProperty);
      var removeProperty; exports('bB', removeProperty);
      var markAsWarning; exports('bC', markAsWarning);
      var replacePropertyLog;
      var markAsWarningLog;
      var removePropertyLog;
      var messageID = 0;
      var messageMap = new Map();
      replacePropertyLog = function replacePropertyLog(n, dp, n2, newp, f, id, s) {
        var item = messageMap.get(id);
        if (item && item.logTimes > item.count) {
          f("'%s' is deprecated, please use '%s' instead. " + s, n + "." + dp, n2 + "." + newp);
          item.count++;
        }
      };
      exports('bA', replaceProperty = function replaceProperty(owner, ownerName, properties) {
        if (owner == null) return;
        properties.forEach(function (item) {
          var id = messageID++;
          messageMap.set(id, {
            id: id,
            count: 0,
            logTimes: item.logTimes !== undefined ? item.logTimes : defaultLogTimes
          });
          var target = item.target != null ? item.target : owner;
          var newName = item.newName != null ? item.newName : item.name;
          var targetName = item.targetName != null ? item.targetName : ownerName;
          var sameTarget = target === owner;
          var suggest = item.suggest ? "(" + item.suggest + ")" : '';
          if (item.customFunction != null) {
            owner[item.name] = function () {
              var _ref;
              replacePropertyLog(ownerName, item.name, targetName, newName, warn, id, suggest);
              return (_ref = item.customFunction).call.apply(_ref, [this].concat(Array.prototype.slice.call(arguments)));
            };
          } else if (item.customSetter != null || item.customGetter != null) {
            var hasSetter = item.customSetter != null;
            var hasGetter = item.customGetter != null;
            if (hasSetter && hasGetter) {
              Object.defineProperty(owner, item.name, {
                get: function get() {
                  replacePropertyLog(ownerName, item.name, targetName, newName, warn, id, suggest);
                  return item.customGetter.call(this);
                },
                set: function set(v) {
                  replacePropertyLog(ownerName, item.name, targetName, newName, warn, id, suggest);
                  item.customSetter.call(this, v);
                },
                enumerable: false
              });
            } else if (hasSetter) {
              Object.defineProperty(owner, item.name, {
                set: function set(v) {
                  replacePropertyLog(ownerName, item.name, targetName, newName, warn, id, suggest);
                  item.customSetter.call(this, v);
                },
                enumerable: false
              });
            } else if (hasGetter) {
              Object.defineProperty(owner, item.name, {
                get: function get() {
                  replacePropertyLog(ownerName, item.name, targetName, newName, warn, id, suggest);
                  return item.customGetter.call(this);
                },
                enumerable: false
              });
            }
          } else {
            Object.defineProperty(owner, item.name, {
              get: function get() {
                replacePropertyLog(ownerName, item.name, targetName, newName, warn, id, suggest);
                return sameTarget ? this[newName] : target[newName];
              },
              set: function set(v) {
                replacePropertyLog(ownerName, item.name, targetName, newName, warn, id, suggest);
                if (sameTarget) {
                  this[newName] = v;
                } else {
                  target[newName] = v;
                }
              },
              enumerable: false
            });
          }
        });
      });
      removePropertyLog = function removePropertyLog(n, dp, f, id, s) {
        var item = messageMap.get(id);
        if (item && item.logTimes > item.count) {
          f("'%s' has been removed. " + s, n + "." + dp);
          item.count++;
        }
      };
      exports('bB', removeProperty = function removeProperty(owner, ownerName, properties) {
        if (owner == null) return;
        properties.forEach(function (item) {
          var id = messageID++;
          messageMap.set(id, {
            id: id,
            count: 0,
            logTimes: item.logTimes !== undefined ? item.logTimes : defaultLogTimes
          });
          var suggest = item.suggest ? "(" + item.suggest + ")" : '';
          Object.defineProperty(owner, item.name, {
            get: function get() {
              return removePropertyLog(ownerName, item.name, error, id, suggest);
            },
            set: function set() {
              removePropertyLog(ownerName, item.name, error, id, suggest);
            },
            enumerable: false
          });
        });
      });
      markAsWarningLog = function markAsWarningLog(n, dp, f, id, s) {
        var item = messageMap.get(id);
        if (item && item.logTimes > item.count) {
          f("'%s' is deprecated. " + s, n + "." + dp);
          item.count++;
        }
      };
      exports('bC', markAsWarning = function markAsWarning(owner, ownerName, properties) {
        if (owner == null) return;
        var _defaultGetSet = function _defaultGetSet(d, n, dp, f, id, s) {
          if (d.get) {
            var oldGet = d.get;
            d.get = function () {
              markAsWarningLog(n, dp, f, id, s);
              return oldGet.call(this);
            };
          }
          if (d.set) {
            var oldSet = d.set;
            d.set = function (v) {
              markAsWarningLog(n, dp, f, id, s);
              oldSet.call(this, v);
            };
          }
          Object.defineProperty(owner, dp, d);
        };
        properties.forEach(function (item) {
          var deprecatedProp = item.name;
          var descriptor = Object.getOwnPropertyDescriptor(owner, deprecatedProp);
          if (!descriptor || !descriptor.configurable) {
            return;
          }
          var id = messageID++;
          messageMap.set(id, {
            id: id,
            count: 0,
            logTimes: item.logTimes !== undefined ? item.logTimes : defaultLogTimes
          });
          var suggest = item.suggest ? "(" + item.suggest + ")" : '';
          if (typeof descriptor.value !== 'undefined') {
            if (typeof descriptor.value === 'function') {
              var oldValue = descriptor.value;
              owner[deprecatedProp] = function () {
                markAsWarningLog(ownerName, deprecatedProp, warn, id, suggest);
                return oldValue.call.apply(oldValue, [this].concat(Array.prototype.slice.call(arguments)));
              };
            } else {
              var _oldValue = descriptor.value;
              Object.defineProperty(owner, deprecatedProp, {
                configurable: true,
                get: function get() {
                  markAsWarningLog(ownerName, deprecatedProp, warn, id, suggest);
                  return _oldValue;
                }
              });
              if (descriptor.writable) {
                Object.defineProperty(owner, deprecatedProp, {
                  set: function set(value) {
                    markAsWarningLog(ownerName, deprecatedProp, warn, id, suggest);
                    _oldValue = value;
                  }
                });
              }
            }
          } else {
            _defaultGetSet(descriptor, ownerName, deprecatedProp, warn, id, suggest);
          }
          Object.defineProperty(owner, deprecatedProp, {
            enumerable: false
          });
        });
      });
      var topLevelDeprecateList = {};
      function deprecateModuleExportedName(deprecateList) {
        for (var deprecateName in deprecateList) {
          var deprecateInfo = deprecateList[deprecateName];
          topLevelDeprecateList[deprecateName] = deprecateInfo;
        }
      }
      function _checkObsoleteByName(checkName) {
        var deprecateInfo = topLevelDeprecateList[checkName];
        if (!deprecateInfo) {
          return;
        }
        var newName = deprecateInfo.newName,
          since = deprecateInfo.since,
          removed = deprecateInfo.removed;
        if (removed) {
          if (newName) {
            errorID(16003, checkName, since, newName);
          } else {
            errorID(16002, checkName, since);
          }
        } else if (newName) {
          warnID(16001, checkName, since, newName);
        } else {
          warnID(16000, checkName, since);
        }
      }
      function __checkObsolete__(checkList) {
        for (var _iterator = _createForOfIteratorHelperLoose(checkList), _step; !(_step = _iterator()).done;) {
          var checkName = _step.value;
          _checkObsoleteByName(checkName);
        }
      }
      var _cachedProxy;
      function __checkObsoleteInNamespace__(ccNamespace) {
        if (!_cachedProxy) {
          if (typeof Proxy === 'undefined') {
            _cachedProxy = {};
          } else {
            _cachedProxy = new Proxy(ccNamespace, {
              get: function get(target, name, receiver) {
                _checkObsoleteByName(name);
                return Reflect.get(target, name, receiver);
              }
            });
          }
        }
        return _cachedProxy;
      }

      var _vec3$1 = new Vec3();
      function WorldNode3DToLocalNodeUI(mainCamera, wpos, uiNode, out) {
        if (!out) {
          out = new Vec3();
        }
        mainCamera.convertToUINode(wpos, uiNode, out);
        var pos = uiNode.position;
        out.add(pos);
        return out;
      }
      function WorldNode3DToWorldNodeUI(mainCamera, wpos, out) {
        if (!out) {
          out = new Vec3();
        }
        mainCamera.worldToScreen(wpos, out);
        out.x /= legacyCC.view.getScaleX();
        out.y /= legacyCC.view.getScaleY();
        return out;
      }
      var convertUtils = exports('bI', {
        WorldNode3DToLocalNodeUI: WorldNode3DToLocalNodeUI,
        WorldNode3DToWorldNodeUI: WorldNode3DToWorldNodeUI
      });
      legacyCC.pipelineUtils = convertUtils;
      replaceProperty(legacyCC.pipelineUtils, 'cc.pipelineUtils', [{
        name: 'WorldNode3DToLocalNodeUI',
        newName: 'convertToUINode',
        targetName: 'cc.Camera.prototype',
        customFunction: function customFunction() {
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          var camera = args[0];
          var out = args[3] || _vec3$1;
          camera.convertToUINode(args[1], args[2], out);
          out.add(args[2].position);
          return args[3] || out.clone();
        }
      }]);

      var _PORTRAIT = 1;
      var _PORTRAIT_UPSIDE_DOWN = _PORTRAIT << 1;
      var _LEFT = _PORTRAIT << 2;
      var _RIGHT = _PORTRAIT << 3;
      var _LANDSCAPE = _LEFT | _RIGHT;
      var _AUTO = _PORTRAIT | _LANDSCAPE;
      var Orientation;
      (function (Orientation) {
        Orientation[Orientation["PORTRAIT"] = _PORTRAIT] = "PORTRAIT";
        Orientation[Orientation["PORTRAIT_UPSIDE_DOWN"] = _PORTRAIT_UPSIDE_DOWN] = "PORTRAIT_UPSIDE_DOWN";
        Orientation[Orientation["LANDSCAPE_LEFT"] = _LEFT] = "LANDSCAPE_LEFT";
        Orientation[Orientation["LANDSCAPE_RIGHT"] = _RIGHT] = "LANDSCAPE_RIGHT";
        Orientation[Orientation["LANDSCAPE"] = _LANDSCAPE] = "LANDSCAPE";
        Orientation[Orientation["AUTO"] = _AUTO] = "AUTO";
      })(Orientation || (Orientation = {}));

      var EVENT_TIMEOUT = 200;
      var orientationMap$2 = {
        auto: Orientation.AUTO,
        landscape: Orientation.LANDSCAPE,
        portrait: Orientation.PORTRAIT
      };
      var WindowType;
      (function (WindowType) {
        WindowType[WindowType["Unknown"] = 0] = "Unknown";
        WindowType[WindowType["SubFrame"] = 1] = "SubFrame";
        WindowType[WindowType["BrowserWindow"] = 2] = "BrowserWindow";
        WindowType[WindowType["Fullscreen"] = 3] = "Fullscreen";
      })(WindowType || (WindowType = {}));
      var ScreenAdapter = function (_EventTarget) {
        _inheritsLoose(ScreenAdapter, _EventTarget);
        function ScreenAdapter() {
          var _this;
          _this = _EventTarget.call(this) || this;
          _this.isFrameRotated = false;
          _this.handleResizeEvent = true;
          _this._gameFrame = void 0;
          _this._gameContainer = void 0;
          _this._gameCanvas = void 0;
          _this._isProportionalToFrame = false;
          _this._cachedFrameStyle = {
            width: '0px',
            height: '0px'
          };
          _this._cachedContainerStyle = {
            width: '0px',
            height: '0px'
          };
          _this._cbToUpdateFrameBuffer = void 0;
          _this._supportFullScreen = false;
          _this._touchEventName = void 0;
          _this._onFullscreenChange = void 0;
          _this._onFullscreenError = void 0;
          _this._orientationChangeTimeoutId = -1;
          _this._cachedFrameSize = new Size$1(0, 0);
          _this._exactFitScreen = false;
          _this._isHeadlessMode = false;
          _this._fn = {};
          _this._fnGroup = [['requestFullscreen', 'exitFullscreen', 'fullscreenchange', 'fullscreenEnabled', 'fullscreenElement', 'fullscreenerror'], ['requestFullScreen', 'exitFullScreen', 'fullScreenchange', 'fullScreenEnabled', 'fullScreenElement', 'fullscreenerror'], ['webkitRequestFullScreen', 'webkitCancelFullScreen', 'webkitfullscreenchange', 'webkitIsFullScreen', 'webkitCurrentFullScreenElement', 'webkitfullscreenerror'], ['mozRequestFullScreen', 'mozCancelFullScreen', 'mozfullscreenchange', 'mozFullScreen', 'mozFullScreenElement', 'mozfullscreenerror'], ['msRequestFullscreen', 'msExitFullscreen', 'MSFullscreenChange', 'msFullscreenEnabled', 'msFullscreenElement', 'msfullscreenerror']];
          _this._resolutionScale = 1;
          _this._orientation = Orientation.AUTO;
          _this._gameFrame = document.getElementById('GameDiv');
          _this._gameContainer = document.getElementById('Cocos3dGameContainer');
          _this._gameCanvas = document.getElementById('GameCanvas');
          {
            if (!_this._gameFrame) {
              var _this$_gameCanvas, _this$_gameCanvas$par;
              _this._gameFrame = document.createElement('div');
              _this._gameFrame.setAttribute('id', 'GameDiv');
              (_this$_gameCanvas = _this._gameCanvas) === null || _this$_gameCanvas === void 0 ? void 0 : (_this$_gameCanvas$par = _this$_gameCanvas.parentNode) === null || _this$_gameCanvas$par === void 0 ? void 0 : _this$_gameCanvas$par.insertBefore(_this._gameFrame, _this._gameCanvas);
              _this._gameFrame.appendChild(_this._gameCanvas);
            }
            if (!_this._gameContainer) {
              var _this$_gameCanvas2, _this$_gameCanvas2$pa;
              _this._gameContainer = document.createElement('div');
              _this._gameContainer.setAttribute('id', 'Cocos3dGameContainer');
              (_this$_gameCanvas2 = _this._gameCanvas) === null || _this$_gameCanvas2 === void 0 ? void 0 : (_this$_gameCanvas2$pa = _this$_gameCanvas2.parentNode) === null || _this$_gameCanvas2$pa === void 0 ? void 0 : _this$_gameCanvas2$pa.insertBefore(_this._gameContainer, _this._gameCanvas);
              _this._gameContainer.appendChild(_this._gameCanvas);
            }
          }
          var fnList;
          var fnGroup = _this._fnGroup;
          for (var i = 0; i < fnGroup.length; i++) {
            fnList = fnGroup[i];
            if (typeof document[fnList[1]] !== 'undefined') {
              for (var _i = 0; _i < fnList.length; _i++) {
                _this._fn[fnGroup[0][_i]] = fnList[_i];
              }
              break;
            }
          }
          _this._supportFullScreen = _this._fn.requestFullscreen !== undefined;
          _this._touchEventName = 'ontouchstart' in window ? 'touchend' : 'mousedown';
          _this._registerEvent();
          return _this;
        }
        var _proto = ScreenAdapter.prototype;
        _proto.init = function init(options, cbToRebuildFrameBuffer) {
          this._cbToUpdateFrameBuffer = cbToRebuildFrameBuffer;
          this.orientation = orientationMap$2[options.configOrientation];
          this._exactFitScreen = options.exactFitScreen;
          this._isHeadlessMode = options.isHeadlessMode;
          this._resizeFrame();
        };
        _proto.requestFullScreen = function requestFullScreen() {
          var _this2 = this;
          return new Promise(function (resolve, reject) {
            if (_this2.isFullScreen) {
              resolve();
              return;
            }
            _this2._cachedFrameSize = _this2.windowSize;
            _this2._doRequestFullScreen().then(function () {
              resolve();
            })["catch"](function () {
              var fullscreenTarget = _this2._getFullscreenTarget();
              if (!fullscreenTarget) {
                reject(new Error('Cannot access fullscreen target'));
                return;
              }
              fullscreenTarget.addEventListener(_this2._touchEventName, function () {
                _this2._doRequestFullScreen().then(function () {
                  resolve();
                })["catch"](reject);
              }, {
                once: true,
                capture: true
              });
            });
          });
        };
        _proto.exitFullScreen = function exitFullScreen() {
          var _this3 = this;
          return new Promise(function (resolve, reject) {
            var requestPromise = document[_this3._fn.exitFullscreen]();
            if (window.Promise && requestPromise instanceof Promise) {
              requestPromise.then(function () {
                _this3.windowSize = _this3._cachedFrameSize;
                resolve();
              })["catch"](reject);
              return;
            }
            _this3.windowSize = _this3._cachedFrameSize;
            resolve();
          });
        };
        _proto._registerEvent = function _registerEvent() {
          var _this4 = this;
          document.addEventListener(this._fn.fullscreenerror, function () {
            var _this4$_onFullscreenE;
            (_this4$_onFullscreenE = _this4._onFullscreenError) === null || _this4$_onFullscreenE === void 0 ? void 0 : _this4$_onFullscreenE.call(_this4);
          });
          window.addEventListener('resize', function () {
            if (!_this4.handleResizeEvent) {
              return;
            }
            _this4._resizeFrame();
          });
          if (typeof window.matchMedia === 'function') {
            var updateDPRChangeListener = function updateDPRChangeListener() {
              var _window$matchMedia, _window$matchMedia$ad;
              var dpr = window.devicePixelRatio;
              (_window$matchMedia = window.matchMedia("(resolution: " + dpr + "dppx)")) === null || _window$matchMedia === void 0 ? void 0 : (_window$matchMedia$ad = _window$matchMedia.addEventListener) === null || _window$matchMedia$ad === void 0 ? void 0 : _window$matchMedia$ad.call(_window$matchMedia, 'change', function () {
                _this4.emit('window-resize', _this4.windowSize.width, _this4.windowSize.height);
                updateDPRChangeListener();
              }, {
                once: true
              });
            };
            updateDPRChangeListener();
          }
          window.addEventListener('orientationchange', function () {
            if (_this4._orientationChangeTimeoutId !== -1) {
              clearTimeout(_this4._orientationChangeTimeoutId);
            }
            _this4._orientationChangeTimeoutId = setTimeout(function () {
              if (!_this4.handleResizeEvent) {
                return;
              }
              _this4._updateFrameState();
              _this4._resizeFrame();
              _this4.emit('orientation-change', _this4.windowSize.width, _this4.windowSize.height);
              _this4._orientationChangeTimeoutId = -1;
            }, EVENT_TIMEOUT);
          });
          document.addEventListener(this._fn.fullscreenchange, function () {
            var _this4$_onFullscreenC;
            (_this4$_onFullscreenC = _this4._onFullscreenChange) === null || _this4$_onFullscreenC === void 0 ? void 0 : _this4$_onFullscreenC.call(_this4);
            _this4.emit('fullscreen-change', _this4.windowSize.width, _this4.windowSize.height);
          });
        };
        _proto._convertToSizeInCssPixels = function _convertToSizeInCssPixels(size) {
          var clonedSize = size.clone();
          var dpr = this.devicePixelRatio;
          clonedSize.width /= dpr;
          clonedSize.height /= dpr;
          return clonedSize;
        };
        _proto._resizeFrame = function _resizeFrame(sizeInCssPixels) {
          if (!this._gameFrame) {
            return;
          }
          this._gameFrame.style.display = 'flex';
          this._gameFrame.style['justify-content'] = 'center';
          this._gameFrame.style['align-items'] = 'center';
          if (this._windowType === WindowType.SubFrame) {
            if (!sizeInCssPixels) {
              this._updateContainer();
              return;
            }
            this._gameFrame.style.width = sizeInCssPixels.width + "px";
            this._gameFrame.style.height = sizeInCssPixels.height + "px";
          } else {
            var winWidth = window.innerWidth;
            var winHeight = window.innerHeight;
            if (this.isFrameRotated) {
              this._gameFrame.style['-webkit-transform'] = 'rotate(90deg)';
              this._gameFrame.style.transform = 'rotate(90deg)';
              this._gameFrame.style['-webkit-transform-origin'] = '0px 0px 0px';
              this._gameFrame.style.transformOrigin = '0px 0px 0px';
              this._gameFrame.style.margin = "0 0 0 " + winWidth + "px";
              this._gameFrame.style.width = winHeight + "px";
              this._gameFrame.style.height = winWidth + "px";
            } else {
              this._gameFrame.style['-webkit-transform'] = 'rotate(0deg)';
              this._gameFrame.style.transform = 'rotate(0deg)';
              this._gameFrame.style.margin = '0px auto';
              this._gameFrame.style.width = winWidth + "px";
              this._gameFrame.style.height = winHeight + "px";
            }
          }
          this._updateContainer();
        };
        _proto._getFullscreenTarget = function _getFullscreenTarget() {
          var windowType = this._windowType;
          if (windowType === WindowType.Fullscreen) {
            return document[this._fn.fullscreenElement];
          }
          if (windowType === WindowType.SubFrame) {
            return this._gameFrame;
          }
          return document.body;
        };
        _proto._doRequestFullScreen = function _doRequestFullScreen() {
          var _this5 = this;
          return new Promise(function (resolve, reject) {
            if (!_this5._supportFullScreen) {
              reject(new Error('fullscreen is not supported'));
              return;
            }
            var fullscreenTarget = _this5._getFullscreenTarget();
            if (!fullscreenTarget) {
              reject(new Error('Cannot access fullscreen target'));
              return;
            }
            _this5._onFullscreenChange = undefined;
            _this5._onFullscreenError = undefined;
            var requestPromise = fullscreenTarget[_this5._fn.requestFullscreen]();
            if (window.Promise && requestPromise instanceof Promise) {
              requestPromise.then(resolve)["catch"](reject);
            } else {
              _this5._onFullscreenChange = resolve;
              _this5._onFullscreenError = reject;
            }
          });
        };
        _proto._updateFrameState = function _updateFrameState() {
          var orientation = this.orientation;
          var width = window.innerWidth;
          var height = window.innerHeight;
          var isBrowserLandscape = width > height;
          this.isFrameRotated = systemInfo.isMobile && (isBrowserLandscape && orientation === Orientation.PORTRAIT || !isBrowserLandscape && orientation === Orientation.LANDSCAPE);
        };
        _proto._updateContainer = function _updateContainer() {
          if (!this._gameContainer) {
            warnID(9201);
            return;
          }
          if (this.isProportionalToFrame) {
            if (!this._gameFrame) {
              warnID(9201);
              return;
            }
            var designedResolution = legacyCC.view.getDesignResolutionSize();
            var frame = this._gameFrame;
            var frameW = frame.clientWidth;
            var frameH = frame.clientHeight;
            var designW = designedResolution.width;
            var designH = designedResolution.height;
            var scaleX = frameW / designW;
            var scaleY = frameH / designH;
            var containerStyle = this._gameContainer.style;
            var containerW;
            var containerH;
            if (scaleX < scaleY) {
              containerW = frameW;
              containerH = designH * scaleX;
            } else {
              containerW = designW * scaleY;
              containerH = frameH;
            }
            containerStyle.width = containerW + "px";
            containerStyle.height = containerH + "px";
          } else {
            var _containerStyle = this._gameContainer.style;
            _containerStyle.width = '100%';
            _containerStyle.height = '100%';
          }
          if (this._gameFrame && (this._cachedFrameStyle.width !== this._gameFrame.style.width || this._cachedFrameStyle.height !== this._gameFrame.style.height || this._cachedContainerStyle.width !== this._gameContainer.style.width || this._cachedContainerStyle.height !== this._gameContainer.style.height)) {
            this.emit('window-resize', this.windowSize.width, this.windowSize.height);
            this._cachedFrameStyle.width = this._gameFrame.style.width;
            this._cachedFrameStyle.height = this._gameFrame.style.height;
            this._cachedContainerStyle.width = this._gameContainer.style.width;
            this._cachedContainerStyle.height = this._gameContainer.style.height;
          }
        };
        _createClass(ScreenAdapter, [{
          key: "supportFullScreen",
          get: function get() {
            return this._supportFullScreen;
          }
        }, {
          key: "isFullScreen",
          get: function get() {
            if (!this._supportFullScreen) {
              return false;
            }
            return !!document[this._fn.fullscreenElement];
          }
        }, {
          key: "devicePixelRatio",
          get: function get() {
            var _window$devicePixelRa;
            return Math.min((_window$devicePixelRa = window.devicePixelRatio) !== null && _window$devicePixelRa !== void 0 ? _window$devicePixelRa : 1, 2);
          }
        }, {
          key: "windowSize",
          get: function get() {
            var result = this._windowSizeInCssPixels;
            var dpr = this.devicePixelRatio;
            result.width *= dpr;
            result.height *= dpr;
            return result;
          },
          set: function set(size) {
            if (this._windowType !== WindowType.SubFrame) {
              warnID(9202);
              return;
            }
            this._resizeFrame(this._convertToSizeInCssPixels(size));
          }
        }, {
          key: "resolution",
          get: function get() {
            var windowSize = this.windowSize;
            var resolutionScale = this.resolutionScale;
            return new Size$1(windowSize.width * resolutionScale, windowSize.height * resolutionScale);
          }
        }, {
          key: "resolutionScale",
          get: function get() {
            return this._resolutionScale;
          },
          set: function set(v) {
            var _this$_cbToUpdateFram;
            if (v === this._resolutionScale) {
              return;
            }
            this._resolutionScale = v;
            (_this$_cbToUpdateFram = this._cbToUpdateFrameBuffer) === null || _this$_cbToUpdateFram === void 0 ? void 0 : _this$_cbToUpdateFram.call(this);
          }
        }, {
          key: "orientation",
          get: function get() {
            return this._orientation;
          },
          set: function set(value) {
            if (this._orientation === value) {
              return;
            }
            this._orientation = value;
            this._updateFrameState();
          }
        }, {
          key: "safeAreaEdge",
          get: function get() {
            var dpr = this.devicePixelRatio;
            var _top = parseInt(getComputedStyle(document.documentElement).getPropertyValue('--safe-top') || '0') * dpr;
            var _bottom = parseInt(getComputedStyle(document.documentElement).getPropertyValue('--safe-bottom') || '0') * dpr;
            var _left = parseInt(getComputedStyle(document.documentElement).getPropertyValue('--safe-left') || '0') * dpr;
            var _right = parseInt(getComputedStyle(document.documentElement).getPropertyValue('--safe-right') || '0') * dpr;
            return {
              top: _top,
              bottom: _bottom,
              left: _left,
              right: _right
            };
          }
        }, {
          key: "isProportionalToFrame",
          get: function get() {
            return this._isProportionalToFrame;
          },
          set: function set(v) {
            if (this._isProportionalToFrame === v) {
              return;
            }
            this._isProportionalToFrame = v;
            this._updateContainer();
          }
        }, {
          key: "_windowSizeInCssPixels",
          get: function get() {
            if (this.isProportionalToFrame) {
              if (!this._gameContainer) {
                warnID(9201);
                return new Size$1(0, 0);
              }
              return new Size$1(this._gameContainer.clientWidth, this._gameContainer.clientHeight);
            }
            var fullscreenTarget;
            var width;
            var height;
            switch (this._windowType) {
              case WindowType.SubFrame:
                if (!this._gameFrame) {
                  warnID(9201);
                  return new Size$1(0, 0);
                }
                return new Size$1(this._gameFrame.clientWidth, this._gameFrame.clientHeight);
              case WindowType.Fullscreen:
                fullscreenTarget = this._getFullscreenTarget();
                width = this.isFrameRotated ? fullscreenTarget.clientHeight : fullscreenTarget.clientWidth;
                height = this.isFrameRotated ? fullscreenTarget.clientWidth : fullscreenTarget.clientHeight;
                return new Size$1(width, height);
              case WindowType.BrowserWindow:
                width = this.isFrameRotated ? window.innerHeight : window.innerWidth;
                height = this.isFrameRotated ? window.innerWidth : window.innerHeight;
                return new Size$1(width, height);
              case WindowType.Unknown:
              default:
                return new Size$1(0, 0);
            }
          }
        }, {
          key: "_windowType",
          get: function get() {
            if (this._isHeadlessMode) {
              return WindowType.Unknown;
            }
            if (this.isFullScreen) {
              return WindowType.Fullscreen;
            }
            if (!this._gameFrame) {
              warnID(9201);
              return WindowType.Unknown;
            }
            if (this._exactFitScreen) {
              return WindowType.BrowserWindow;
            }
            return WindowType.SubFrame;
          }
        }]);
        return ScreenAdapter;
      }(EventTarget);
      var screenAdapter = new ScreenAdapter();

      var Screen = function () {
        function Screen() {}
        var _proto = Screen.prototype;
        _proto.init = function init() {
          var _settings$querySettin, _settings$querySettin2;
          var exactFitScreen = (_settings$querySettin = settings.querySettings(Settings.Category.SCREEN, 'exactFitScreen')) !== null && _settings$querySettin !== void 0 ? _settings$querySettin : true;
          var orientation = (_settings$querySettin2 = settings.querySettings(Settings.Category.SCREEN, 'orientation')) !== null && _settings$querySettin2 !== void 0 ? _settings$querySettin2 : 'auto';
          var isHeadlessMode = settings.querySettings(Settings.Category.RENDERING, 'renderMode') === 3;
          screenAdapter.init({
            exactFitScreen: exactFitScreen,
            configOrientation: orientation,
            isHeadlessMode: isHeadlessMode
          }, function () {
            var _director$root;
            var director = legacyCC.director;
            if (!((_director$root = director.root) !== null && _director$root !== void 0 && _director$root.pipeline)) {
              warnID(1220);
              return;
            }
            director.root.pipeline.shadingScale = screenAdapter.resolutionScale;
          });
        };
        _proto.fullScreen = function fullScreen() {
          return screenAdapter.isFullScreen;
        };
        _proto.requestFullScreen = function requestFullScreen(element, onFullScreenChange, onFullScreenError) {
          if (arguments.length > 0) {
            warnID(1400, 'screen.requestFullScreen(element, onFullScreenChange?, onFullScreenError?)', 'screen.requestFullScreen(): Promise');
          }
          return screenAdapter.requestFullScreen().then(function () {
            onFullScreenChange === null || onFullScreenChange === void 0 ? void 0 : onFullScreenChange.call(document);
          })["catch"](function (err) {
            error(err);
            onFullScreenError === null || onFullScreenError === void 0 ? void 0 : onFullScreenError.call(document);
          });
        };
        _proto.exitFullScreen = function exitFullScreen() {
          return screenAdapter.exitFullScreen();
        };
        _proto.autoFullScreen = function autoFullScreen(element, onFullScreenChange) {
          var _this$requestFullScre;
          (_this$requestFullScre = this.requestFullScreen(element, onFullScreenChange)) === null || _this$requestFullScre === void 0 ? void 0 : _this$requestFullScre["catch"](function (e) {
            warn(e);
          });
        };
        _proto.disableAutoFullScreen = function disableAutoFullScreen(element) {};
        _proto.on = function on(type, callback, target) {
          screenAdapter.on(type, callback, target);
        };
        _proto.once = function once(type, callback, target) {
          screenAdapter.once(type, callback, target);
        };
        _proto.off = function off(type, callback, target) {
          screenAdapter.off(type, callback, target);
        };
        _createClass(Screen, [{
          key: "devicePixelRatio",
          get: function get() {
            return screenAdapter.devicePixelRatio;
          }
        }, {
          key: "windowSize",
          get: function get() {
            return screenAdapter.windowSize;
          },
          set: function set(size) {
            screenAdapter.windowSize = size;
          }
        }, {
          key: "resolution",
          get: function get() {
            return screenAdapter.resolution;
          }
        }, {
          key: "supportsFullScreen",
          get: function get() {
            return screenAdapter.supportFullScreen;
          }
        }]);
        return Screen;
      }();
      var screen = exports('cb', new Screen());
      legacyCC.screen = screen;

      var sys = exports('cc', {
        Feature: Feature$1,
        hasFeature: function hasFeature(feature) {
          return systemInfo.hasFeature(feature);
        },
        NetworkType: NetworkType,
        Language: Language,
        OS: OS,
        Platform: Platform,
        BrowserType: BrowserType,
        isNative: systemInfo.isNative,
        isBrowser: systemInfo.isBrowser,
        isMobile: systemInfo.isMobile,
        isLittleEndian: systemInfo.isLittleEndian,
        platform: systemInfo.platform,
        language: systemInfo.language,
        languageCode: systemInfo.nativeLanguage,
        os: systemInfo.os,
        osVersion: systemInfo.osVersion,
        osMainVersion: systemInfo.osMainVersion,
        browserType: systemInfo.browserType,
        browserVersion: systemInfo.browserVersion,
        isXR: systemInfo.isXR,
        windowPixelResolution: screen.windowSize,
        capabilities: {
          canvas: true,
          opengl: true,
          webp: systemInfo.hasFeature(Feature$1.WEBP),
          imageBitmap: systemInfo.hasFeature(Feature$1.IMAGE_BITMAP),
          touches: systemInfo.hasFeature(Feature$1.INPUT_TOUCH),
          mouse: systemInfo.hasFeature(Feature$1.EVENT_MOUSE),
          keyboard: systemInfo.hasFeature(Feature$1.EVENT_KEYBOARD),
          accelerometer: systemInfo.hasFeature(Feature$1.EVENT_ACCELEROMETER)
        },
        localStorage: {},
        getNetworkType: function getNetworkType() {
          return systemInfo.networkType;
        },
        getBatteryLevel: function getBatteryLevel() {
          return systemInfo.getBatteryLevel();
        },
        garbageCollect: function garbageCollect() {
          systemInfo.triggerGC();
        },
        isObjectValid: function isObjectValid(obj) {
          if (obj === null || obj === undefined) {
            return false;
          }
          return true;
        },
        __isWebIOS14OrIPadOS14Env: false,
        dump: function dump() {
          var str = '';
          str += "isMobile : " + this.isMobile + "\r\n";
          str += "language : " + this.language + "\r\n";
          str += "browserType : " + this.browserType + "\r\n";
          str += "browserVersion : " + this.browserVersion + "\r\n";
          str += "supports webp: " + sys.hasFeature(Feature$1.WEBP) + "\r\n";
          str += "supports bitmap: " + sys.hasFeature(Feature$1.IMAGE_BITMAP) + "\r\n";
          str += "supports touches: " + sys.hasFeature(Feature$1.INPUT_TOUCH) + "\r\n";
          str += "supports mouse: " + sys.hasFeature(Feature$1.EVENT_MOUSE) + "\r\n";
          str += "supports keyboard: " + sys.hasFeature(Feature$1.EVENT_KEYBOARD) + "\r\n";
          str += "supports accelerometer: " + sys.hasFeature(Feature$1.EVENT_ACCELEROMETER) + "\r\n";
          str += "os : " + this.os + "\r\n";
          str += "osVersion : " + this.osVersion + "\r\n";
          str += "platform : " + this.platform + "\r\n";
          str += "Using " + (legacyCC.game.renderType === legacyCC.game.RENDER_TYPE_WEBGL ? 'WEBGL' : 'CANVAS') + " renderer.\r\n";
          log(str);
        },
        openURL: function openURL(url) {
          systemInfo.openURL(url);
        },
        init: function init() {
          var _this = this;
          return Promise.resolve().then(function () {
            return systemInfo.init();
          }).then(function () {
            try {
              var localStorage = sys.localStorage = window.localStorage;
              localStorage.setItem('storage', '');
              localStorage.removeItem('storage');
              localStorage = null;
            } catch (e) {
              var warn = function warn() {
                warnID(5200);
              };
              _this.localStorage = {
                getItem: warn,
                setItem: warn,
                clear: warn,
                removeItem: warn,
                key: warn,
                length: 0
              };
            }
            {
              _this.__isWebIOS14OrIPadOS14Env = (sys.os === OS.IOS || sys.os === OS.OSX) && systemInfo.isBrowser && /(OS 14)|(Version\/14)/.test(window.navigator.userAgent);
            }
          });
        },
        now: function now() {
          return systemInfo.now();
        },
        restartVM: function restartVM() {
          systemInfo.restartJSVM();
        },
        getSafeAreaRect: function getSafeAreaRect() {
          var locView = legacyCC.view;
          var edge = screenAdapter.safeAreaEdge;
          var windowSize = screenAdapter.windowSize;
          var leftBottom = new Vec2(edge.left, edge.bottom);
          var rightTop = new Vec2(windowSize.width - edge.right, windowSize.height - edge.top);
          locView._convertToUISpace(leftBottom);
          locView._convertToUISpace(rightTop);
          var x = leftBottom.x;
          var y = leftBottom.y;
          var width = rightTop.x - leftBottom.x;
          var height = rightTop.y - leftBottom.y;
          return new Rect$1(x, y, width, height);
        }
      });
      legacyCC.sys = sys;

      var visibleRect = exports('ce', {
        topLeft: legacyCC.v2(0, 0),
        topRight: legacyCC.v2(0, 0),
        top: legacyCC.v2(0, 0),
        bottomLeft: legacyCC.v2(0, 0),
        bottomRight: legacyCC.v2(0, 0),
        bottom: legacyCC.v2(0, 0),
        center: legacyCC.v2(0, 0),
        left: legacyCC.v2(0, 0),
        right: legacyCC.v2(0, 0),
        width: 0,
        height: 0,
        init: function init(visibleRect_) {
          var w = this.width = visibleRect_.width;
          var h = this.height = visibleRect_.height;
          var l = visibleRect_.x;
          var b = visibleRect_.y;
          var t = b + h;
          var r = l + w;
          this.topLeft.x = l;
          this.topLeft.y = t;
          this.topRight.x = r;
          this.topRight.y = t;
          this.top.x = l + w / 2;
          this.top.y = t;
          this.bottomLeft.x = l;
          this.bottomLeft.y = b;
          this.bottomRight.x = r;
          this.bottomRight.y = b;
          this.bottom.x = l + w / 2;
          this.bottom.y = b;
          this.center.x = l + w / 2;
          this.center.y = b + h / 2;
          this.left.x = l;
          this.left.y = b + h / 2;
          this.right.x = r;
          this.right.y = b + h / 2;
        }
      });
      legacyCC.visibleRect = visibleRect;

      var System = exports('cs', function () {
        function System() {
          this._id = '';
          this._priority = 0;
          this._executeInEditMode = false;
        }
        System.sortByPriority = function sortByPriority(a, b) {
          if (a._priority < b._priority) {
            return 1;
          } else if (a._priority > b.priority) {
            return -1;
          } else {
            return 0;
          }
        };
        var _proto = System.prototype;
        _proto.init = function init() {};
        _proto.update = function update(dt) {};
        _proto.postUpdate = function postUpdate(dt) {};
        _proto.destroy = function destroy() {};
        _createClass(System, [{
          key: "priority",
          get: function get() {
            return this._priority;
          },
          set: function set(value) {
            this._priority = value;
          }
        }, {
          key: "id",
          get: function get() {
            return this._id;
          },
          set: function set(id) {
            this._id = id;
          }
        }]);
        return System;
      }());
      System.Priority = Enum({
        LOW: 0,
        MEDIUM: 100,
        HIGH: 200,
        SCHEDULER: 1 << 31 >>> 0
      });

      var MAX_POOL_SIZE$1 = 20;
      var idGenerator$3 = new IDGenerator('Scheduler');
      var ListEntry = function () {
        ListEntry.get = function get(target, priority, paused, markedForDeletion) {
          var result = ListEntry._listEntries.pop();
          if (result) {
            result.target = target;
            result.priority = priority;
            result.paused = paused;
            result.markedForDeletion = markedForDeletion;
          } else {
            result = new ListEntry(target, priority, paused, markedForDeletion);
          }
          return result;
        };
        ListEntry.put = function put(entry) {
          if (ListEntry._listEntries.length < MAX_POOL_SIZE$1) {
            entry.target = null;
            ListEntry._listEntries.push(entry);
          }
        };
        function ListEntry(target, priority, paused, markedForDeletion) {
          this.target = void 0;
          this.priority = void 0;
          this.paused = void 0;
          this.markedForDeletion = void 0;
          this.target = target;
          this.priority = priority;
          this.paused = paused;
          this.markedForDeletion = markedForDeletion;
        }
        return ListEntry;
      }();
      ListEntry._listEntries = [];
      var HashUpdateEntry = function () {
        HashUpdateEntry.get = function get(list, entry, target, callback) {
          var result = HashUpdateEntry._hashUpdateEntries.pop();
          if (result) {
            result.list = list;
            result.entry = entry;
            result.target = target;
            result.callback = callback;
          } else {
            result = new HashUpdateEntry(list, entry, target, callback);
          }
          return result;
        };
        HashUpdateEntry.put = function put(entry) {
          if (HashUpdateEntry._hashUpdateEntries.length < MAX_POOL_SIZE$1) {
            entry.list = entry.entry = entry.target = entry.callback = null;
            HashUpdateEntry._hashUpdateEntries.push(entry);
          }
        };
        function HashUpdateEntry(list, entry, target, callback) {
          this.list = void 0;
          this.entry = void 0;
          this.target = void 0;
          this.callback = void 0;
          this.list = list;
          this.entry = entry;
          this.target = target;
          this.callback = callback;
        }
        return HashUpdateEntry;
      }();
      HashUpdateEntry._hashUpdateEntries = [];
      var HashTimerEntry = function () {
        HashTimerEntry.get = function get(timers, target, timerIndex, currentTimer, currentTimerSalvaged, paused) {
          var result = HashTimerEntry._hashTimerEntries.pop();
          if (result) {
            result.timers = timers;
            result.target = target;
            result.timerIndex = timerIndex;
            result.currentTimer = currentTimer;
            result.currentTimerSalvaged = currentTimerSalvaged;
            result.paused = paused;
          } else {
            result = new HashTimerEntry(timers, target, timerIndex, currentTimer, currentTimerSalvaged, paused);
          }
          return result;
        };
        HashTimerEntry.put = function put(entry) {
          if (HashTimerEntry._hashTimerEntries.length < MAX_POOL_SIZE$1) {
            entry.timers = entry.target = entry.currentTimer = null;
            HashTimerEntry._hashTimerEntries.push(entry);
          }
        };
        function HashTimerEntry(timers, target, timerIndex, currentTimer, currentTimerSalvaged, paused) {
          this.timers = void 0;
          this.target = void 0;
          this.timerIndex = void 0;
          this.currentTimer = void 0;
          this.currentTimerSalvaged = void 0;
          this.paused = void 0;
          this.timers = timers;
          this.target = target;
          this.timerIndex = timerIndex;
          this.currentTimer = currentTimer;
          this.currentTimerSalvaged = currentTimerSalvaged;
          this.paused = paused;
        }
        return HashTimerEntry;
      }();
      HashTimerEntry._hashTimerEntries = [];
      var CallbackTimer = function () {
        CallbackTimer.get = function get() {
          return CallbackTimer._timers.pop() || new CallbackTimer();
        };
        CallbackTimer.put = function put(timer) {
          if (CallbackTimer._timers.length < MAX_POOL_SIZE$1 && !timer._lock) {
            timer._scheduler = timer._target = timer._callback = null;
            CallbackTimer._timers.push(timer);
          }
        };
        function CallbackTimer() {
          this._lock = void 0;
          this._scheduler = void 0;
          this._elapsed = void 0;
          this._runForever = void 0;
          this._useDelay = void 0;
          this._timesExecuted = void 0;
          this._repeat = void 0;
          this._delay = void 0;
          this._interval = void 0;
          this._target = void 0;
          this._callback = void 0;
          this._lock = false;
          this._scheduler = null;
          this._elapsed = -1;
          this._runForever = false;
          this._useDelay = false;
          this._timesExecuted = 0;
          this._repeat = 0;
          this._delay = 0;
          this._interval = 0;
          this._target = null;
        }
        var _proto = CallbackTimer.prototype;
        _proto.initWithCallback = function initWithCallback(scheduler, callback, target, seconds, repeat, delay) {
          this._lock = false;
          this._scheduler = scheduler;
          this._target = target;
          this._callback = callback;
          this._elapsed = -1;
          this._interval = seconds;
          this._delay = delay;
          this._useDelay = this._delay > 0;
          this._repeat = repeat;
          this._runForever = this._repeat === legacyCC.macro.REPEAT_FOREVER;
          return true;
        };
        _proto.getInterval = function getInterval() {
          return this._interval;
        };
        _proto.setInterval = function setInterval(interval) {
          this._interval = interval;
        };
        _proto.update = function update(dt) {
          if (this._elapsed === -1) {
            this._elapsed = 0;
            this._timesExecuted = 0;
          } else {
            this._elapsed += dt;
            if (this._runForever && !this._useDelay) {
              if (this._elapsed >= this._interval) {
                this.trigger();
                this._elapsed = 0;
              }
            } else {
              if (this._useDelay) {
                if (this._elapsed >= this._delay) {
                  this.trigger();
                  this._elapsed -= this._delay;
                  this._timesExecuted += 1;
                  this._useDelay = false;
                }
              } else if (this._elapsed >= this._interval) {
                this.trigger();
                this._elapsed = 0;
                this._timesExecuted += 1;
              }
              if (this._callback && !this._runForever && this._timesExecuted > this._repeat) {
                this.cancel();
              }
            }
          }
        };
        _proto.getCallback = function getCallback() {
          return this._callback;
        };
        _proto.trigger = function trigger() {
          if (this._target && this._callback) {
            this._lock = true;
            this._callback.call(this._target, this._elapsed);
            this._lock = false;
          }
        };
        _proto.cancel = function cancel() {
          if (this._scheduler && this._callback && this._target) {
            this._scheduler.unschedule(this._callback, this._target);
          }
        };
        return CallbackTimer;
      }();
      CallbackTimer._timers = [];
      var Scheduler = exports('cf', function (_System) {
        _inheritsLoose(Scheduler, _System);
        Scheduler.enableForTarget = function enableForTarget(target) {
          var found = false;
          if (target.uuid) {
            found = true;
          } else if (target.id) {
            found = true;
          }
          if (!found) {
            target.id = idGenerator$3.getNewId();
          }
        };
        function Scheduler() {
          var _this;
          _this = _System.call(this) || this;
          _this._timeScale = void 0;
          _this._updatesNegList = void 0;
          _this._updates0List = void 0;
          _this._updatesPosList = void 0;
          _this._hashForUpdates = void 0;
          _this._hashForTimers = void 0;
          _this._currentTarget = void 0;
          _this._currentTargetSalvaged = void 0;
          _this._updateHashLocked = void 0;
          _this._arrayForTimers = void 0;
          _this._timeScale = 1.0;
          _this._updatesNegList = [];
          _this._updates0List = [];
          _this._updatesPosList = [];
          _this._hashForUpdates = createMap(true);
          _this._hashForTimers = createMap(true);
          _this._currentTarget = null;
          _this._currentTargetSalvaged = false;
          _this._updateHashLocked = false;
          _this._arrayForTimers = [];
          return _this;
        }
        var _proto2 = Scheduler.prototype;
        _proto2.setTimeScale = function setTimeScale(timeScale) {
          this._timeScale = timeScale;
        };
        _proto2.getTimeScale = function getTimeScale() {
          return this._timeScale;
        };
        _proto2.update = function update(dt) {
          this._updateHashLocked = true;
          if (this._timeScale !== 1) {
            dt *= this._timeScale;
          }
          var i;
          var list;
          var len;
          var entry;
          for (i = 0, list = this._updatesNegList, len = list.length; i < len; i++) {
            entry = list[i];
            if (!entry.paused && !entry.markedForDeletion && entry.target) {
              var _entry$target$update, _entry$target;
              (_entry$target$update = (_entry$target = entry.target).update) === null || _entry$target$update === void 0 ? void 0 : _entry$target$update.call(_entry$target, dt);
            }
          }
          for (i = 0, list = this._updates0List, len = list.length; i < len; i++) {
            entry = list[i];
            if (!entry.paused && !entry.markedForDeletion && entry.target) {
              var _entry$target$update2, _entry$target2;
              (_entry$target$update2 = (_entry$target2 = entry.target).update) === null || _entry$target$update2 === void 0 ? void 0 : _entry$target$update2.call(_entry$target2, dt);
            }
          }
          for (i = 0, list = this._updatesPosList, len = list.length; i < len; i++) {
            entry = list[i];
            if (!entry.paused && !entry.markedForDeletion && entry.target) {
              var _entry$target$update3, _entry$target3;
              (_entry$target$update3 = (_entry$target3 = entry.target).update) === null || _entry$target$update3 === void 0 ? void 0 : _entry$target$update3.call(_entry$target3, dt);
            }
          }
          var elt;
          var arr = this._arrayForTimers;
          for (i = 0; i < arr.length; i++) {
            var _this$_currentTarget$;
            elt = arr[i];
            this._currentTarget = elt;
            this._currentTargetSalvaged = false;
            if (!elt.paused && elt.timers) {
              for (elt.timerIndex = 0; elt.timerIndex < elt.timers.length; ++elt.timerIndex) {
                elt.currentTimer = elt.timers[elt.timerIndex];
                elt.currentTimerSalvaged = false;
                elt.currentTimer.update(dt);
                elt.currentTimer = null;
              }
            }
            if (this._currentTargetSalvaged && ((_this$_currentTarget$ = this._currentTarget.timers) === null || _this$_currentTarget$ === void 0 ? void 0 : _this$_currentTarget$.length) === 0) {
              this._removeHashElement(this._currentTarget);
              --i;
            }
          }
          for (i = 0, list = this._updatesNegList; i < list.length;) {
            entry = list[i];
            if (entry.markedForDeletion) {
              this._removeUpdateFromHash(entry);
            } else {
              i++;
            }
          }
          for (i = 0, list = this._updates0List; i < list.length;) {
            entry = list[i];
            if (entry.markedForDeletion) {
              this._removeUpdateFromHash(entry);
            } else {
              i++;
            }
          }
          for (i = 0, list = this._updatesPosList; i < list.length;) {
            entry = list[i];
            if (entry.markedForDeletion) {
              this._removeUpdateFromHash(entry);
            } else {
              i++;
            }
          }
          this._updateHashLocked = false;
          this._currentTarget = null;
        };
        _proto2.schedule = function schedule(callbackTmp, targetTmp, interval, repeat, delay, paused) {
          var _repeat, _delay;
          var callback;
          var target;
          if (typeof callbackTmp !== 'function') {
            warnID(1514);
            callback = targetTmp;
            target = callbackTmp;
          } else {
            callback = callbackTmp;
            target = targetTmp;
          }
          if (arguments.length === 3 || arguments.length === 4 || arguments.length === 5) {
            paused = !!repeat;
            repeat = legacyCC.macro.REPEAT_FOREVER;
            delay = 0;
          }
          assertID(Boolean(target), 1502);
          var targetId = target.uuid || target.id;
          if (!targetId) {
            errorID(1510);
            return;
          }
          var element = this._hashForTimers[targetId];
          if (!element) {
            element = HashTimerEntry.get(null, target, 0, null, false, Boolean(paused));
            this._arrayForTimers.push(element);
            this._hashForTimers[targetId] = element;
          } else if (element.paused !== paused) {
            warnID(1511);
          }
          var timer;
          var i;
          if (element.timers == null) {
            element.timers = [];
          } else {
            for (i = 0; i < element.timers.length; ++i) {
              timer = element.timers[i];
              if (timer && callback === timer.getCallback()) {
                logID(1507, timer.getInterval(), interval);
                timer.setInterval(interval);
                return;
              }
            }
          }
          timer = CallbackTimer.get();
          timer.initWithCallback(this, callback, target, interval, (_repeat = repeat) !== null && _repeat !== void 0 ? _repeat : 0, (_delay = delay) !== null && _delay !== void 0 ? _delay : 0);
          element.timers.push(timer);
          if (this._currentTarget === element && this._currentTargetSalvaged) {
            this._currentTargetSalvaged = false;
          }
        };
        _proto2.scheduleUpdate = function scheduleUpdate(target, priority, paused) {
          var targetId = target.uuid || target.id;
          if (!targetId) {
            errorID(1510);
            return;
          }
          var hashElement = this._hashForUpdates[targetId];
          if (hashElement && hashElement.entry) {
            if (hashElement.entry.priority !== priority) {
              if (this._updateHashLocked) {
                logID(1506);
                hashElement.entry.markedForDeletion = false;
                hashElement.entry.paused = paused;
                return;
              } else {
                this.unscheduleUpdate(target);
              }
            } else {
              hashElement.entry.markedForDeletion = false;
              hashElement.entry.paused = paused;
              return;
            }
          }
          var listElement = ListEntry.get(target, priority, paused, false);
          var ppList;
          if (priority === 0) {
            ppList = this._updates0List;
            this._appendIn(ppList, listElement);
          } else {
            ppList = priority < 0 ? this._updatesNegList : this._updatesPosList;
            this._priorityIn(ppList, listElement, priority);
          }
          this._hashForUpdates[targetId] = HashUpdateEntry.get(ppList, listElement, target, null);
        };
        _proto2.unschedule = function unschedule(callback, target) {
          if (!target || !callback) {
            return;
          }
          var targetId = target.uuid || target.id;
          if (!targetId) {
            errorID(1510);
            return;
          }
          var element = this._hashForTimers[targetId];
          if (element) {
            var timers = element.timers;
            if (!timers) {
              return;
            }
            for (var i = 0, li = timers.length; i < li; i++) {
              var timer = timers[i];
              if (callback === timer.getCallback()) {
                if (timer === element.currentTimer && !element.currentTimerSalvaged) {
                  element.currentTimerSalvaged = true;
                }
                timers.splice(i, 1);
                CallbackTimer.put(timer);
                if (element.timerIndex >= i) {
                  element.timerIndex--;
                }
                if (timers.length === 0) {
                  if (this._currentTarget === element) {
                    this._currentTargetSalvaged = true;
                  } else {
                    this._removeHashElement(element);
                  }
                }
                return;
              }
            }
          }
        };
        _proto2.unscheduleUpdate = function unscheduleUpdate(target) {
          if (!target) {
            return;
          }
          var targetId = target.uuid || target.id;
          if (!targetId) {
            errorID(1510);
            return;
          }
          var element = this._hashForUpdates[targetId];
          if (element !== null && element !== void 0 && element.entry) {
            if (this._updateHashLocked) {
              element.entry.markedForDeletion = true;
            } else {
              this._removeUpdateFromHash(element.entry);
            }
          }
        };
        _proto2.unscheduleAllForTarget = function unscheduleAllForTarget(target) {
          if (!target) {
            return;
          }
          var targetId = target.uuid || target.id;
          if (!targetId) {
            errorID(1510);
            return;
          }
          var element = this._hashForTimers[targetId];
          if (element !== null && element !== void 0 && element.timers) {
            var timers = element.timers;
            if (element.currentTimer && timers.indexOf(element.currentTimer) > -1 && !element.currentTimerSalvaged) {
              element.currentTimerSalvaged = true;
            }
            for (var i = 0, l = timers.length; i < l; i++) {
              CallbackTimer.put(timers[i]);
            }
            timers.length = 0;
            if (this._currentTarget === element) {
              this._currentTargetSalvaged = true;
            } else {
              this._removeHashElement(element);
            }
          }
          this.unscheduleUpdate(target);
        };
        _proto2.unscheduleAll = function unscheduleAll() {
          this.unscheduleAllWithMinPriority(System.Priority.SCHEDULER);
        };
        _proto2.unscheduleAllWithMinPriority = function unscheduleAllWithMinPriority(minPriority) {
          var i;
          var element;
          var arr = this._arrayForTimers;
          for (i = arr.length - 1; i >= 0; i--) {
            element = arr[i];
            if (element.target) {
              this.unscheduleAllForTarget(element.target);
            }
          }
          var entry;
          var temp_length = 0;
          if (minPriority < 0) {
            for (i = 0; i < this._updatesNegList.length;) {
              var _entry;
              temp_length = this._updatesNegList.length;
              entry = this._updatesNegList[i];
              if ((_entry = entry) !== null && _entry !== void 0 && _entry.target && entry.priority >= minPriority) {
                this.unscheduleUpdate(entry.target);
              }
              if (temp_length === this._updatesNegList.length) {
                i++;
              }
            }
          }
          if (minPriority <= 0) {
            for (i = 0; i < this._updates0List.length;) {
              var _entry2;
              temp_length = this._updates0List.length;
              entry = this._updates0List[i];
              if ((_entry2 = entry) !== null && _entry2 !== void 0 && _entry2.target) {
                this.unscheduleUpdate(entry.target);
              }
              if (temp_length === this._updates0List.length) {
                i++;
              }
            }
          }
          for (i = 0; i < this._updatesPosList.length;) {
            var _entry3;
            temp_length = this._updatesPosList.length;
            entry = this._updatesPosList[i];
            if ((_entry3 = entry) !== null && _entry3 !== void 0 && _entry3.target && entry.priority >= minPriority) {
              this.unscheduleUpdate(entry.target);
            }
            if (temp_length === this._updatesPosList.length) {
              i++;
            }
          }
        };
        _proto2.isScheduled = function isScheduled(callback, target) {
          assertID(Boolean(callback), 1508);
          assertID(Boolean(target), 1509);
          var targetId = target.uuid || target.id;
          if (!targetId) {
            errorID(1510);
            return false;
          }
          var element = this._hashForTimers[targetId];
          if (!element) {
            return false;
          }
          if (element.timers == null) {
            return false;
          } else {
            var timers = element.timers;
            for (var i = 0; i < timers.length; ++i) {
              var timer = timers[i];
              if (callback === timer.getCallback()) {
                return true;
              }
            }
            return false;
          }
        };
        _proto2.pauseAllTargets = function pauseAllTargets() {
          return this.pauseAllTargetsWithMinPriority(System.Priority.SCHEDULER);
        };
        _proto2.pauseAllTargetsWithMinPriority = function pauseAllTargetsWithMinPriority(minPriority) {
          var idsWithSelectors = [];
          var element;
          var locArrayForTimers = this._arrayForTimers;
          var i;
          var li;
          for (i = 0, li = locArrayForTimers.length; i < li; i++) {
            var _element;
            element = locArrayForTimers[i];
            if ((_element = element) !== null && _element !== void 0 && _element.target) {
              element.paused = true;
              idsWithSelectors.push(element.target);
            }
          }
          var entry;
          if (minPriority < 0) {
            for (i = 0; i < this._updatesNegList.length; i++) {
              var _entry4;
              entry = this._updatesNegList[i];
              if ((_entry4 = entry) !== null && _entry4 !== void 0 && _entry4.target) {
                if (entry.priority >= minPriority) {
                  entry.paused = true;
                  idsWithSelectors.push(entry.target);
                }
              }
            }
          }
          if (minPriority <= 0) {
            for (i = 0; i < this._updates0List.length; i++) {
              var _entry5;
              entry = this._updates0List[i];
              if ((_entry5 = entry) !== null && _entry5 !== void 0 && _entry5.target) {
                entry.paused = true;
                idsWithSelectors.push(entry.target);
              }
            }
          }
          for (i = 0; i < this._updatesPosList.length; i++) {
            var _entry6;
            entry = this._updatesPosList[i];
            if ((_entry6 = entry) !== null && _entry6 !== void 0 && _entry6.target) {
              if (entry.priority >= minPriority) {
                entry.paused = true;
                idsWithSelectors.push(entry.target);
              }
            }
          }
          return idsWithSelectors;
        };
        _proto2.resumeTargets = function resumeTargets(targetsToResume) {
          if (!targetsToResume) {
            return;
          }
          for (var i = 0; i < targetsToResume.length; i++) {
            this.resumeTarget(targetsToResume[i]);
          }
        };
        _proto2.pauseTarget = function pauseTarget(target) {
          assertID(Boolean(target), 1503);
          var targetId = target.uuid || target.id;
          if (!targetId) {
            errorID(1510);
            return;
          }
          var element = this._hashForTimers[targetId];
          if (element) {
            element.paused = true;
          }
          var elementUpdate = this._hashForUpdates[targetId];
          if (elementUpdate !== null && elementUpdate !== void 0 && elementUpdate.entry) {
            elementUpdate.entry.paused = true;
          }
        };
        _proto2.resumeTarget = function resumeTarget(target) {
          assertID(Boolean(target), 1504);
          var targetId = target.uuid || target.id;
          if (!targetId) {
            errorID(1510);
            return;
          }
          var element = this._hashForTimers[targetId];
          if (element) {
            element.paused = false;
          }
          var elementUpdate = this._hashForUpdates[targetId];
          if (elementUpdate !== null && elementUpdate !== void 0 && elementUpdate.entry) {
            elementUpdate.entry.paused = false;
          }
        };
        _proto2.isTargetPaused = function isTargetPaused(target) {
          assertID(Boolean(target), 1505);
          var targetId = target.uuid || target.id;
          if (!targetId) {
            errorID(1510);
            return false;
          }
          var element = this._hashForTimers[targetId];
          if (element) {
            return element.paused;
          }
          var elementUpdate = this._hashForUpdates[targetId];
          if (elementUpdate !== null && elementUpdate !== void 0 && elementUpdate.entry) {
            return elementUpdate.entry.paused;
          }
          return false;
        };
        _proto2._removeHashElement = function _removeHashElement(element) {
          if (!element.target) {
            return;
          }
          var targetId = element.target.uuid || element.target.id;
          if (typeof targetId === 'undefined') {
            return;
          }
          delete this._hashForTimers[targetId];
          var arr = this._arrayForTimers;
          for (var i = 0, l = arr.length; i < l; i++) {
            if (arr[i] === element) {
              arr.splice(i, 1);
              break;
            }
          }
          HashTimerEntry.put(element);
        };
        _proto2._removeUpdateFromHash = function _removeUpdateFromHash(entry) {
          if (!entry.target) {
            return;
          }
          var targetId = entry.target.uuid || entry.target.id;
          if (typeof targetId === 'undefined') {
            return;
          }
          var element = this._hashForUpdates[targetId];
          if (element) {
            var list = element.list;
            var listEntry = element.entry;
            if (list) {
              for (var i = 0, l = list.length; i < l; i++) {
                if (list[i] === listEntry) {
                  list.splice(i, 1);
                  break;
                }
              }
            }
            delete this._hashForUpdates[targetId];
            if (listEntry) {
              ListEntry.put(listEntry);
            }
            HashUpdateEntry.put(element);
          }
        };
        _proto2._priorityIn = function _priorityIn(ppList, listElement, priority) {
          for (var i = 0; i < ppList.length; i++) {
            if (priority < ppList[i].priority) {
              ppList.splice(i, 0, listElement);
              return;
            }
          }
          ppList.push(listElement);
        };
        _proto2._appendIn = function _appendIn(ppList, listElement) {
          ppList.push(listElement);
        };
        return Scheduler;
      }(System));
      Scheduler.ID = 'scheduler';
      legacyCC.Scheduler = Scheduler;

      var getUint8ForString = String.prototype.charCodeAt;
      function getUint8ForArray(idx) {
        return this[idx];
      }
      function murmurhash2_32_gc(input, seed) {
        var l = input.length;
        var h = seed ^ l;
        var i = 0;
        var getUint8 = typeof input === 'string' ? getUint8ForString : getUint8ForArray;
        while (l >= 4) {
          var k = getUint8.call(input, i) & 0xff | (getUint8.call(input, ++i) & 0xff) << 8 | (getUint8.call(input, ++i) & 0xff) << 16 | (getUint8.call(input, ++i) & 0xff) << 24;
          k = (k & 0xffff) * 0x5bd1e995 + (((k >>> 16) * 0x5bd1e995 & 0xffff) << 16);
          k ^= k >>> 24;
          k = (k & 0xffff) * 0x5bd1e995 + (((k >>> 16) * 0x5bd1e995 & 0xffff) << 16);
          h = (h & 0xffff) * 0x5bd1e995 + (((h >>> 16) * 0x5bd1e995 & 0xffff) << 16) ^ k;
          l -= 4;
          ++i;
        }
        switch (l) {
          case 3:
            h ^= (getUint8.call(input, i + 2) & 0xff) << 16;
          case 2:
            h ^= (getUint8.call(input, i + 1) & 0xff) << 8;
          case 1:
            h ^= getUint8.call(input, i) & 0xff;
            h = (h & 0xffff) * 0x5bd1e995 + (((h >>> 16) * 0x5bd1e995 & 0xffff) << 16);
            break;
        }
        h ^= h >>> 13;
        h = (h & 0xffff) * 0x5bd1e995 + (((h >>> 16) * 0x5bd1e995 & 0xffff) << 16);
        h ^= h >>> 15;
        return h >>> 0;
      }

      legacyCC.easing = easing;

      function syncNodeValues(node) {
        var lpos = node._lpos;
        node.setPositionForJS(lpos.x, lpos.y, lpos.z);
        var lscale = node._lscale;
        node.setScaleForJS(lscale.x, lscale.y, lscale.z);
        var lrot = node._lrot;
        node.setRotationForJS(lrot.x, lrot.y, lrot.z, lrot.w);
        var euler = node._euler;
        node.setRotationFromEulerForJS(euler.x, euler.y, euler.z);
      }
      function updateChildrenForDeserialize(node) {
        if (!node) {
          return;
        }
        var children = node.children;
        if (!children) {
          return;
        }
        var len = children.length;
        if (!len) {
          return;
        }
        node._setChildren(children);
        for (var i = 0; i < len; ++i) {
          var child = children[i];
          updateChildrenForDeserialize(child);
        }
      }
      function ExtraEventMethods() {}
      ExtraEventMethods.prototype.once = function once(type, callback, target) {
        return this.on(type, callback, target, true);
      };
      ExtraEventMethods.prototype.targetOff = function targetOff(typeOrTarget) {
        this.removeAll(typeOrTarget);
      };

      var jsbUtils = /*#__PURE__*/Object.freeze({
        __proto__: null,
        syncNodeValues: syncNodeValues,
        updateChildrenForDeserialize: updateChildrenForDeserialize,
        ExtraEventMethods: ExtraEventMethods
      });
      exports('cx', jsbUtils);

      function shift(array, first, last) {
        assertsArrayIndex(array, first);
        assertsArrayIndex(array, last);
        if (first === last) {
          return array;
        }
        var element = array[first];
        if (first < last) {
          for (var iElement = first + 1; iElement <= last; ++iElement) {
            array[iElement - 1] = array[iElement];
          }
        } else {
          for (var _iElement = first; _iElement !== last; --_iElement) {
            array[_iElement] = array[_iElement - 1];
          }
        }
        array[last] = element;
        return array;
      }

      var GarbageCollectionManager = function () {
        function GarbageCollectionManager() {
          this._finalizationRegistry = null;
          this._gcObjects = new WeakMap();
        }
        var _proto = GarbageCollectionManager.prototype;
        _proto.registerGCObject = function registerGCObject(gcObject) {
          {
            return gcObject;
          }
        };
        _proto.init = function init() {};
        _proto.finalizationRegistryCallback = function finalizationRegistryCallback(token) {
          var gcObject = this._gcObjects.get(token);
          if (gcObject) {
            this._gcObjects["delete"](token);
            gcObject.destroy();
          }
          this._finalizationRegistry.unregister(token);
        };
        _proto.destroy = function destroy() {};
        return GarbageCollectionManager;
      }();
      var garbageCollectionManager = exports('cL', new GarbageCollectionManager());

      var GCObject = exports('cM', function () {
        function GCObject() {
          return garbageCollectionManager.registerGCObject(this);
        }
        var _proto = GCObject.prototype;
        _proto.destroy = function destroy() {};
        return GCObject;
      }());

      function deepFlatten(strList, array) {
        for (var _iterator = _createForOfIteratorHelperLoose(array), _step; !(_step = _iterator()).done;) {
          var item = _step.value;
          if (Array.isArray(item)) {
            deepFlatten(strList, item);
          } else {
            strList.push(item);
          }
        }
      }
      function flattenCodeArray(array) {
        var separator = '';
        var strList = [];
        deepFlatten(strList, array);
        return strList.join(separator);
      }

      function applyMixins(derivedCtor, baseCtors) {
        baseCtors.forEach(function (baseCtor) {
          Object.getOwnPropertyNames(baseCtor.prototype).forEach(function (name) {
            if (name !== 'constructor') {
              Object.defineProperty(derivedCtor.prototype, name, Object.getOwnPropertyDescriptor(baseCtor.prototype, name));
            }
          });
        });
      }

      legacyCC.math = math;
      legacyCC.geometry = geometry;

      var deepCopy = function deepCopy(target, source, Ctor) {
        for (var i = 0; i < source.length; ++i) {
          if (target.length <= i) target.push(new Ctor());
          target[i].copy(source[i]);
        }
        target.length = source.length;
      };
      var ObjectType;
      (function (ObjectType) {
        ObjectType[ObjectType["UNKNOWN"] = 0] = "UNKNOWN";
        ObjectType[ObjectType["SWAPCHAIN"] = 1] = "SWAPCHAIN";
        ObjectType[ObjectType["BUFFER"] = 2] = "BUFFER";
        ObjectType[ObjectType["TEXTURE"] = 3] = "TEXTURE";
        ObjectType[ObjectType["RENDER_PASS"] = 4] = "RENDER_PASS";
        ObjectType[ObjectType["FRAMEBUFFER"] = 5] = "FRAMEBUFFER";
        ObjectType[ObjectType["SAMPLER"] = 6] = "SAMPLER";
        ObjectType[ObjectType["SHADER"] = 7] = "SHADER";
        ObjectType[ObjectType["DESCRIPTOR_SET_LAYOUT"] = 8] = "DESCRIPTOR_SET_LAYOUT";
        ObjectType[ObjectType["PIPELINE_LAYOUT"] = 9] = "PIPELINE_LAYOUT";
        ObjectType[ObjectType["PIPELINE_STATE"] = 10] = "PIPELINE_STATE";
        ObjectType[ObjectType["DESCRIPTOR_SET"] = 11] = "DESCRIPTOR_SET";
        ObjectType[ObjectType["INPUT_ASSEMBLER"] = 12] = "INPUT_ASSEMBLER";
        ObjectType[ObjectType["COMMAND_BUFFER"] = 13] = "COMMAND_BUFFER";
        ObjectType[ObjectType["QUEUE"] = 14] = "QUEUE";
        ObjectType[ObjectType["QUERY_POOL"] = 15] = "QUERY_POOL";
        ObjectType[ObjectType["GLOBAL_BARRIER"] = 16] = "GLOBAL_BARRIER";
        ObjectType[ObjectType["TEXTURE_BARRIER"] = 17] = "TEXTURE_BARRIER";
        ObjectType[ObjectType["BUFFER_BARRIER"] = 18] = "BUFFER_BARRIER";
        ObjectType[ObjectType["COUNT"] = 19] = "COUNT";
      })(ObjectType || (ObjectType = {}));
      var Status;
      (function (Status) {
        Status[Status["UNREADY"] = 0] = "UNREADY";
        Status[Status["FAILED"] = 1] = "FAILED";
        Status[Status["SUCCESS"] = 2] = "SUCCESS";
      })(Status || (Status = {}));
      var API;
      (function (API) {
        API[API["UNKNOWN"] = 0] = "UNKNOWN";
        API[API["GLES2"] = 1] = "GLES2";
        API[API["GLES3"] = 2] = "GLES3";
        API[API["METAL"] = 3] = "METAL";
        API[API["VULKAN"] = 4] = "VULKAN";
        API[API["NVN"] = 5] = "NVN";
        API[API["WEBGL"] = 6] = "WEBGL";
        API[API["WEBGL2"] = 7] = "WEBGL2";
        API[API["WEBGPU"] = 8] = "WEBGPU";
      })(API || (API = {}));
      var SurfaceTransform;
      (function (SurfaceTransform) {
        SurfaceTransform[SurfaceTransform["IDENTITY"] = 0] = "IDENTITY";
        SurfaceTransform[SurfaceTransform["ROTATE_90"] = 1] = "ROTATE_90";
        SurfaceTransform[SurfaceTransform["ROTATE_180"] = 2] = "ROTATE_180";
        SurfaceTransform[SurfaceTransform["ROTATE_270"] = 3] = "ROTATE_270";
      })(SurfaceTransform || (SurfaceTransform = {}));
      var Feature;
      (function (Feature) {
        Feature[Feature["ELEMENT_INDEX_UINT"] = 0] = "ELEMENT_INDEX_UINT";
        Feature[Feature["INSTANCED_ARRAYS"] = 1] = "INSTANCED_ARRAYS";
        Feature[Feature["MULTIPLE_RENDER_TARGETS"] = 2] = "MULTIPLE_RENDER_TARGETS";
        Feature[Feature["BLEND_MINMAX"] = 3] = "BLEND_MINMAX";
        Feature[Feature["COMPUTE_SHADER"] = 4] = "COMPUTE_SHADER";
        Feature[Feature["INPUT_ATTACHMENT_BENEFIT"] = 5] = "INPUT_ATTACHMENT_BENEFIT";
        Feature[Feature["SUBPASS_COLOR_INPUT"] = 6] = "SUBPASS_COLOR_INPUT";
        Feature[Feature["SUBPASS_DEPTH_STENCIL_INPUT"] = 7] = "SUBPASS_DEPTH_STENCIL_INPUT";
        Feature[Feature["RASTERIZATION_ORDER_COHERENT"] = 8] = "RASTERIZATION_ORDER_COHERENT";
        Feature[Feature["MULTI_SAMPLE_RESOLVE_DEPTH_STENCIL"] = 9] = "MULTI_SAMPLE_RESOLVE_DEPTH_STENCIL";
        Feature[Feature["COUNT"] = 10] = "COUNT";
      })(Feature || (Feature = {}));
      var Format;
      (function (Format) {
        Format[Format["UNKNOWN"] = 0] = "UNKNOWN";
        Format[Format["A8"] = 1] = "A8";
        Format[Format["L8"] = 2] = "L8";
        Format[Format["LA8"] = 3] = "LA8";
        Format[Format["R8"] = 4] = "R8";
        Format[Format["R8SN"] = 5] = "R8SN";
        Format[Format["R8UI"] = 6] = "R8UI";
        Format[Format["R8I"] = 7] = "R8I";
        Format[Format["R16F"] = 8] = "R16F";
        Format[Format["R16UI"] = 9] = "R16UI";
        Format[Format["R16I"] = 10] = "R16I";
        Format[Format["R32F"] = 11] = "R32F";
        Format[Format["R32UI"] = 12] = "R32UI";
        Format[Format["R32I"] = 13] = "R32I";
        Format[Format["RG8"] = 14] = "RG8";
        Format[Format["RG8SN"] = 15] = "RG8SN";
        Format[Format["RG8UI"] = 16] = "RG8UI";
        Format[Format["RG8I"] = 17] = "RG8I";
        Format[Format["RG16F"] = 18] = "RG16F";
        Format[Format["RG16UI"] = 19] = "RG16UI";
        Format[Format["RG16I"] = 20] = "RG16I";
        Format[Format["RG32F"] = 21] = "RG32F";
        Format[Format["RG32UI"] = 22] = "RG32UI";
        Format[Format["RG32I"] = 23] = "RG32I";
        Format[Format["RGB8"] = 24] = "RGB8";
        Format[Format["SRGB8"] = 25] = "SRGB8";
        Format[Format["RGB8SN"] = 26] = "RGB8SN";
        Format[Format["RGB8UI"] = 27] = "RGB8UI";
        Format[Format["RGB8I"] = 28] = "RGB8I";
        Format[Format["RGB16F"] = 29] = "RGB16F";
        Format[Format["RGB16UI"] = 30] = "RGB16UI";
        Format[Format["RGB16I"] = 31] = "RGB16I";
        Format[Format["RGB32F"] = 32] = "RGB32F";
        Format[Format["RGB32UI"] = 33] = "RGB32UI";
        Format[Format["RGB32I"] = 34] = "RGB32I";
        Format[Format["RGBA8"] = 35] = "RGBA8";
        Format[Format["BGRA8"] = 36] = "BGRA8";
        Format[Format["SRGB8_A8"] = 37] = "SRGB8_A8";
        Format[Format["RGBA8SN"] = 38] = "RGBA8SN";
        Format[Format["RGBA8UI"] = 39] = "RGBA8UI";
        Format[Format["RGBA8I"] = 40] = "RGBA8I";
        Format[Format["RGBA16F"] = 41] = "RGBA16F";
        Format[Format["RGBA16UI"] = 42] = "RGBA16UI";
        Format[Format["RGBA16I"] = 43] = "RGBA16I";
        Format[Format["RGBA32F"] = 44] = "RGBA32F";
        Format[Format["RGBA32UI"] = 45] = "RGBA32UI";
        Format[Format["RGBA32I"] = 46] = "RGBA32I";
        Format[Format["R5G6B5"] = 47] = "R5G6B5";
        Format[Format["R11G11B10F"] = 48] = "R11G11B10F";
        Format[Format["RGB5A1"] = 49] = "RGB5A1";
        Format[Format["RGBA4"] = 50] = "RGBA4";
        Format[Format["RGB10A2"] = 51] = "RGB10A2";
        Format[Format["RGB10A2UI"] = 52] = "RGB10A2UI";
        Format[Format["RGB9E5"] = 53] = "RGB9E5";
        Format[Format["DEPTH"] = 54] = "DEPTH";
        Format[Format["DEPTH_STENCIL"] = 55] = "DEPTH_STENCIL";
        Format[Format["BC1"] = 56] = "BC1";
        Format[Format["BC1_ALPHA"] = 57] = "BC1_ALPHA";
        Format[Format["BC1_SRGB"] = 58] = "BC1_SRGB";
        Format[Format["BC1_SRGB_ALPHA"] = 59] = "BC1_SRGB_ALPHA";
        Format[Format["BC2"] = 60] = "BC2";
        Format[Format["BC2_SRGB"] = 61] = "BC2_SRGB";
        Format[Format["BC3"] = 62] = "BC3";
        Format[Format["BC3_SRGB"] = 63] = "BC3_SRGB";
        Format[Format["BC4"] = 64] = "BC4";
        Format[Format["BC4_SNORM"] = 65] = "BC4_SNORM";
        Format[Format["BC5"] = 66] = "BC5";
        Format[Format["BC5_SNORM"] = 67] = "BC5_SNORM";
        Format[Format["BC6H_UF16"] = 68] = "BC6H_UF16";
        Format[Format["BC6H_SF16"] = 69] = "BC6H_SF16";
        Format[Format["BC7"] = 70] = "BC7";
        Format[Format["BC7_SRGB"] = 71] = "BC7_SRGB";
        Format[Format["ETC_RGB8"] = 72] = "ETC_RGB8";
        Format[Format["ETC2_RGB8"] = 73] = "ETC2_RGB8";
        Format[Format["ETC2_SRGB8"] = 74] = "ETC2_SRGB8";
        Format[Format["ETC2_RGB8_A1"] = 75] = "ETC2_RGB8_A1";
        Format[Format["ETC2_SRGB8_A1"] = 76] = "ETC2_SRGB8_A1";
        Format[Format["ETC2_RGBA8"] = 77] = "ETC2_RGBA8";
        Format[Format["ETC2_SRGB8_A8"] = 78] = "ETC2_SRGB8_A8";
        Format[Format["EAC_R11"] = 79] = "EAC_R11";
        Format[Format["EAC_R11SN"] = 80] = "EAC_R11SN";
        Format[Format["EAC_RG11"] = 81] = "EAC_RG11";
        Format[Format["EAC_RG11SN"] = 82] = "EAC_RG11SN";
        Format[Format["PVRTC_RGB2"] = 83] = "PVRTC_RGB2";
        Format[Format["PVRTC_RGBA2"] = 84] = "PVRTC_RGBA2";
        Format[Format["PVRTC_RGB4"] = 85] = "PVRTC_RGB4";
        Format[Format["PVRTC_RGBA4"] = 86] = "PVRTC_RGBA4";
        Format[Format["PVRTC2_2BPP"] = 87] = "PVRTC2_2BPP";
        Format[Format["PVRTC2_4BPP"] = 88] = "PVRTC2_4BPP";
        Format[Format["ASTC_RGBA_4X4"] = 89] = "ASTC_RGBA_4X4";
        Format[Format["ASTC_RGBA_5X4"] = 90] = "ASTC_RGBA_5X4";
        Format[Format["ASTC_RGBA_5X5"] = 91] = "ASTC_RGBA_5X5";
        Format[Format["ASTC_RGBA_6X5"] = 92] = "ASTC_RGBA_6X5";
        Format[Format["ASTC_RGBA_6X6"] = 93] = "ASTC_RGBA_6X6";
        Format[Format["ASTC_RGBA_8X5"] = 94] = "ASTC_RGBA_8X5";
        Format[Format["ASTC_RGBA_8X6"] = 95] = "ASTC_RGBA_8X6";
        Format[Format["ASTC_RGBA_8X8"] = 96] = "ASTC_RGBA_8X8";
        Format[Format["ASTC_RGBA_10X5"] = 97] = "ASTC_RGBA_10X5";
        Format[Format["ASTC_RGBA_10X6"] = 98] = "ASTC_RGBA_10X6";
        Format[Format["ASTC_RGBA_10X8"] = 99] = "ASTC_RGBA_10X8";
        Format[Format["ASTC_RGBA_10X10"] = 100] = "ASTC_RGBA_10X10";
        Format[Format["ASTC_RGBA_12X10"] = 101] = "ASTC_RGBA_12X10";
        Format[Format["ASTC_RGBA_12X12"] = 102] = "ASTC_RGBA_12X12";
        Format[Format["ASTC_SRGBA_4X4"] = 103] = "ASTC_SRGBA_4X4";
        Format[Format["ASTC_SRGBA_5X4"] = 104] = "ASTC_SRGBA_5X4";
        Format[Format["ASTC_SRGBA_5X5"] = 105] = "ASTC_SRGBA_5X5";
        Format[Format["ASTC_SRGBA_6X5"] = 106] = "ASTC_SRGBA_6X5";
        Format[Format["ASTC_SRGBA_6X6"] = 107] = "ASTC_SRGBA_6X6";
        Format[Format["ASTC_SRGBA_8X5"] = 108] = "ASTC_SRGBA_8X5";
        Format[Format["ASTC_SRGBA_8X6"] = 109] = "ASTC_SRGBA_8X6";
        Format[Format["ASTC_SRGBA_8X8"] = 110] = "ASTC_SRGBA_8X8";
        Format[Format["ASTC_SRGBA_10X5"] = 111] = "ASTC_SRGBA_10X5";
        Format[Format["ASTC_SRGBA_10X6"] = 112] = "ASTC_SRGBA_10X6";
        Format[Format["ASTC_SRGBA_10X8"] = 113] = "ASTC_SRGBA_10X8";
        Format[Format["ASTC_SRGBA_10X10"] = 114] = "ASTC_SRGBA_10X10";
        Format[Format["ASTC_SRGBA_12X10"] = 115] = "ASTC_SRGBA_12X10";
        Format[Format["ASTC_SRGBA_12X12"] = 116] = "ASTC_SRGBA_12X12";
        Format[Format["COUNT"] = 117] = "COUNT";
      })(Format || (Format = {}));
      var FormatType;
      (function (FormatType) {
        FormatType[FormatType["NONE"] = 0] = "NONE";
        FormatType[FormatType["UNORM"] = 1] = "UNORM";
        FormatType[FormatType["SNORM"] = 2] = "SNORM";
        FormatType[FormatType["UINT"] = 3] = "UINT";
        FormatType[FormatType["INT"] = 4] = "INT";
        FormatType[FormatType["UFLOAT"] = 5] = "UFLOAT";
        FormatType[FormatType["FLOAT"] = 6] = "FLOAT";
      })(FormatType || (FormatType = {}));
      var Type$1;
      (function (Type) {
        Type[Type["UNKNOWN"] = 0] = "UNKNOWN";
        Type[Type["BOOL"] = 1] = "BOOL";
        Type[Type["BOOL2"] = 2] = "BOOL2";
        Type[Type["BOOL3"] = 3] = "BOOL3";
        Type[Type["BOOL4"] = 4] = "BOOL4";
        Type[Type["INT"] = 5] = "INT";
        Type[Type["INT2"] = 6] = "INT2";
        Type[Type["INT3"] = 7] = "INT3";
        Type[Type["INT4"] = 8] = "INT4";
        Type[Type["UINT"] = 9] = "UINT";
        Type[Type["UINT2"] = 10] = "UINT2";
        Type[Type["UINT3"] = 11] = "UINT3";
        Type[Type["UINT4"] = 12] = "UINT4";
        Type[Type["FLOAT"] = 13] = "FLOAT";
        Type[Type["FLOAT2"] = 14] = "FLOAT2";
        Type[Type["FLOAT3"] = 15] = "FLOAT3";
        Type[Type["FLOAT4"] = 16] = "FLOAT4";
        Type[Type["MAT2"] = 17] = "MAT2";
        Type[Type["MAT2X3"] = 18] = "MAT2X3";
        Type[Type["MAT2X4"] = 19] = "MAT2X4";
        Type[Type["MAT3X2"] = 20] = "MAT3X2";
        Type[Type["MAT3"] = 21] = "MAT3";
        Type[Type["MAT3X4"] = 22] = "MAT3X4";
        Type[Type["MAT4X2"] = 23] = "MAT4X2";
        Type[Type["MAT4X3"] = 24] = "MAT4X3";
        Type[Type["MAT4"] = 25] = "MAT4";
        Type[Type["SAMPLER1D"] = 26] = "SAMPLER1D";
        Type[Type["SAMPLER1D_ARRAY"] = 27] = "SAMPLER1D_ARRAY";
        Type[Type["SAMPLER2D"] = 28] = "SAMPLER2D";
        Type[Type["SAMPLER2D_ARRAY"] = 29] = "SAMPLER2D_ARRAY";
        Type[Type["SAMPLER3D"] = 30] = "SAMPLER3D";
        Type[Type["SAMPLER_CUBE"] = 31] = "SAMPLER_CUBE";
        Type[Type["SAMPLER"] = 32] = "SAMPLER";
        Type[Type["TEXTURE1D"] = 33] = "TEXTURE1D";
        Type[Type["TEXTURE1D_ARRAY"] = 34] = "TEXTURE1D_ARRAY";
        Type[Type["TEXTURE2D"] = 35] = "TEXTURE2D";
        Type[Type["TEXTURE2D_ARRAY"] = 36] = "TEXTURE2D_ARRAY";
        Type[Type["TEXTURE3D"] = 37] = "TEXTURE3D";
        Type[Type["TEXTURE_CUBE"] = 38] = "TEXTURE_CUBE";
        Type[Type["IMAGE1D"] = 39] = "IMAGE1D";
        Type[Type["IMAGE1D_ARRAY"] = 40] = "IMAGE1D_ARRAY";
        Type[Type["IMAGE2D"] = 41] = "IMAGE2D";
        Type[Type["IMAGE2D_ARRAY"] = 42] = "IMAGE2D_ARRAY";
        Type[Type["IMAGE3D"] = 43] = "IMAGE3D";
        Type[Type["IMAGE_CUBE"] = 44] = "IMAGE_CUBE";
        Type[Type["SUBPASS_INPUT"] = 45] = "SUBPASS_INPUT";
        Type[Type["COUNT"] = 46] = "COUNT";
      })(Type$1 || (Type$1 = {}));
      var BufferUsageBit;
      (function (BufferUsageBit) {
        BufferUsageBit[BufferUsageBit["NONE"] = 0] = "NONE";
        BufferUsageBit[BufferUsageBit["TRANSFER_SRC"] = 1] = "TRANSFER_SRC";
        BufferUsageBit[BufferUsageBit["TRANSFER_DST"] = 2] = "TRANSFER_DST";
        BufferUsageBit[BufferUsageBit["INDEX"] = 4] = "INDEX";
        BufferUsageBit[BufferUsageBit["VERTEX"] = 8] = "VERTEX";
        BufferUsageBit[BufferUsageBit["UNIFORM"] = 16] = "UNIFORM";
        BufferUsageBit[BufferUsageBit["STORAGE"] = 32] = "STORAGE";
        BufferUsageBit[BufferUsageBit["INDIRECT"] = 64] = "INDIRECT";
      })(BufferUsageBit || (BufferUsageBit = {}));
      var BufferFlagBit;
      (function (BufferFlagBit) {
        BufferFlagBit[BufferFlagBit["NONE"] = 0] = "NONE";
      })(BufferFlagBit || (BufferFlagBit = {}));
      var MemoryAccessBit;
      (function (MemoryAccessBit) {
        MemoryAccessBit[MemoryAccessBit["NONE"] = 0] = "NONE";
        MemoryAccessBit[MemoryAccessBit["READ_ONLY"] = 1] = "READ_ONLY";
        MemoryAccessBit[MemoryAccessBit["WRITE_ONLY"] = 2] = "WRITE_ONLY";
        MemoryAccessBit[MemoryAccessBit["READ_WRITE"] = 3] = "READ_WRITE";
      })(MemoryAccessBit || (MemoryAccessBit = {}));
      var MemoryUsageBit;
      (function (MemoryUsageBit) {
        MemoryUsageBit[MemoryUsageBit["NONE"] = 0] = "NONE";
        MemoryUsageBit[MemoryUsageBit["DEVICE"] = 1] = "DEVICE";
        MemoryUsageBit[MemoryUsageBit["HOST"] = 2] = "HOST";
      })(MemoryUsageBit || (MemoryUsageBit = {}));
      var TextureType;
      (function (TextureType) {
        TextureType[TextureType["TEX1D"] = 0] = "TEX1D";
        TextureType[TextureType["TEX2D"] = 1] = "TEX2D";
        TextureType[TextureType["TEX3D"] = 2] = "TEX3D";
        TextureType[TextureType["CUBE"] = 3] = "CUBE";
        TextureType[TextureType["TEX1D_ARRAY"] = 4] = "TEX1D_ARRAY";
        TextureType[TextureType["TEX2D_ARRAY"] = 5] = "TEX2D_ARRAY";
      })(TextureType || (TextureType = {}));
      var TextureUsageBit;
      (function (TextureUsageBit) {
        TextureUsageBit[TextureUsageBit["NONE"] = 0] = "NONE";
        TextureUsageBit[TextureUsageBit["TRANSFER_SRC"] = 1] = "TRANSFER_SRC";
        TextureUsageBit[TextureUsageBit["TRANSFER_DST"] = 2] = "TRANSFER_DST";
        TextureUsageBit[TextureUsageBit["SAMPLED"] = 4] = "SAMPLED";
        TextureUsageBit[TextureUsageBit["STORAGE"] = 8] = "STORAGE";
        TextureUsageBit[TextureUsageBit["COLOR_ATTACHMENT"] = 16] = "COLOR_ATTACHMENT";
        TextureUsageBit[TextureUsageBit["DEPTH_STENCIL_ATTACHMENT"] = 32] = "DEPTH_STENCIL_ATTACHMENT";
        TextureUsageBit[TextureUsageBit["INPUT_ATTACHMENT"] = 64] = "INPUT_ATTACHMENT";
      })(TextureUsageBit || (TextureUsageBit = {}));
      var TextureFlagBit;
      (function (TextureFlagBit) {
        TextureFlagBit[TextureFlagBit["NONE"] = 0] = "NONE";
        TextureFlagBit[TextureFlagBit["GEN_MIPMAP"] = 1] = "GEN_MIPMAP";
        TextureFlagBit[TextureFlagBit["GENERAL_LAYOUT"] = 2] = "GENERAL_LAYOUT";
        TextureFlagBit[TextureFlagBit["EXTERNAL_OES"] = 4] = "EXTERNAL_OES";
        TextureFlagBit[TextureFlagBit["EXTERNAL_NORMAL"] = 8] = "EXTERNAL_NORMAL";
        TextureFlagBit[TextureFlagBit["LAZILY_ALLOCATED"] = 16] = "LAZILY_ALLOCATED";
        TextureFlagBit[TextureFlagBit["MUTABLE_VIEW_FORMAT"] = 64] = "MUTABLE_VIEW_FORMAT";
      })(TextureFlagBit || (TextureFlagBit = {}));
      var FormatFeatureBit;
      (function (FormatFeatureBit) {
        FormatFeatureBit[FormatFeatureBit["NONE"] = 0] = "NONE";
        FormatFeatureBit[FormatFeatureBit["RENDER_TARGET"] = 1] = "RENDER_TARGET";
        FormatFeatureBit[FormatFeatureBit["SAMPLED_TEXTURE"] = 2] = "SAMPLED_TEXTURE";
        FormatFeatureBit[FormatFeatureBit["LINEAR_FILTER"] = 4] = "LINEAR_FILTER";
        FormatFeatureBit[FormatFeatureBit["STORAGE_TEXTURE"] = 8] = "STORAGE_TEXTURE";
        FormatFeatureBit[FormatFeatureBit["VERTEX_ATTRIBUTE"] = 16] = "VERTEX_ATTRIBUTE";
      })(FormatFeatureBit || (FormatFeatureBit = {}));
      var SampleCount;
      (function (SampleCount) {
        SampleCount[SampleCount["X1"] = 1] = "X1";
        SampleCount[SampleCount["X2"] = 2] = "X2";
        SampleCount[SampleCount["X4"] = 4] = "X4";
        SampleCount[SampleCount["X8"] = 8] = "X8";
        SampleCount[SampleCount["X16"] = 16] = "X16";
        SampleCount[SampleCount["X32"] = 32] = "X32";
        SampleCount[SampleCount["X64"] = 64] = "X64";
      })(SampleCount || (SampleCount = {}));
      var VsyncMode;
      (function (VsyncMode) {
        VsyncMode[VsyncMode["OFF"] = 0] = "OFF";
        VsyncMode[VsyncMode["ON"] = 1] = "ON";
        VsyncMode[VsyncMode["RELAXED"] = 2] = "RELAXED";
        VsyncMode[VsyncMode["MAILBOX"] = 3] = "MAILBOX";
        VsyncMode[VsyncMode["HALF"] = 4] = "HALF";
      })(VsyncMode || (VsyncMode = {}));
      var Filter$1;
      (function (Filter) {
        Filter[Filter["NONE"] = 0] = "NONE";
        Filter[Filter["POINT"] = 1] = "POINT";
        Filter[Filter["LINEAR"] = 2] = "LINEAR";
        Filter[Filter["ANISOTROPIC"] = 3] = "ANISOTROPIC";
      })(Filter$1 || (Filter$1 = {}));
      var Address;
      (function (Address) {
        Address[Address["WRAP"] = 0] = "WRAP";
        Address[Address["MIRROR"] = 1] = "MIRROR";
        Address[Address["CLAMP"] = 2] = "CLAMP";
        Address[Address["BORDER"] = 3] = "BORDER";
      })(Address || (Address = {}));
      var ComparisonFunc;
      (function (ComparisonFunc) {
        ComparisonFunc[ComparisonFunc["NEVER"] = 0] = "NEVER";
        ComparisonFunc[ComparisonFunc["LESS"] = 1] = "LESS";
        ComparisonFunc[ComparisonFunc["EQUAL"] = 2] = "EQUAL";
        ComparisonFunc[ComparisonFunc["LESS_EQUAL"] = 3] = "LESS_EQUAL";
        ComparisonFunc[ComparisonFunc["GREATER"] = 4] = "GREATER";
        ComparisonFunc[ComparisonFunc["NOT_EQUAL"] = 5] = "NOT_EQUAL";
        ComparisonFunc[ComparisonFunc["GREATER_EQUAL"] = 6] = "GREATER_EQUAL";
        ComparisonFunc[ComparisonFunc["ALWAYS"] = 7] = "ALWAYS";
      })(ComparisonFunc || (ComparisonFunc = {}));
      var StencilOp;
      (function (StencilOp) {
        StencilOp[StencilOp["ZERO"] = 0] = "ZERO";
        StencilOp[StencilOp["KEEP"] = 1] = "KEEP";
        StencilOp[StencilOp["REPLACE"] = 2] = "REPLACE";
        StencilOp[StencilOp["INCR"] = 3] = "INCR";
        StencilOp[StencilOp["DECR"] = 4] = "DECR";
        StencilOp[StencilOp["INVERT"] = 5] = "INVERT";
        StencilOp[StencilOp["INCR_WRAP"] = 6] = "INCR_WRAP";
        StencilOp[StencilOp["DECR_WRAP"] = 7] = "DECR_WRAP";
      })(StencilOp || (StencilOp = {}));
      var BlendFactor;
      (function (BlendFactor) {
        BlendFactor[BlendFactor["ZERO"] = 0] = "ZERO";
        BlendFactor[BlendFactor["ONE"] = 1] = "ONE";
        BlendFactor[BlendFactor["SRC_ALPHA"] = 2] = "SRC_ALPHA";
        BlendFactor[BlendFactor["DST_ALPHA"] = 3] = "DST_ALPHA";
        BlendFactor[BlendFactor["ONE_MINUS_SRC_ALPHA"] = 4] = "ONE_MINUS_SRC_ALPHA";
        BlendFactor[BlendFactor["ONE_MINUS_DST_ALPHA"] = 5] = "ONE_MINUS_DST_ALPHA";
        BlendFactor[BlendFactor["SRC_COLOR"] = 6] = "SRC_COLOR";
        BlendFactor[BlendFactor["DST_COLOR"] = 7] = "DST_COLOR";
        BlendFactor[BlendFactor["ONE_MINUS_SRC_COLOR"] = 8] = "ONE_MINUS_SRC_COLOR";
        BlendFactor[BlendFactor["ONE_MINUS_DST_COLOR"] = 9] = "ONE_MINUS_DST_COLOR";
        BlendFactor[BlendFactor["SRC_ALPHA_SATURATE"] = 10] = "SRC_ALPHA_SATURATE";
        BlendFactor[BlendFactor["CONSTANT_COLOR"] = 11] = "CONSTANT_COLOR";
        BlendFactor[BlendFactor["ONE_MINUS_CONSTANT_COLOR"] = 12] = "ONE_MINUS_CONSTANT_COLOR";
        BlendFactor[BlendFactor["CONSTANT_ALPHA"] = 13] = "CONSTANT_ALPHA";
        BlendFactor[BlendFactor["ONE_MINUS_CONSTANT_ALPHA"] = 14] = "ONE_MINUS_CONSTANT_ALPHA";
      })(BlendFactor || (BlendFactor = {}));
      var BlendOp;
      (function (BlendOp) {
        BlendOp[BlendOp["ADD"] = 0] = "ADD";
        BlendOp[BlendOp["SUB"] = 1] = "SUB";
        BlendOp[BlendOp["REV_SUB"] = 2] = "REV_SUB";
        BlendOp[BlendOp["MIN"] = 3] = "MIN";
        BlendOp[BlendOp["MAX"] = 4] = "MAX";
      })(BlendOp || (BlendOp = {}));
      var ColorMask;
      (function (ColorMask) {
        ColorMask[ColorMask["NONE"] = 0] = "NONE";
        ColorMask[ColorMask["R"] = 1] = "R";
        ColorMask[ColorMask["G"] = 2] = "G";
        ColorMask[ColorMask["B"] = 4] = "B";
        ColorMask[ColorMask["A"] = 8] = "A";
        ColorMask[ColorMask["ALL"] = 15] = "ALL";
      })(ColorMask || (ColorMask = {}));
      var ShaderStageFlagBit;
      (function (ShaderStageFlagBit) {
        ShaderStageFlagBit[ShaderStageFlagBit["NONE"] = 0] = "NONE";
        ShaderStageFlagBit[ShaderStageFlagBit["VERTEX"] = 1] = "VERTEX";
        ShaderStageFlagBit[ShaderStageFlagBit["CONTROL"] = 2] = "CONTROL";
        ShaderStageFlagBit[ShaderStageFlagBit["EVALUATION"] = 4] = "EVALUATION";
        ShaderStageFlagBit[ShaderStageFlagBit["GEOMETRY"] = 8] = "GEOMETRY";
        ShaderStageFlagBit[ShaderStageFlagBit["FRAGMENT"] = 16] = "FRAGMENT";
        ShaderStageFlagBit[ShaderStageFlagBit["COMPUTE"] = 32] = "COMPUTE";
        ShaderStageFlagBit[ShaderStageFlagBit["ALL"] = 63] = "ALL";
      })(ShaderStageFlagBit || (ShaderStageFlagBit = {}));
      var LoadOp;
      (function (LoadOp) {
        LoadOp[LoadOp["LOAD"] = 0] = "LOAD";
        LoadOp[LoadOp["CLEAR"] = 1] = "CLEAR";
        LoadOp[LoadOp["DISCARD"] = 2] = "DISCARD";
      })(LoadOp || (LoadOp = {}));
      var StoreOp;
      (function (StoreOp) {
        StoreOp[StoreOp["STORE"] = 0] = "STORE";
        StoreOp[StoreOp["DISCARD"] = 1] = "DISCARD";
      })(StoreOp || (StoreOp = {}));
      var AccessFlagBit;
      (function (AccessFlagBit) {
        AccessFlagBit[AccessFlagBit["NONE"] = 0] = "NONE";
        AccessFlagBit[AccessFlagBit["INDIRECT_BUFFER"] = 1] = "INDIRECT_BUFFER";
        AccessFlagBit[AccessFlagBit["INDEX_BUFFER"] = 2] = "INDEX_BUFFER";
        AccessFlagBit[AccessFlagBit["VERTEX_BUFFER"] = 4] = "VERTEX_BUFFER";
        AccessFlagBit[AccessFlagBit["VERTEX_SHADER_READ_UNIFORM_BUFFER"] = 8] = "VERTEX_SHADER_READ_UNIFORM_BUFFER";
        AccessFlagBit[AccessFlagBit["VERTEX_SHADER_READ_TEXTURE"] = 16] = "VERTEX_SHADER_READ_TEXTURE";
        AccessFlagBit[AccessFlagBit["VERTEX_SHADER_READ_OTHER"] = 32] = "VERTEX_SHADER_READ_OTHER";
        AccessFlagBit[AccessFlagBit["FRAGMENT_SHADER_READ_UNIFORM_BUFFER"] = 64] = "FRAGMENT_SHADER_READ_UNIFORM_BUFFER";
        AccessFlagBit[AccessFlagBit["FRAGMENT_SHADER_READ_TEXTURE"] = 128] = "FRAGMENT_SHADER_READ_TEXTURE";
        AccessFlagBit[AccessFlagBit["FRAGMENT_SHADER_READ_COLOR_INPUT_ATTACHMENT"] = 256] = "FRAGMENT_SHADER_READ_COLOR_INPUT_ATTACHMENT";
        AccessFlagBit[AccessFlagBit["FRAGMENT_SHADER_READ_DEPTH_STENCIL_INPUT_ATTACHMENT"] = 512] = "FRAGMENT_SHADER_READ_DEPTH_STENCIL_INPUT_ATTACHMENT";
        AccessFlagBit[AccessFlagBit["FRAGMENT_SHADER_READ_OTHER"] = 1024] = "FRAGMENT_SHADER_READ_OTHER";
        AccessFlagBit[AccessFlagBit["COLOR_ATTACHMENT_READ"] = 2048] = "COLOR_ATTACHMENT_READ";
        AccessFlagBit[AccessFlagBit["DEPTH_STENCIL_ATTACHMENT_READ"] = 4096] = "DEPTH_STENCIL_ATTACHMENT_READ";
        AccessFlagBit[AccessFlagBit["COMPUTE_SHADER_READ_UNIFORM_BUFFER"] = 8192] = "COMPUTE_SHADER_READ_UNIFORM_BUFFER";
        AccessFlagBit[AccessFlagBit["COMPUTE_SHADER_READ_TEXTURE"] = 16384] = "COMPUTE_SHADER_READ_TEXTURE";
        AccessFlagBit[AccessFlagBit["COMPUTE_SHADER_READ_OTHER"] = 32768] = "COMPUTE_SHADER_READ_OTHER";
        AccessFlagBit[AccessFlagBit["TRANSFER_READ"] = 65536] = "TRANSFER_READ";
        AccessFlagBit[AccessFlagBit["HOST_READ"] = 131072] = "HOST_READ";
        AccessFlagBit[AccessFlagBit["PRESENT"] = 262144] = "PRESENT";
        AccessFlagBit[AccessFlagBit["VERTEX_SHADER_WRITE"] = 524288] = "VERTEX_SHADER_WRITE";
        AccessFlagBit[AccessFlagBit["FRAGMENT_SHADER_WRITE"] = 1048576] = "FRAGMENT_SHADER_WRITE";
        AccessFlagBit[AccessFlagBit["COLOR_ATTACHMENT_WRITE"] = 2097152] = "COLOR_ATTACHMENT_WRITE";
        AccessFlagBit[AccessFlagBit["DEPTH_STENCIL_ATTACHMENT_WRITE"] = 4194304] = "DEPTH_STENCIL_ATTACHMENT_WRITE";
        AccessFlagBit[AccessFlagBit["COMPUTE_SHADER_WRITE"] = 8388608] = "COMPUTE_SHADER_WRITE";
        AccessFlagBit[AccessFlagBit["TRANSFER_WRITE"] = 16777216] = "TRANSFER_WRITE";
        AccessFlagBit[AccessFlagBit["HOST_PREINITIALIZED"] = 33554432] = "HOST_PREINITIALIZED";
        AccessFlagBit[AccessFlagBit["HOST_WRITE"] = 67108864] = "HOST_WRITE";
      })(AccessFlagBit || (AccessFlagBit = {}));
      var ResolveMode;
      (function (ResolveMode) {
        ResolveMode[ResolveMode["NONE"] = 0] = "NONE";
        ResolveMode[ResolveMode["SAMPLE_ZERO"] = 1] = "SAMPLE_ZERO";
        ResolveMode[ResolveMode["AVERAGE"] = 2] = "AVERAGE";
        ResolveMode[ResolveMode["MIN"] = 3] = "MIN";
        ResolveMode[ResolveMode["MAX"] = 4] = "MAX";
      })(ResolveMode || (ResolveMode = {}));
      var PipelineBindPoint;
      (function (PipelineBindPoint) {
        PipelineBindPoint[PipelineBindPoint["GRAPHICS"] = 0] = "GRAPHICS";
        PipelineBindPoint[PipelineBindPoint["COMPUTE"] = 1] = "COMPUTE";
        PipelineBindPoint[PipelineBindPoint["RAY_TRACING"] = 2] = "RAY_TRACING";
      })(PipelineBindPoint || (PipelineBindPoint = {}));
      var PrimitiveMode;
      (function (PrimitiveMode) {
        PrimitiveMode[PrimitiveMode["POINT_LIST"] = 0] = "POINT_LIST";
        PrimitiveMode[PrimitiveMode["LINE_LIST"] = 1] = "LINE_LIST";
        PrimitiveMode[PrimitiveMode["LINE_STRIP"] = 2] = "LINE_STRIP";
        PrimitiveMode[PrimitiveMode["LINE_LOOP"] = 3] = "LINE_LOOP";
        PrimitiveMode[PrimitiveMode["LINE_LIST_ADJACENCY"] = 4] = "LINE_LIST_ADJACENCY";
        PrimitiveMode[PrimitiveMode["LINE_STRIP_ADJACENCY"] = 5] = "LINE_STRIP_ADJACENCY";
        PrimitiveMode[PrimitiveMode["ISO_LINE_LIST"] = 6] = "ISO_LINE_LIST";
        PrimitiveMode[PrimitiveMode["TRIANGLE_LIST"] = 7] = "TRIANGLE_LIST";
        PrimitiveMode[PrimitiveMode["TRIANGLE_STRIP"] = 8] = "TRIANGLE_STRIP";
        PrimitiveMode[PrimitiveMode["TRIANGLE_FAN"] = 9] = "TRIANGLE_FAN";
        PrimitiveMode[PrimitiveMode["TRIANGLE_LIST_ADJACENCY"] = 10] = "TRIANGLE_LIST_ADJACENCY";
        PrimitiveMode[PrimitiveMode["TRIANGLE_STRIP_ADJACENCY"] = 11] = "TRIANGLE_STRIP_ADJACENCY";
        PrimitiveMode[PrimitiveMode["TRIANGLE_PATCH_ADJACENCY"] = 12] = "TRIANGLE_PATCH_ADJACENCY";
        PrimitiveMode[PrimitiveMode["QUAD_PATCH_LIST"] = 13] = "QUAD_PATCH_LIST";
      })(PrimitiveMode || (PrimitiveMode = {}));
      var PolygonMode;
      (function (PolygonMode) {
        PolygonMode[PolygonMode["FILL"] = 0] = "FILL";
        PolygonMode[PolygonMode["POINT"] = 1] = "POINT";
        PolygonMode[PolygonMode["LINE"] = 2] = "LINE";
      })(PolygonMode || (PolygonMode = {}));
      var ShadeModel;
      (function (ShadeModel) {
        ShadeModel[ShadeModel["GOURAND"] = 0] = "GOURAND";
        ShadeModel[ShadeModel["FLAT"] = 1] = "FLAT";
      })(ShadeModel || (ShadeModel = {}));
      var CullMode;
      (function (CullMode) {
        CullMode[CullMode["NONE"] = 0] = "NONE";
        CullMode[CullMode["FRONT"] = 1] = "FRONT";
        CullMode[CullMode["BACK"] = 2] = "BACK";
      })(CullMode || (CullMode = {}));
      var DynamicStateFlagBit;
      (function (DynamicStateFlagBit) {
        DynamicStateFlagBit[DynamicStateFlagBit["NONE"] = 0] = "NONE";
        DynamicStateFlagBit[DynamicStateFlagBit["LINE_WIDTH"] = 1] = "LINE_WIDTH";
        DynamicStateFlagBit[DynamicStateFlagBit["DEPTH_BIAS"] = 2] = "DEPTH_BIAS";
        DynamicStateFlagBit[DynamicStateFlagBit["BLEND_CONSTANTS"] = 4] = "BLEND_CONSTANTS";
        DynamicStateFlagBit[DynamicStateFlagBit["DEPTH_BOUNDS"] = 8] = "DEPTH_BOUNDS";
        DynamicStateFlagBit[DynamicStateFlagBit["STENCIL_WRITE_MASK"] = 16] = "STENCIL_WRITE_MASK";
        DynamicStateFlagBit[DynamicStateFlagBit["STENCIL_COMPARE_MASK"] = 32] = "STENCIL_COMPARE_MASK";
      })(DynamicStateFlagBit || (DynamicStateFlagBit = {}));
      var StencilFace;
      (function (StencilFace) {
        StencilFace[StencilFace["FRONT"] = 1] = "FRONT";
        StencilFace[StencilFace["BACK"] = 2] = "BACK";
        StencilFace[StencilFace["ALL"] = 3] = "ALL";
      })(StencilFace || (StencilFace = {}));
      var DescriptorType;
      (function (DescriptorType) {
        DescriptorType[DescriptorType["UNKNOWN"] = 0] = "UNKNOWN";
        DescriptorType[DescriptorType["UNIFORM_BUFFER"] = 1] = "UNIFORM_BUFFER";
        DescriptorType[DescriptorType["DYNAMIC_UNIFORM_BUFFER"] = 2] = "DYNAMIC_UNIFORM_BUFFER";
        DescriptorType[DescriptorType["STORAGE_BUFFER"] = 4] = "STORAGE_BUFFER";
        DescriptorType[DescriptorType["DYNAMIC_STORAGE_BUFFER"] = 8] = "DYNAMIC_STORAGE_BUFFER";
        DescriptorType[DescriptorType["SAMPLER_TEXTURE"] = 16] = "SAMPLER_TEXTURE";
        DescriptorType[DescriptorType["SAMPLER"] = 32] = "SAMPLER";
        DescriptorType[DescriptorType["TEXTURE"] = 64] = "TEXTURE";
        DescriptorType[DescriptorType["STORAGE_IMAGE"] = 128] = "STORAGE_IMAGE";
        DescriptorType[DescriptorType["INPUT_ATTACHMENT"] = 256] = "INPUT_ATTACHMENT";
      })(DescriptorType || (DescriptorType = {}));
      var QueueType;
      (function (QueueType) {
        QueueType[QueueType["GRAPHICS"] = 0] = "GRAPHICS";
        QueueType[QueueType["COMPUTE"] = 1] = "COMPUTE";
        QueueType[QueueType["TRANSFER"] = 2] = "TRANSFER";
      })(QueueType || (QueueType = {}));
      var QueryType;
      (function (QueryType) {
        QueryType[QueryType["OCCLUSION"] = 0] = "OCCLUSION";
        QueryType[QueryType["PIPELINE_STATISTICS"] = 1] = "PIPELINE_STATISTICS";
        QueryType[QueryType["TIMESTAMP"] = 2] = "TIMESTAMP";
      })(QueryType || (QueryType = {}));
      var CommandBufferType;
      (function (CommandBufferType) {
        CommandBufferType[CommandBufferType["PRIMARY"] = 0] = "PRIMARY";
        CommandBufferType[CommandBufferType["SECONDARY"] = 1] = "SECONDARY";
      })(CommandBufferType || (CommandBufferType = {}));
      var ClearFlagBit;
      (function (ClearFlagBit) {
        ClearFlagBit[ClearFlagBit["NONE"] = 0] = "NONE";
        ClearFlagBit[ClearFlagBit["COLOR"] = 1] = "COLOR";
        ClearFlagBit[ClearFlagBit["DEPTH"] = 2] = "DEPTH";
        ClearFlagBit[ClearFlagBit["STENCIL"] = 4] = "STENCIL";
        ClearFlagBit[ClearFlagBit["DEPTH_STENCIL"] = 6] = "DEPTH_STENCIL";
        ClearFlagBit[ClearFlagBit["ALL"] = 7] = "ALL";
      })(ClearFlagBit || (ClearFlagBit = {}));
      var BarrierType;
      (function (BarrierType) {
        BarrierType[BarrierType["FULL"] = 0] = "FULL";
        BarrierType[BarrierType["SPLIT_BEGIN"] = 1] = "SPLIT_BEGIN";
        BarrierType[BarrierType["SPLIT_END"] = 2] = "SPLIT_END";
      })(BarrierType || (BarrierType = {}));
      var PassType;
      (function (PassType) {
        PassType[PassType["RASTER"] = 0] = "RASTER";
        PassType[PassType["COMPUTE"] = 1] = "COMPUTE";
        PassType[PassType["COPY"] = 2] = "COPY";
        PassType[PassType["MOVE"] = 3] = "MOVE";
        PassType[PassType["RAYTRACE"] = 4] = "RAYTRACE";
        PassType[PassType["PRESENT"] = 5] = "PRESENT";
      })(PassType || (PassType = {}));
      var Size = function () {
        function Size(x, y, z) {
          if (x === void 0) {
            x = 0;
          }
          if (y === void 0) {
            y = 0;
          }
          if (z === void 0) {
            z = 0;
          }
          this.x = x;
          this.y = y;
          this.z = z;
        }
        var _proto = Size.prototype;
        _proto.copy = function copy(info) {
          this.x = info.x;
          this.y = info.y;
          this.z = info.z;
          return this;
        };
        return Size;
      }();
      var DeviceCaps = function () {
        function DeviceCaps(maxVertexAttributes, maxVertexUniformVectors, maxFragmentUniformVectors, maxTextureUnits, maxImageUnits, maxVertexTextureUnits, maxColorRenderTargets, maxShaderStorageBufferBindings, maxShaderStorageBlockSize, maxUniformBufferBindings, maxUniformBlockSize, maxTextureSize, maxCubeMapTextureSize, maxArrayTextureLayers, max3DTextureSize, uboOffsetAlignment, maxComputeSharedMemorySize, maxComputeWorkGroupInvocations, maxComputeWorkGroupSize, maxComputeWorkGroupCount, supportQuery, clipSpaceMinZ, screenSpaceSignY, clipSpaceSignY) {
          if (maxVertexAttributes === void 0) {
            maxVertexAttributes = 0;
          }
          if (maxVertexUniformVectors === void 0) {
            maxVertexUniformVectors = 0;
          }
          if (maxFragmentUniformVectors === void 0) {
            maxFragmentUniformVectors = 0;
          }
          if (maxTextureUnits === void 0) {
            maxTextureUnits = 0;
          }
          if (maxImageUnits === void 0) {
            maxImageUnits = 0;
          }
          if (maxVertexTextureUnits === void 0) {
            maxVertexTextureUnits = 0;
          }
          if (maxColorRenderTargets === void 0) {
            maxColorRenderTargets = 0;
          }
          if (maxShaderStorageBufferBindings === void 0) {
            maxShaderStorageBufferBindings = 0;
          }
          if (maxShaderStorageBlockSize === void 0) {
            maxShaderStorageBlockSize = 0;
          }
          if (maxUniformBufferBindings === void 0) {
            maxUniformBufferBindings = 0;
          }
          if (maxUniformBlockSize === void 0) {
            maxUniformBlockSize = 0;
          }
          if (maxTextureSize === void 0) {
            maxTextureSize = 0;
          }
          if (maxCubeMapTextureSize === void 0) {
            maxCubeMapTextureSize = 0;
          }
          if (maxArrayTextureLayers === void 0) {
            maxArrayTextureLayers = 0;
          }
          if (max3DTextureSize === void 0) {
            max3DTextureSize = 0;
          }
          if (uboOffsetAlignment === void 0) {
            uboOffsetAlignment = 1;
          }
          if (maxComputeSharedMemorySize === void 0) {
            maxComputeSharedMemorySize = 0;
          }
          if (maxComputeWorkGroupInvocations === void 0) {
            maxComputeWorkGroupInvocations = 0;
          }
          if (maxComputeWorkGroupSize === void 0) {
            maxComputeWorkGroupSize = new Size();
          }
          if (maxComputeWorkGroupCount === void 0) {
            maxComputeWorkGroupCount = new Size();
          }
          if (supportQuery === void 0) {
            supportQuery = false;
          }
          if (clipSpaceMinZ === void 0) {
            clipSpaceMinZ = -1;
          }
          if (screenSpaceSignY === void 0) {
            screenSpaceSignY = 1;
          }
          if (clipSpaceSignY === void 0) {
            clipSpaceSignY = 1;
          }
          this.maxVertexAttributes = maxVertexAttributes;
          this.maxVertexUniformVectors = maxVertexUniformVectors;
          this.maxFragmentUniformVectors = maxFragmentUniformVectors;
          this.maxTextureUnits = maxTextureUnits;
          this.maxImageUnits = maxImageUnits;
          this.maxVertexTextureUnits = maxVertexTextureUnits;
          this.maxColorRenderTargets = maxColorRenderTargets;
          this.maxShaderStorageBufferBindings = maxShaderStorageBufferBindings;
          this.maxShaderStorageBlockSize = maxShaderStorageBlockSize;
          this.maxUniformBufferBindings = maxUniformBufferBindings;
          this.maxUniformBlockSize = maxUniformBlockSize;
          this.maxTextureSize = maxTextureSize;
          this.maxCubeMapTextureSize = maxCubeMapTextureSize;
          this.maxArrayTextureLayers = maxArrayTextureLayers;
          this.max3DTextureSize = max3DTextureSize;
          this.uboOffsetAlignment = uboOffsetAlignment;
          this.maxComputeSharedMemorySize = maxComputeSharedMemorySize;
          this.maxComputeWorkGroupInvocations = maxComputeWorkGroupInvocations;
          this.maxComputeWorkGroupSize = maxComputeWorkGroupSize;
          this.maxComputeWorkGroupCount = maxComputeWorkGroupCount;
          this.supportQuery = supportQuery;
          this.clipSpaceMinZ = clipSpaceMinZ;
          this.screenSpaceSignY = screenSpaceSignY;
          this.clipSpaceSignY = clipSpaceSignY;
        }
        var _proto2 = DeviceCaps.prototype;
        _proto2.copy = function copy(info) {
          this.maxVertexAttributes = info.maxVertexAttributes;
          this.maxVertexUniformVectors = info.maxVertexUniformVectors;
          this.maxFragmentUniformVectors = info.maxFragmentUniformVectors;
          this.maxTextureUnits = info.maxTextureUnits;
          this.maxImageUnits = info.maxImageUnits;
          this.maxVertexTextureUnits = info.maxVertexTextureUnits;
          this.maxColorRenderTargets = info.maxColorRenderTargets;
          this.maxShaderStorageBufferBindings = info.maxShaderStorageBufferBindings;
          this.maxShaderStorageBlockSize = info.maxShaderStorageBlockSize;
          this.maxUniformBufferBindings = info.maxUniformBufferBindings;
          this.maxUniformBlockSize = info.maxUniformBlockSize;
          this.maxTextureSize = info.maxTextureSize;
          this.maxCubeMapTextureSize = info.maxCubeMapTextureSize;
          this.maxArrayTextureLayers = info.maxArrayTextureLayers;
          this.max3DTextureSize = info.max3DTextureSize;
          this.uboOffsetAlignment = info.uboOffsetAlignment;
          this.maxComputeSharedMemorySize = info.maxComputeSharedMemorySize;
          this.maxComputeWorkGroupInvocations = info.maxComputeWorkGroupInvocations;
          this.maxComputeWorkGroupSize.copy(info.maxComputeWorkGroupSize);
          this.maxComputeWorkGroupCount.copy(info.maxComputeWorkGroupCount);
          this.supportQuery = info.supportQuery;
          this.clipSpaceMinZ = info.clipSpaceMinZ;
          this.screenSpaceSignY = info.screenSpaceSignY;
          this.clipSpaceSignY = info.clipSpaceSignY;
          return this;
        };
        return DeviceCaps;
      }();
      var DeviceOptions = function () {
        function DeviceOptions(enableBarrierDeduce) {
          if (enableBarrierDeduce === void 0) {
            enableBarrierDeduce = true;
          }
          this.enableBarrierDeduce = enableBarrierDeduce;
        }
        var _proto3 = DeviceOptions.prototype;
        _proto3.copy = function copy(info) {
          this.enableBarrierDeduce = info.enableBarrierDeduce;
          return this;
        };
        return DeviceOptions;
      }();
      var Offset = function () {
        function Offset(x, y, z) {
          if (x === void 0) {
            x = 0;
          }
          if (y === void 0) {
            y = 0;
          }
          if (z === void 0) {
            z = 0;
          }
          this.x = x;
          this.y = y;
          this.z = z;
        }
        var _proto4 = Offset.prototype;
        _proto4.copy = function copy(info) {
          this.x = info.x;
          this.y = info.y;
          this.z = info.z;
          return this;
        };
        return Offset;
      }();
      var Rect = function () {
        function Rect(x, y, width, height) {
          if (x === void 0) {
            x = 0;
          }
          if (y === void 0) {
            y = 0;
          }
          if (width === void 0) {
            width = 0;
          }
          if (height === void 0) {
            height = 0;
          }
          this.x = x;
          this.y = y;
          this.width = width;
          this.height = height;
        }
        var _proto5 = Rect.prototype;
        _proto5.copy = function copy(info) {
          this.x = info.x;
          this.y = info.y;
          this.width = info.width;
          this.height = info.height;
          return this;
        };
        return Rect;
      }();
      var Extent = function () {
        function Extent(width, height, depth) {
          if (width === void 0) {
            width = 0;
          }
          if (height === void 0) {
            height = 0;
          }
          if (depth === void 0) {
            depth = 1;
          }
          this.width = width;
          this.height = height;
          this.depth = depth;
        }
        var _proto6 = Extent.prototype;
        _proto6.copy = function copy(info) {
          this.width = info.width;
          this.height = info.height;
          this.depth = info.depth;
          return this;
        };
        return Extent;
      }();
      var TextureSubresLayers = function () {
        function TextureSubresLayers(mipLevel, baseArrayLayer, layerCount) {
          if (mipLevel === void 0) {
            mipLevel = 0;
          }
          if (baseArrayLayer === void 0) {
            baseArrayLayer = 0;
          }
          if (layerCount === void 0) {
            layerCount = 1;
          }
          this.mipLevel = mipLevel;
          this.baseArrayLayer = baseArrayLayer;
          this.layerCount = layerCount;
        }
        var _proto7 = TextureSubresLayers.prototype;
        _proto7.copy = function copy(info) {
          this.mipLevel = info.mipLevel;
          this.baseArrayLayer = info.baseArrayLayer;
          this.layerCount = info.layerCount;
          return this;
        };
        return TextureSubresLayers;
      }();
      var TextureSubresRange = function () {
        function TextureSubresRange(baseMipLevel, levelCount, baseArrayLayer, layerCount) {
          if (baseMipLevel === void 0) {
            baseMipLevel = 0;
          }
          if (levelCount === void 0) {
            levelCount = 1;
          }
          if (baseArrayLayer === void 0) {
            baseArrayLayer = 0;
          }
          if (layerCount === void 0) {
            layerCount = 1;
          }
          this.baseMipLevel = baseMipLevel;
          this.levelCount = levelCount;
          this.baseArrayLayer = baseArrayLayer;
          this.layerCount = layerCount;
        }
        var _proto8 = TextureSubresRange.prototype;
        _proto8.copy = function copy(info) {
          this.baseMipLevel = info.baseMipLevel;
          this.levelCount = info.levelCount;
          this.baseArrayLayer = info.baseArrayLayer;
          this.layerCount = info.layerCount;
          return this;
        };
        return TextureSubresRange;
      }();
      var TextureCopy = function () {
        function TextureCopy(srcSubres, srcOffset, dstSubres, dstOffset, extent) {
          if (srcSubres === void 0) {
            srcSubres = new TextureSubresLayers();
          }
          if (srcOffset === void 0) {
            srcOffset = new Offset();
          }
          if (dstSubres === void 0) {
            dstSubres = new TextureSubresLayers();
          }
          if (dstOffset === void 0) {
            dstOffset = new Offset();
          }
          if (extent === void 0) {
            extent = new Extent();
          }
          this.srcSubres = srcSubres;
          this.srcOffset = srcOffset;
          this.dstSubres = dstSubres;
          this.dstOffset = dstOffset;
          this.extent = extent;
        }
        var _proto9 = TextureCopy.prototype;
        _proto9.copy = function copy(info) {
          this.srcSubres.copy(info.srcSubres);
          this.srcOffset.copy(info.srcOffset);
          this.dstSubres.copy(info.dstSubres);
          this.dstOffset.copy(info.dstOffset);
          this.extent.copy(info.extent);
          return this;
        };
        return TextureCopy;
      }();
      var TextureBlit = function () {
        function TextureBlit(srcSubres, srcOffset, srcExtent, dstSubres, dstOffset, dstExtent) {
          if (srcSubres === void 0) {
            srcSubres = new TextureSubresLayers();
          }
          if (srcOffset === void 0) {
            srcOffset = new Offset();
          }
          if (srcExtent === void 0) {
            srcExtent = new Extent();
          }
          if (dstSubres === void 0) {
            dstSubres = new TextureSubresLayers();
          }
          if (dstOffset === void 0) {
            dstOffset = new Offset();
          }
          if (dstExtent === void 0) {
            dstExtent = new Extent();
          }
          this.srcSubres = srcSubres;
          this.srcOffset = srcOffset;
          this.srcExtent = srcExtent;
          this.dstSubres = dstSubres;
          this.dstOffset = dstOffset;
          this.dstExtent = dstExtent;
        }
        var _proto10 = TextureBlit.prototype;
        _proto10.copy = function copy(info) {
          this.srcSubres.copy(info.srcSubres);
          this.srcOffset.copy(info.srcOffset);
          this.srcExtent.copy(info.srcExtent);
          this.dstSubres.copy(info.dstSubres);
          this.dstOffset.copy(info.dstOffset);
          this.dstExtent.copy(info.dstExtent);
          return this;
        };
        return TextureBlit;
      }();
      var BufferTextureCopy = function () {
        function BufferTextureCopy(buffOffset, buffStride, buffTexHeight, texOffset, texExtent, texSubres) {
          if (buffOffset === void 0) {
            buffOffset = 0;
          }
          if (buffStride === void 0) {
            buffStride = 0;
          }
          if (buffTexHeight === void 0) {
            buffTexHeight = 0;
          }
          if (texOffset === void 0) {
            texOffset = new Offset();
          }
          if (texExtent === void 0) {
            texExtent = new Extent();
          }
          if (texSubres === void 0) {
            texSubres = new TextureSubresLayers();
          }
          this.buffOffset = buffOffset;
          this.buffStride = buffStride;
          this.buffTexHeight = buffTexHeight;
          this.texOffset = texOffset;
          this.texExtent = texExtent;
          this.texSubres = texSubres;
        }
        var _proto11 = BufferTextureCopy.prototype;
        _proto11.copy = function copy(info) {
          this.buffOffset = info.buffOffset;
          this.buffStride = info.buffStride;
          this.buffTexHeight = info.buffTexHeight;
          this.texOffset.copy(info.texOffset);
          this.texExtent.copy(info.texExtent);
          this.texSubres.copy(info.texSubres);
          return this;
        };
        return BufferTextureCopy;
      }();
      var Viewport = function () {
        function Viewport(left, top, width, height, minDepth, maxDepth) {
          if (left === void 0) {
            left = 0;
          }
          if (top === void 0) {
            top = 0;
          }
          if (width === void 0) {
            width = 0;
          }
          if (height === void 0) {
            height = 0;
          }
          if (minDepth === void 0) {
            minDepth = 0;
          }
          if (maxDepth === void 0) {
            maxDepth = 1;
          }
          this.left = left;
          this.top = top;
          this.width = width;
          this.height = height;
          this.minDepth = minDepth;
          this.maxDepth = maxDepth;
        }
        var _proto12 = Viewport.prototype;
        _proto12.copy = function copy(info) {
          this.left = info.left;
          this.top = info.top;
          this.width = info.width;
          this.height = info.height;
          this.minDepth = info.minDepth;
          this.maxDepth = info.maxDepth;
          return this;
        };
        return Viewport;
      }();
      var Color = function () {
        function Color(x, y, z, w) {
          if (x === void 0) {
            x = 0;
          }
          if (y === void 0) {
            y = 0;
          }
          if (z === void 0) {
            z = 0;
          }
          if (w === void 0) {
            w = 0;
          }
          this.x = x;
          this.y = y;
          this.z = z;
          this.w = w;
        }
        var _proto13 = Color.prototype;
        _proto13.copy = function copy(info) {
          this.x = info.x;
          this.y = info.y;
          this.z = info.z;
          this.w = info.w;
          return this;
        };
        _proto13.set = function set(x, y, z, w) {
          this.x = x;
          this.y = y;
          this.z = z;
          this.w = w;
          return this;
        };
        return Color;
      }();
      var BindingMappingInfo = function () {
        function BindingMappingInfo(maxBlockCounts, maxSamplerTextureCounts, maxSamplerCounts, maxTextureCounts, maxBufferCounts, maxImageCounts, maxSubpassInputCounts, setIndices) {
          if (maxBlockCounts === void 0) {
            maxBlockCounts = [0];
          }
          if (maxSamplerTextureCounts === void 0) {
            maxSamplerTextureCounts = [0];
          }
          if (maxSamplerCounts === void 0) {
            maxSamplerCounts = [0];
          }
          if (maxTextureCounts === void 0) {
            maxTextureCounts = [0];
          }
          if (maxBufferCounts === void 0) {
            maxBufferCounts = [0];
          }
          if (maxImageCounts === void 0) {
            maxImageCounts = [0];
          }
          if (maxSubpassInputCounts === void 0) {
            maxSubpassInputCounts = [0];
          }
          if (setIndices === void 0) {
            setIndices = [0];
          }
          this.maxBlockCounts = maxBlockCounts;
          this.maxSamplerTextureCounts = maxSamplerTextureCounts;
          this.maxSamplerCounts = maxSamplerCounts;
          this.maxTextureCounts = maxTextureCounts;
          this.maxBufferCounts = maxBufferCounts;
          this.maxImageCounts = maxImageCounts;
          this.maxSubpassInputCounts = maxSubpassInputCounts;
          this.setIndices = setIndices;
        }
        var _proto14 = BindingMappingInfo.prototype;
        _proto14.copy = function copy(info) {
          this.maxBlockCounts = info.maxBlockCounts.slice();
          this.maxSamplerTextureCounts = info.maxSamplerTextureCounts.slice();
          this.maxSamplerCounts = info.maxSamplerCounts.slice();
          this.maxTextureCounts = info.maxTextureCounts.slice();
          this.maxBufferCounts = info.maxBufferCounts.slice();
          this.maxImageCounts = info.maxImageCounts.slice();
          this.maxSubpassInputCounts = info.maxSubpassInputCounts.slice();
          this.setIndices = info.setIndices.slice();
          return this;
        };
        return BindingMappingInfo;
      }();
      var SwapchainInfo = function () {
        function SwapchainInfo(windowId, windowHandle, vsyncMode, width, height) {
          if (windowId === void 0) {
            windowId = 0;
          }
          if (windowHandle === void 0) {
            windowHandle = null;
          }
          if (vsyncMode === void 0) {
            vsyncMode = VsyncMode.ON;
          }
          if (width === void 0) {
            width = 0;
          }
          if (height === void 0) {
            height = 0;
          }
          this.windowId = windowId;
          this.windowHandle = windowHandle;
          this.vsyncMode = vsyncMode;
          this.width = width;
          this.height = height;
        }
        var _proto15 = SwapchainInfo.prototype;
        _proto15.copy = function copy(info) {
          this.windowId = info.windowId;
          this.windowHandle = info.windowHandle;
          this.vsyncMode = info.vsyncMode;
          this.width = info.width;
          this.height = info.height;
          return this;
        };
        return SwapchainInfo;
      }();
      var DeviceInfo = function () {
        function DeviceInfo(bindingMappingInfo) {
          if (bindingMappingInfo === void 0) {
            bindingMappingInfo = new BindingMappingInfo();
          }
          this.bindingMappingInfo = bindingMappingInfo;
        }
        var _proto16 = DeviceInfo.prototype;
        _proto16.copy = function copy(info) {
          this.bindingMappingInfo.copy(info.bindingMappingInfo);
          return this;
        };
        return DeviceInfo;
      }();
      var BufferInfo = function () {
        function BufferInfo(usage, memUsage, size, stride, flags) {
          if (usage === void 0) {
            usage = BufferUsageBit.NONE;
          }
          if (memUsage === void 0) {
            memUsage = MemoryUsageBit.NONE;
          }
          if (size === void 0) {
            size = 0;
          }
          if (stride === void 0) {
            stride = 1;
          }
          if (flags === void 0) {
            flags = BufferFlagBit.NONE;
          }
          this.usage = usage;
          this.memUsage = memUsage;
          this.size = size;
          this.stride = stride;
          this.flags = flags;
        }
        var _proto17 = BufferInfo.prototype;
        _proto17.copy = function copy(info) {
          this.usage = info.usage;
          this.memUsage = info.memUsage;
          this.size = info.size;
          this.stride = info.stride;
          this.flags = info.flags;
          return this;
        };
        return BufferInfo;
      }();
      var BufferViewInfo = function () {
        function BufferViewInfo(buffer, offset, range) {
          if (buffer === void 0) {
            buffer = null;
          }
          if (offset === void 0) {
            offset = 0;
          }
          if (range === void 0) {
            range = 0;
          }
          this.buffer = buffer;
          this.offset = offset;
          this.range = range;
        }
        var _proto18 = BufferViewInfo.prototype;
        _proto18.copy = function copy(info) {
          this.buffer = info.buffer;
          this.offset = info.offset;
          this.range = info.range;
          return this;
        };
        return BufferViewInfo;
      }();
      var DrawInfo = function () {
        function DrawInfo(vertexCount, firstVertex, indexCount, firstIndex, vertexOffset, instanceCount, firstInstance) {
          if (vertexCount === void 0) {
            vertexCount = 0;
          }
          if (firstVertex === void 0) {
            firstVertex = 0;
          }
          if (indexCount === void 0) {
            indexCount = 0;
          }
          if (firstIndex === void 0) {
            firstIndex = 0;
          }
          if (vertexOffset === void 0) {
            vertexOffset = 0;
          }
          if (instanceCount === void 0) {
            instanceCount = 0;
          }
          if (firstInstance === void 0) {
            firstInstance = 0;
          }
          this.vertexCount = vertexCount;
          this.firstVertex = firstVertex;
          this.indexCount = indexCount;
          this.firstIndex = firstIndex;
          this.vertexOffset = vertexOffset;
          this.instanceCount = instanceCount;
          this.firstInstance = firstInstance;
        }
        var _proto19 = DrawInfo.prototype;
        _proto19.copy = function copy(info) {
          this.vertexCount = info.vertexCount;
          this.firstVertex = info.firstVertex;
          this.indexCount = info.indexCount;
          this.firstIndex = info.firstIndex;
          this.vertexOffset = info.vertexOffset;
          this.instanceCount = info.instanceCount;
          this.firstInstance = info.firstInstance;
          return this;
        };
        return DrawInfo;
      }();
      var DispatchInfo = function () {
        function DispatchInfo(groupCountX, groupCountY, groupCountZ, indirectBuffer, indirectOffset) {
          if (groupCountX === void 0) {
            groupCountX = 0;
          }
          if (groupCountY === void 0) {
            groupCountY = 0;
          }
          if (groupCountZ === void 0) {
            groupCountZ = 0;
          }
          if (indirectBuffer === void 0) {
            indirectBuffer = null;
          }
          if (indirectOffset === void 0) {
            indirectOffset = 0;
          }
          this.groupCountX = groupCountX;
          this.groupCountY = groupCountY;
          this.groupCountZ = groupCountZ;
          this.indirectBuffer = indirectBuffer;
          this.indirectOffset = indirectOffset;
        }
        var _proto20 = DispatchInfo.prototype;
        _proto20.copy = function copy(info) {
          this.groupCountX = info.groupCountX;
          this.groupCountY = info.groupCountY;
          this.groupCountZ = info.groupCountZ;
          this.indirectBuffer = info.indirectBuffer;
          this.indirectOffset = info.indirectOffset;
          return this;
        };
        return DispatchInfo;
      }();
      var IndirectBuffer = function () {
        function IndirectBuffer(drawInfos) {
          if (drawInfos === void 0) {
            drawInfos = [];
          }
          this.drawInfos = drawInfos;
        }
        var _proto21 = IndirectBuffer.prototype;
        _proto21.copy = function copy(info) {
          deepCopy(this.drawInfos, info.drawInfos, DrawInfo);
          return this;
        };
        return IndirectBuffer;
      }();
      var TextureInfo = function () {
        function TextureInfo(type, usage, format, width, height, flags, layerCount, levelCount, samples, depth, externalRes) {
          if (type === void 0) {
            type = TextureType.TEX2D;
          }
          if (usage === void 0) {
            usage = TextureUsageBit.NONE;
          }
          if (format === void 0) {
            format = Format.UNKNOWN;
          }
          if (width === void 0) {
            width = 0;
          }
          if (height === void 0) {
            height = 0;
          }
          if (flags === void 0) {
            flags = TextureFlagBit.NONE;
          }
          if (layerCount === void 0) {
            layerCount = 1;
          }
          if (levelCount === void 0) {
            levelCount = 1;
          }
          if (samples === void 0) {
            samples = SampleCount.X1;
          }
          if (depth === void 0) {
            depth = 1;
          }
          if (externalRes === void 0) {
            externalRes = 0;
          }
          this.type = type;
          this.usage = usage;
          this.format = format;
          this.width = width;
          this.height = height;
          this.flags = flags;
          this.layerCount = layerCount;
          this.levelCount = levelCount;
          this.samples = samples;
          this.depth = depth;
          this.externalRes = externalRes;
        }
        var _proto22 = TextureInfo.prototype;
        _proto22.copy = function copy(info) {
          this.type = info.type;
          this.usage = info.usage;
          this.format = info.format;
          this.width = info.width;
          this.height = info.height;
          this.flags = info.flags;
          this.layerCount = info.layerCount;
          this.levelCount = info.levelCount;
          this.samples = info.samples;
          this.depth = info.depth;
          this.externalRes = info.externalRes;
          return this;
        };
        return TextureInfo;
      }();
      var TextureViewInfo = function () {
        function TextureViewInfo(texture, type, format, baseLevel, levelCount, baseLayer, layerCount) {
          if (texture === void 0) {
            texture = null;
          }
          if (type === void 0) {
            type = TextureType.TEX2D;
          }
          if (format === void 0) {
            format = Format.UNKNOWN;
          }
          if (baseLevel === void 0) {
            baseLevel = 0;
          }
          if (levelCount === void 0) {
            levelCount = 1;
          }
          if (baseLayer === void 0) {
            baseLayer = 0;
          }
          if (layerCount === void 0) {
            layerCount = 1;
          }
          this.texture = texture;
          this.type = type;
          this.format = format;
          this.baseLevel = baseLevel;
          this.levelCount = levelCount;
          this.baseLayer = baseLayer;
          this.layerCount = layerCount;
        }
        var _proto23 = TextureViewInfo.prototype;
        _proto23.copy = function copy(info) {
          this.texture = info.texture;
          this.type = info.type;
          this.format = info.format;
          this.baseLevel = info.baseLevel;
          this.levelCount = info.levelCount;
          this.baseLayer = info.baseLayer;
          this.layerCount = info.layerCount;
          return this;
        };
        return TextureViewInfo;
      }();
      var SamplerInfo = function () {
        function SamplerInfo(minFilter, magFilter, mipFilter, addressU, addressV, addressW, maxAnisotropy, cmpFunc) {
          if (minFilter === void 0) {
            minFilter = Filter$1.LINEAR;
          }
          if (magFilter === void 0) {
            magFilter = Filter$1.LINEAR;
          }
          if (mipFilter === void 0) {
            mipFilter = Filter$1.NONE;
          }
          if (addressU === void 0) {
            addressU = Address.WRAP;
          }
          if (addressV === void 0) {
            addressV = Address.WRAP;
          }
          if (addressW === void 0) {
            addressW = Address.WRAP;
          }
          if (maxAnisotropy === void 0) {
            maxAnisotropy = 0;
          }
          if (cmpFunc === void 0) {
            cmpFunc = ComparisonFunc.ALWAYS;
          }
          this.minFilter = minFilter;
          this.magFilter = magFilter;
          this.mipFilter = mipFilter;
          this.addressU = addressU;
          this.addressV = addressV;
          this.addressW = addressW;
          this.maxAnisotropy = maxAnisotropy;
          this.cmpFunc = cmpFunc;
        }
        var _proto24 = SamplerInfo.prototype;
        _proto24.copy = function copy(info) {
          this.minFilter = info.minFilter;
          this.magFilter = info.magFilter;
          this.mipFilter = info.mipFilter;
          this.addressU = info.addressU;
          this.addressV = info.addressV;
          this.addressW = info.addressW;
          this.maxAnisotropy = info.maxAnisotropy;
          this.cmpFunc = info.cmpFunc;
          return this;
        };
        return SamplerInfo;
      }();
      var Uniform = function () {
        function Uniform(name, type, count) {
          if (name === void 0) {
            name = '';
          }
          if (type === void 0) {
            type = Type$1.UNKNOWN;
          }
          if (count === void 0) {
            count = 0;
          }
          this.name = name;
          this.type = type;
          this.count = count;
        }
        var _proto25 = Uniform.prototype;
        _proto25.copy = function copy(info) {
          this.name = info.name;
          this.type = info.type;
          this.count = info.count;
          return this;
        };
        return Uniform;
      }();
      var UniformBlock = function () {
        function UniformBlock(set, binding, name, members, count, flattened) {
          if (set === void 0) {
            set = 0;
          }
          if (binding === void 0) {
            binding = 0;
          }
          if (name === void 0) {
            name = '';
          }
          if (members === void 0) {
            members = [];
          }
          if (count === void 0) {
            count = 0;
          }
          if (flattened === void 0) {
            flattened = 0;
          }
          this.set = set;
          this.binding = binding;
          this.name = name;
          this.members = members;
          this.count = count;
          this.flattened = flattened;
        }
        var _proto26 = UniformBlock.prototype;
        _proto26.copy = function copy(info) {
          this.set = info.set;
          this.binding = info.binding;
          this.name = info.name;
          deepCopy(this.members, info.members, Uniform);
          this.count = info.count;
          this.flattened = info.flattened;
          return this;
        };
        return UniformBlock;
      }();
      var UniformSamplerTexture = function () {
        function UniformSamplerTexture(set, binding, name, type, count, flattened) {
          if (set === void 0) {
            set = 0;
          }
          if (binding === void 0) {
            binding = 0;
          }
          if (name === void 0) {
            name = '';
          }
          if (type === void 0) {
            type = Type$1.UNKNOWN;
          }
          if (count === void 0) {
            count = 0;
          }
          if (flattened === void 0) {
            flattened = 0;
          }
          this.set = set;
          this.binding = binding;
          this.name = name;
          this.type = type;
          this.count = count;
          this.flattened = flattened;
        }
        var _proto27 = UniformSamplerTexture.prototype;
        _proto27.copy = function copy(info) {
          this.set = info.set;
          this.binding = info.binding;
          this.name = info.name;
          this.type = info.type;
          this.count = info.count;
          this.flattened = info.flattened;
          return this;
        };
        return UniformSamplerTexture;
      }();
      var UniformSampler = function () {
        function UniformSampler(set, binding, name, count, flattened) {
          if (set === void 0) {
            set = 0;
          }
          if (binding === void 0) {
            binding = 0;
          }
          if (name === void 0) {
            name = '';
          }
          if (count === void 0) {
            count = 0;
          }
          if (flattened === void 0) {
            flattened = 0;
          }
          this.set = set;
          this.binding = binding;
          this.name = name;
          this.count = count;
          this.flattened = flattened;
        }
        var _proto28 = UniformSampler.prototype;
        _proto28.copy = function copy(info) {
          this.set = info.set;
          this.binding = info.binding;
          this.name = info.name;
          this.count = info.count;
          this.flattened = info.flattened;
          return this;
        };
        return UniformSampler;
      }();
      var UniformTexture = function () {
        function UniformTexture(set, binding, name, type, count, flattened) {
          if (set === void 0) {
            set = 0;
          }
          if (binding === void 0) {
            binding = 0;
          }
          if (name === void 0) {
            name = '';
          }
          if (type === void 0) {
            type = Type$1.UNKNOWN;
          }
          if (count === void 0) {
            count = 0;
          }
          if (flattened === void 0) {
            flattened = 0;
          }
          this.set = set;
          this.binding = binding;
          this.name = name;
          this.type = type;
          this.count = count;
          this.flattened = flattened;
        }
        var _proto29 = UniformTexture.prototype;
        _proto29.copy = function copy(info) {
          this.set = info.set;
          this.binding = info.binding;
          this.name = info.name;
          this.type = info.type;
          this.count = info.count;
          this.flattened = info.flattened;
          return this;
        };
        return UniformTexture;
      }();
      var UniformStorageImage = function () {
        function UniformStorageImage(set, binding, name, type, count, memoryAccess, flattened) {
          if (set === void 0) {
            set = 0;
          }
          if (binding === void 0) {
            binding = 0;
          }
          if (name === void 0) {
            name = '';
          }
          if (type === void 0) {
            type = Type$1.UNKNOWN;
          }
          if (count === void 0) {
            count = 0;
          }
          if (memoryAccess === void 0) {
            memoryAccess = MemoryAccessBit.READ_WRITE;
          }
          if (flattened === void 0) {
            flattened = 0;
          }
          this.set = set;
          this.binding = binding;
          this.name = name;
          this.type = type;
          this.count = count;
          this.memoryAccess = memoryAccess;
          this.flattened = flattened;
        }
        var _proto30 = UniformStorageImage.prototype;
        _proto30.copy = function copy(info) {
          this.set = info.set;
          this.binding = info.binding;
          this.name = info.name;
          this.type = info.type;
          this.count = info.count;
          this.memoryAccess = info.memoryAccess;
          this.flattened = info.flattened;
          return this;
        };
        return UniformStorageImage;
      }();
      var UniformStorageBuffer = function () {
        function UniformStorageBuffer(set, binding, name, count, memoryAccess, flattened) {
          if (set === void 0) {
            set = 0;
          }
          if (binding === void 0) {
            binding = 0;
          }
          if (name === void 0) {
            name = '';
          }
          if (count === void 0) {
            count = 0;
          }
          if (memoryAccess === void 0) {
            memoryAccess = MemoryAccessBit.READ_WRITE;
          }
          if (flattened === void 0) {
            flattened = 0;
          }
          this.set = set;
          this.binding = binding;
          this.name = name;
          this.count = count;
          this.memoryAccess = memoryAccess;
          this.flattened = flattened;
        }
        var _proto31 = UniformStorageBuffer.prototype;
        _proto31.copy = function copy(info) {
          this.set = info.set;
          this.binding = info.binding;
          this.name = info.name;
          this.count = info.count;
          this.memoryAccess = info.memoryAccess;
          this.flattened = info.flattened;
          return this;
        };
        return UniformStorageBuffer;
      }();
      var UniformInputAttachment = function () {
        function UniformInputAttachment(set, binding, name, count, flattened) {
          if (set === void 0) {
            set = 0;
          }
          if (binding === void 0) {
            binding = 0;
          }
          if (name === void 0) {
            name = '';
          }
          if (count === void 0) {
            count = 0;
          }
          if (flattened === void 0) {
            flattened = 0;
          }
          this.set = set;
          this.binding = binding;
          this.name = name;
          this.count = count;
          this.flattened = flattened;
        }
        var _proto32 = UniformInputAttachment.prototype;
        _proto32.copy = function copy(info) {
          this.set = info.set;
          this.binding = info.binding;
          this.name = info.name;
          this.count = info.count;
          this.flattened = info.flattened;
          return this;
        };
        return UniformInputAttachment;
      }();
      var ShaderStage = function () {
        function ShaderStage(stage, source) {
          if (stage === void 0) {
            stage = ShaderStageFlagBit.NONE;
          }
          if (source === void 0) {
            source = '';
          }
          this.stage = stage;
          this.source = source;
        }
        var _proto33 = ShaderStage.prototype;
        _proto33.copy = function copy(info) {
          this.stage = info.stage;
          this.source = info.source;
          return this;
        };
        return ShaderStage;
      }();
      var Attribute = function () {
        function Attribute(name, format, isNormalized, stream, isInstanced, location) {
          if (name === void 0) {
            name = '';
          }
          if (format === void 0) {
            format = Format.UNKNOWN;
          }
          if (isNormalized === void 0) {
            isNormalized = false;
          }
          if (stream === void 0) {
            stream = 0;
          }
          if (isInstanced === void 0) {
            isInstanced = false;
          }
          if (location === void 0) {
            location = 0;
          }
          this.name = name;
          this.format = format;
          this.isNormalized = isNormalized;
          this.stream = stream;
          this.isInstanced = isInstanced;
          this.location = location;
        }
        var _proto34 = Attribute.prototype;
        _proto34.copy = function copy(info) {
          this.name = info.name;
          this.format = info.format;
          this.isNormalized = info.isNormalized;
          this.stream = info.stream;
          this.isInstanced = info.isInstanced;
          this.location = info.location;
          return this;
        };
        return Attribute;
      }();
      var ShaderInfo = function () {
        function ShaderInfo(name, stages, attributes, blocks, buffers, samplerTextures, samplers, textures, images, subpassInputs) {
          if (name === void 0) {
            name = '';
          }
          if (stages === void 0) {
            stages = [];
          }
          if (attributes === void 0) {
            attributes = [];
          }
          if (blocks === void 0) {
            blocks = [];
          }
          if (buffers === void 0) {
            buffers = [];
          }
          if (samplerTextures === void 0) {
            samplerTextures = [];
          }
          if (samplers === void 0) {
            samplers = [];
          }
          if (textures === void 0) {
            textures = [];
          }
          if (images === void 0) {
            images = [];
          }
          if (subpassInputs === void 0) {
            subpassInputs = [];
          }
          this.name = name;
          this.stages = stages;
          this.attributes = attributes;
          this.blocks = blocks;
          this.buffers = buffers;
          this.samplerTextures = samplerTextures;
          this.samplers = samplers;
          this.textures = textures;
          this.images = images;
          this.subpassInputs = subpassInputs;
        }
        var _proto35 = ShaderInfo.prototype;
        _proto35.copy = function copy(info) {
          this.name = info.name;
          deepCopy(this.stages, info.stages, ShaderStage);
          deepCopy(this.attributes, info.attributes, Attribute);
          deepCopy(this.blocks, info.blocks, UniformBlock);
          deepCopy(this.buffers, info.buffers, UniformStorageBuffer);
          deepCopy(this.samplerTextures, info.samplerTextures, UniformSamplerTexture);
          deepCopy(this.samplers, info.samplers, UniformSampler);
          deepCopy(this.textures, info.textures, UniformTexture);
          deepCopy(this.images, info.images, UniformStorageImage);
          deepCopy(this.subpassInputs, info.subpassInputs, UniformInputAttachment);
          return this;
        };
        return ShaderInfo;
      }();
      var InputAssemblerInfo = function () {
        function InputAssemblerInfo(attributes, vertexBuffers, indexBuffer, indirectBuffer) {
          if (attributes === void 0) {
            attributes = [];
          }
          if (vertexBuffers === void 0) {
            vertexBuffers = [];
          }
          if (indexBuffer === void 0) {
            indexBuffer = null;
          }
          if (indirectBuffer === void 0) {
            indirectBuffer = null;
          }
          this.attributes = attributes;
          this.vertexBuffers = vertexBuffers;
          this.indexBuffer = indexBuffer;
          this.indirectBuffer = indirectBuffer;
        }
        var _proto36 = InputAssemblerInfo.prototype;
        _proto36.copy = function copy(info) {
          deepCopy(this.attributes, info.attributes, Attribute);
          this.vertexBuffers = info.vertexBuffers.slice();
          this.indexBuffer = info.indexBuffer;
          this.indirectBuffer = info.indirectBuffer;
          return this;
        };
        return InputAssemblerInfo;
      }();
      var ColorAttachment = function () {
        function ColorAttachment(format, sampleCount, loadOp, storeOp, barrier) {
          if (format === void 0) {
            format = Format.UNKNOWN;
          }
          if (sampleCount === void 0) {
            sampleCount = SampleCount.X1;
          }
          if (loadOp === void 0) {
            loadOp = LoadOp.CLEAR;
          }
          if (storeOp === void 0) {
            storeOp = StoreOp.STORE;
          }
          if (barrier === void 0) {
            barrier = null;
          }
          this.format = format;
          this.sampleCount = sampleCount;
          this.loadOp = loadOp;
          this.storeOp = storeOp;
          this.barrier = barrier;
        }
        var _proto37 = ColorAttachment.prototype;
        _proto37.copy = function copy(info) {
          this.format = info.format;
          this.sampleCount = info.sampleCount;
          this.loadOp = info.loadOp;
          this.storeOp = info.storeOp;
          this.barrier = info.barrier;
          return this;
        };
        return ColorAttachment;
      }();
      var DepthStencilAttachment = function () {
        function DepthStencilAttachment(format, sampleCount, depthLoadOp, depthStoreOp, stencilLoadOp, stencilStoreOp, barrier) {
          if (format === void 0) {
            format = Format.UNKNOWN;
          }
          if (sampleCount === void 0) {
            sampleCount = SampleCount.X1;
          }
          if (depthLoadOp === void 0) {
            depthLoadOp = LoadOp.CLEAR;
          }
          if (depthStoreOp === void 0) {
            depthStoreOp = StoreOp.STORE;
          }
          if (stencilLoadOp === void 0) {
            stencilLoadOp = LoadOp.CLEAR;
          }
          if (stencilStoreOp === void 0) {
            stencilStoreOp = StoreOp.STORE;
          }
          if (barrier === void 0) {
            barrier = null;
          }
          this.format = format;
          this.sampleCount = sampleCount;
          this.depthLoadOp = depthLoadOp;
          this.depthStoreOp = depthStoreOp;
          this.stencilLoadOp = stencilLoadOp;
          this.stencilStoreOp = stencilStoreOp;
          this.barrier = barrier;
        }
        var _proto38 = DepthStencilAttachment.prototype;
        _proto38.copy = function copy(info) {
          this.format = info.format;
          this.sampleCount = info.sampleCount;
          this.depthLoadOp = info.depthLoadOp;
          this.depthStoreOp = info.depthStoreOp;
          this.stencilLoadOp = info.stencilLoadOp;
          this.stencilStoreOp = info.stencilStoreOp;
          this.barrier = info.barrier;
          return this;
        };
        return DepthStencilAttachment;
      }();
      var SubpassInfo = function () {
        function SubpassInfo(inputs, colors, resolves, preserves, depthStencil, depthStencilResolve, depthResolveMode, stencilResolveMode) {
          if (inputs === void 0) {
            inputs = [];
          }
          if (colors === void 0) {
            colors = [];
          }
          if (resolves === void 0) {
            resolves = [];
          }
          if (preserves === void 0) {
            preserves = [];
          }
          if (depthStencil === void 0) {
            depthStencil = -1;
          }
          if (depthStencilResolve === void 0) {
            depthStencilResolve = -1;
          }
          if (depthResolveMode === void 0) {
            depthResolveMode = ResolveMode.NONE;
          }
          if (stencilResolveMode === void 0) {
            stencilResolveMode = ResolveMode.NONE;
          }
          this.inputs = inputs;
          this.colors = colors;
          this.resolves = resolves;
          this.preserves = preserves;
          this.depthStencil = depthStencil;
          this.depthStencilResolve = depthStencilResolve;
          this.depthResolveMode = depthResolveMode;
          this.stencilResolveMode = stencilResolveMode;
        }
        var _proto39 = SubpassInfo.prototype;
        _proto39.copy = function copy(info) {
          this.inputs = info.inputs.slice();
          this.colors = info.colors.slice();
          this.resolves = info.resolves.slice();
          this.preserves = info.preserves.slice();
          this.depthStencil = info.depthStencil;
          this.depthStencilResolve = info.depthStencilResolve;
          this.depthResolveMode = info.depthResolveMode;
          this.stencilResolveMode = info.stencilResolveMode;
          return this;
        };
        return SubpassInfo;
      }();
      var SubpassDependency = function () {
        function SubpassDependency(srcSubpass, dstSubpass, generalBarrier, prevAccesses, nextAccesses) {
          if (srcSubpass === void 0) {
            srcSubpass = 0;
          }
          if (dstSubpass === void 0) {
            dstSubpass = 0;
          }
          if (generalBarrier === void 0) {
            generalBarrier = null;
          }
          if (prevAccesses === void 0) {
            prevAccesses = [AccessFlagBit.NONE];
          }
          if (nextAccesses === void 0) {
            nextAccesses = [AccessFlagBit.NONE];
          }
          this.srcSubpass = srcSubpass;
          this.dstSubpass = dstSubpass;
          this.generalBarrier = generalBarrier;
          this.prevAccesses = prevAccesses;
          this.nextAccesses = nextAccesses;
        }
        var _proto40 = SubpassDependency.prototype;
        _proto40.copy = function copy(info) {
          this.srcSubpass = info.srcSubpass;
          this.dstSubpass = info.dstSubpass;
          this.generalBarrier = info.generalBarrier;
          this.prevAccesses = info.prevAccesses.slice();
          this.nextAccesses = info.nextAccesses.slice();
          return this;
        };
        return SubpassDependency;
      }();
      var RenderPassInfo = function () {
        function RenderPassInfo(colorAttachments, depthStencilAttachment, depthStencilResolveAttachment, subpasses, dependencies) {
          if (colorAttachments === void 0) {
            colorAttachments = [];
          }
          if (depthStencilAttachment === void 0) {
            depthStencilAttachment = new DepthStencilAttachment();
          }
          if (depthStencilResolveAttachment === void 0) {
            depthStencilResolveAttachment = new DepthStencilAttachment();
          }
          if (subpasses === void 0) {
            subpasses = [];
          }
          if (dependencies === void 0) {
            dependencies = [];
          }
          this.colorAttachments = colorAttachments;
          this.depthStencilAttachment = depthStencilAttachment;
          this.depthStencilResolveAttachment = depthStencilResolveAttachment;
          this.subpasses = subpasses;
          this.dependencies = dependencies;
        }
        var _proto41 = RenderPassInfo.prototype;
        _proto41.copy = function copy(info) {
          deepCopy(this.colorAttachments, info.colorAttachments, ColorAttachment);
          this.depthStencilAttachment.copy(info.depthStencilAttachment);
          this.depthStencilResolveAttachment.copy(info.depthStencilResolveAttachment);
          deepCopy(this.subpasses, info.subpasses, SubpassInfo);
          deepCopy(this.dependencies, info.dependencies, SubpassDependency);
          return this;
        };
        return RenderPassInfo;
      }();
      var GeneralBarrierInfo = function () {
        function GeneralBarrierInfo(prevAccesses, nextAccesses, type) {
          if (prevAccesses === void 0) {
            prevAccesses = AccessFlagBit.NONE;
          }
          if (nextAccesses === void 0) {
            nextAccesses = AccessFlagBit.NONE;
          }
          if (type === void 0) {
            type = BarrierType.FULL;
          }
          this.prevAccesses = prevAccesses;
          this.nextAccesses = nextAccesses;
          this.type = type;
        }
        var _proto42 = GeneralBarrierInfo.prototype;
        _proto42.copy = function copy(info) {
          this.prevAccesses = info.prevAccesses;
          this.nextAccesses = info.nextAccesses;
          this.type = info.type;
          return this;
        };
        return GeneralBarrierInfo;
      }();
      var TextureBarrierInfo = function () {
        function TextureBarrierInfo(prevAccesses, nextAccesses, type, baseMipLevel, levelCount, baseSlice, sliceCount, discardContents, srcQueue, dstQueue) {
          if (prevAccesses === void 0) {
            prevAccesses = AccessFlagBit.NONE;
          }
          if (nextAccesses === void 0) {
            nextAccesses = AccessFlagBit.NONE;
          }
          if (type === void 0) {
            type = BarrierType.FULL;
          }
          if (baseMipLevel === void 0) {
            baseMipLevel = 0;
          }
          if (levelCount === void 0) {
            levelCount = 1;
          }
          if (baseSlice === void 0) {
            baseSlice = 0;
          }
          if (sliceCount === void 0) {
            sliceCount = 1;
          }
          if (discardContents === void 0) {
            discardContents = false;
          }
          if (srcQueue === void 0) {
            srcQueue = null;
          }
          if (dstQueue === void 0) {
            dstQueue = null;
          }
          this.prevAccesses = prevAccesses;
          this.nextAccesses = nextAccesses;
          this.type = type;
          this.baseMipLevel = baseMipLevel;
          this.levelCount = levelCount;
          this.baseSlice = baseSlice;
          this.sliceCount = sliceCount;
          this.discardContents = discardContents;
          this.srcQueue = srcQueue;
          this.dstQueue = dstQueue;
        }
        var _proto43 = TextureBarrierInfo.prototype;
        _proto43.copy = function copy(info) {
          this.prevAccesses = info.prevAccesses;
          this.nextAccesses = info.nextAccesses;
          this.type = info.type;
          this.baseMipLevel = info.baseMipLevel;
          this.levelCount = info.levelCount;
          this.baseSlice = info.baseSlice;
          this.sliceCount = info.sliceCount;
          this.discardContents = info.discardContents;
          this.srcQueue = info.srcQueue;
          this.dstQueue = info.dstQueue;
          return this;
        };
        return TextureBarrierInfo;
      }();
      var BufferBarrierInfo = function () {
        function BufferBarrierInfo(prevAccesses, nextAccesses, type, offset, size, discardContents, srcQueue, dstQueue) {
          if (prevAccesses === void 0) {
            prevAccesses = AccessFlagBit.NONE;
          }
          if (nextAccesses === void 0) {
            nextAccesses = AccessFlagBit.NONE;
          }
          if (type === void 0) {
            type = BarrierType.FULL;
          }
          if (offset === void 0) {
            offset = 0;
          }
          if (size === void 0) {
            size = 0;
          }
          if (discardContents === void 0) {
            discardContents = false;
          }
          if (srcQueue === void 0) {
            srcQueue = null;
          }
          if (dstQueue === void 0) {
            dstQueue = null;
          }
          this.prevAccesses = prevAccesses;
          this.nextAccesses = nextAccesses;
          this.type = type;
          this.offset = offset;
          this.size = size;
          this.discardContents = discardContents;
          this.srcQueue = srcQueue;
          this.dstQueue = dstQueue;
        }
        var _proto44 = BufferBarrierInfo.prototype;
        _proto44.copy = function copy(info) {
          this.prevAccesses = info.prevAccesses;
          this.nextAccesses = info.nextAccesses;
          this.type = info.type;
          this.offset = info.offset;
          this.size = info.size;
          this.discardContents = info.discardContents;
          this.srcQueue = info.srcQueue;
          this.dstQueue = info.dstQueue;
          return this;
        };
        return BufferBarrierInfo;
      }();
      var FramebufferInfo = function () {
        function FramebufferInfo(renderPass, colorTextures, depthStencilTexture, depthStencilResolveTexture) {
          if (renderPass === void 0) {
            renderPass = null;
          }
          if (colorTextures === void 0) {
            colorTextures = [];
          }
          if (depthStencilTexture === void 0) {
            depthStencilTexture = null;
          }
          if (depthStencilResolveTexture === void 0) {
            depthStencilResolveTexture = null;
          }
          this.renderPass = renderPass;
          this.colorTextures = colorTextures;
          this.depthStencilTexture = depthStencilTexture;
          this.depthStencilResolveTexture = depthStencilResolveTexture;
        }
        var _proto45 = FramebufferInfo.prototype;
        _proto45.copy = function copy(info) {
          this.renderPass = info.renderPass;
          this.colorTextures = info.colorTextures.slice();
          this.depthStencilTexture = info.depthStencilTexture;
          this.depthStencilResolveTexture = info.depthStencilResolveTexture;
          return this;
        };
        return FramebufferInfo;
      }();
      var DescriptorSetLayoutBinding = function () {
        function DescriptorSetLayoutBinding(binding, descriptorType, count, stageFlags, immutableSamplers) {
          if (binding === void 0) {
            binding = -1;
          }
          if (descriptorType === void 0) {
            descriptorType = DescriptorType.UNKNOWN;
          }
          if (count === void 0) {
            count = 0;
          }
          if (stageFlags === void 0) {
            stageFlags = ShaderStageFlagBit.NONE;
          }
          if (immutableSamplers === void 0) {
            immutableSamplers = [];
          }
          this.binding = binding;
          this.descriptorType = descriptorType;
          this.count = count;
          this.stageFlags = stageFlags;
          this.immutableSamplers = immutableSamplers;
        }
        var _proto46 = DescriptorSetLayoutBinding.prototype;
        _proto46.copy = function copy(info) {
          this.binding = info.binding;
          this.descriptorType = info.descriptorType;
          this.count = info.count;
          this.stageFlags = info.stageFlags;
          this.immutableSamplers = info.immutableSamplers.slice();
          return this;
        };
        return DescriptorSetLayoutBinding;
      }();
      var DescriptorSetLayoutInfo = function () {
        function DescriptorSetLayoutInfo(bindings) {
          if (bindings === void 0) {
            bindings = [];
          }
          this.bindings = bindings;
        }
        var _proto47 = DescriptorSetLayoutInfo.prototype;
        _proto47.copy = function copy(info) {
          deepCopy(this.bindings, info.bindings, DescriptorSetLayoutBinding);
          return this;
        };
        return DescriptorSetLayoutInfo;
      }();
      var DescriptorSetInfo = function () {
        function DescriptorSetInfo(layout) {
          if (layout === void 0) {
            layout = null;
          }
          this.layout = layout;
        }
        var _proto48 = DescriptorSetInfo.prototype;
        _proto48.copy = function copy(info) {
          this.layout = info.layout;
          return this;
        };
        return DescriptorSetInfo;
      }();
      var PipelineLayoutInfo = function () {
        function PipelineLayoutInfo(setLayouts) {
          if (setLayouts === void 0) {
            setLayouts = [];
          }
          this.setLayouts = setLayouts;
        }
        var _proto49 = PipelineLayoutInfo.prototype;
        _proto49.copy = function copy(info) {
          this.setLayouts = info.setLayouts.slice();
          return this;
        };
        return PipelineLayoutInfo;
      }();
      var InputState = function () {
        function InputState(attributes) {
          if (attributes === void 0) {
            attributes = [];
          }
          this.attributes = attributes;
        }
        var _proto50 = InputState.prototype;
        _proto50.copy = function copy(info) {
          deepCopy(this.attributes, info.attributes, Attribute);
          return this;
        };
        return InputState;
      }();
      var CommandBufferInfo = function () {
        function CommandBufferInfo(queue, type) {
          if (queue === void 0) {
            queue = null;
          }
          if (type === void 0) {
            type = CommandBufferType.PRIMARY;
          }
          this.queue = queue;
          this.type = type;
        }
        var _proto51 = CommandBufferInfo.prototype;
        _proto51.copy = function copy(info) {
          this.queue = info.queue;
          this.type = info.type;
          return this;
        };
        return CommandBufferInfo;
      }();
      var QueueInfo = function () {
        function QueueInfo(type) {
          if (type === void 0) {
            type = QueueType.GRAPHICS;
          }
          this.type = type;
        }
        var _proto52 = QueueInfo.prototype;
        _proto52.copy = function copy(info) {
          this.type = info.type;
          return this;
        };
        return QueueInfo;
      }();
      var QueryPoolInfo = function () {
        function QueryPoolInfo(type, maxQueryObjects, forceWait) {
          if (type === void 0) {
            type = QueryType.OCCLUSION;
          }
          if (maxQueryObjects === void 0) {
            maxQueryObjects = 32767;
          }
          if (forceWait === void 0) {
            forceWait = true;
          }
          this.type = type;
          this.maxQueryObjects = maxQueryObjects;
          this.forceWait = forceWait;
        }
        var _proto53 = QueryPoolInfo.prototype;
        _proto53.copy = function copy(info) {
          this.type = info.type;
          this.maxQueryObjects = info.maxQueryObjects;
          this.forceWait = info.forceWait;
          return this;
        };
        return QueryPoolInfo;
      }();
      var FormatInfo = function FormatInfo(name, size, count, type, hasAlpha, hasDepth, hasStencil, isCompressed) {
        if (name === void 0) {
          name = '';
        }
        if (size === void 0) {
          size = 0;
        }
        if (count === void 0) {
          count = 0;
        }
        if (type === void 0) {
          type = FormatType.NONE;
        }
        if (hasAlpha === void 0) {
          hasAlpha = false;
        }
        if (hasDepth === void 0) {
          hasDepth = false;
        }
        if (hasStencil === void 0) {
          hasStencil = false;
        }
        if (isCompressed === void 0) {
          isCompressed = false;
        }
        this.name = name;
        this.size = size;
        this.count = count;
        this.type = type;
        this.hasAlpha = hasAlpha;
        this.hasDepth = hasDepth;
        this.hasStencil = hasStencil;
        this.isCompressed = isCompressed;
      };
      var MemoryStatus = function () {
        function MemoryStatus(bufferSize, textureSize) {
          if (bufferSize === void 0) {
            bufferSize = 0;
          }
          if (textureSize === void 0) {
            textureSize = 0;
          }
          this.bufferSize = bufferSize;
          this.textureSize = textureSize;
        }
        var _proto54 = MemoryStatus.prototype;
        _proto54.copy = function copy(info) {
          this.bufferSize = info.bufferSize;
          this.textureSize = info.textureSize;
          return this;
        };
        return MemoryStatus;
      }();
      var DynamicStencilStates = function () {
        function DynamicStencilStates(writeMask, compareMask, reference) {
          if (writeMask === void 0) {
            writeMask = 0;
          }
          if (compareMask === void 0) {
            compareMask = 0;
          }
          if (reference === void 0) {
            reference = 0;
          }
          this.writeMask = writeMask;
          this.compareMask = compareMask;
          this.reference = reference;
        }
        var _proto55 = DynamicStencilStates.prototype;
        _proto55.copy = function copy(info) {
          this.writeMask = info.writeMask;
          this.compareMask = info.compareMask;
          this.reference = info.reference;
          return this;
        };
        return DynamicStencilStates;
      }();
      var DynamicStates = function () {
        function DynamicStates(viewport, scissor, blendConstant, lineWidth, depthBiasConstant, depthBiasClamp, depthBiasSlope, depthMinBounds, depthMaxBounds, stencilStatesFront, stencilStatesBack) {
          if (viewport === void 0) {
            viewport = new Viewport();
          }
          if (scissor === void 0) {
            scissor = new Rect();
          }
          if (blendConstant === void 0) {
            blendConstant = new Color();
          }
          if (lineWidth === void 0) {
            lineWidth = 1;
          }
          if (depthBiasConstant === void 0) {
            depthBiasConstant = 0;
          }
          if (depthBiasClamp === void 0) {
            depthBiasClamp = 0;
          }
          if (depthBiasSlope === void 0) {
            depthBiasSlope = 0;
          }
          if (depthMinBounds === void 0) {
            depthMinBounds = 0;
          }
          if (depthMaxBounds === void 0) {
            depthMaxBounds = 0;
          }
          if (stencilStatesFront === void 0) {
            stencilStatesFront = new DynamicStencilStates();
          }
          if (stencilStatesBack === void 0) {
            stencilStatesBack = new DynamicStencilStates();
          }
          this.viewport = viewport;
          this.scissor = scissor;
          this.blendConstant = blendConstant;
          this.lineWidth = lineWidth;
          this.depthBiasConstant = depthBiasConstant;
          this.depthBiasClamp = depthBiasClamp;
          this.depthBiasSlope = depthBiasSlope;
          this.depthMinBounds = depthMinBounds;
          this.depthMaxBounds = depthMaxBounds;
          this.stencilStatesFront = stencilStatesFront;
          this.stencilStatesBack = stencilStatesBack;
        }
        var _proto56 = DynamicStates.prototype;
        _proto56.copy = function copy(info) {
          this.viewport.copy(info.viewport);
          this.scissor.copy(info.scissor);
          this.blendConstant.copy(info.blendConstant);
          this.lineWidth = info.lineWidth;
          this.depthBiasConstant = info.depthBiasConstant;
          this.depthBiasClamp = info.depthBiasClamp;
          this.depthBiasSlope = info.depthBiasSlope;
          this.depthMinBounds = info.depthMinBounds;
          this.depthMaxBounds = info.depthMaxBounds;
          this.stencilStatesFront.copy(info.stencilStatesFront);
          this.stencilStatesBack.copy(info.stencilStatesBack);
          return this;
        };
        return DynamicStates;
      }();
      var GFXObject = function (_GCObject) {
        _inheritsLoose(GFXObject, _GCObject);
        function GFXObject(objectType) {
          var _this;
          _this = _GCObject.call(this) || this;
          _this._objectType = ObjectType.UNKNOWN;
          _this._objectID = 0;
          _this._typedID = 0;
          _this._objectType = objectType;
          _this._objectID = GFXObject._idTable[ObjectType.UNKNOWN]++;
          _this._typedID = GFXObject._idTable[objectType]++;
          return _this;
        }
        _createClass(GFXObject, [{
          key: "objectType",
          get: function get() {
            return this._objectType;
          }
        }, {
          key: "objectID",
          get: function get() {
            return this._objectID;
          }
        }, {
          key: "typedID",
          get: function get() {
            return this._typedID;
          }
        }]);
        return GFXObject;
      }(GCObject);
      GFXObject._idTable = Array(ObjectType.COUNT).fill(1 << 16);
      var AttributeName;
      (function (AttributeName) {
        AttributeName["ATTR_POSITION"] = "a_position";
        AttributeName["ATTR_NORMAL"] = "a_normal";
        AttributeName["ATTR_TANGENT"] = "a_tangent";
        AttributeName["ATTR_BITANGENT"] = "a_bitangent";
        AttributeName["ATTR_WEIGHTS"] = "a_weights";
        AttributeName["ATTR_JOINTS"] = "a_joints";
        AttributeName["ATTR_COLOR"] = "a_color";
        AttributeName["ATTR_COLOR1"] = "a_color1";
        AttributeName["ATTR_COLOR2"] = "a_color2";
        AttributeName["ATTR_TEX_COORD"] = "a_texCoord";
        AttributeName["ATTR_TEX_COORD1"] = "a_texCoord1";
        AttributeName["ATTR_TEX_COORD2"] = "a_texCoord2";
        AttributeName["ATTR_TEX_COORD3"] = "a_texCoord3";
        AttributeName["ATTR_TEX_COORD4"] = "a_texCoord4";
        AttributeName["ATTR_TEX_COORD5"] = "a_texCoord5";
        AttributeName["ATTR_TEX_COORD6"] = "a_texCoord6";
        AttributeName["ATTR_TEX_COORD7"] = "a_texCoord7";
        AttributeName["ATTR_TEX_COORD8"] = "a_texCoord8";
        AttributeName["ATTR_BATCH_ID"] = "a_batch_id";
        AttributeName["ATTR_BATCH_UV"] = "a_batch_uv";
      })(AttributeName || (AttributeName = {}));
      var FormatInfos = Object.freeze([new FormatInfo('UNKNOWN', 0, 0, FormatType.NONE, false, false, false, false), new FormatInfo('A8', 1, 1, FormatType.UNORM, true, false, false, false), new FormatInfo('L8', 1, 1, FormatType.UNORM, false, false, false, false), new FormatInfo('LA8', 1, 2, FormatType.UNORM, true, false, false, false), new FormatInfo('R8', 1, 1, FormatType.UNORM, false, false, false, false), new FormatInfo('R8SN', 1, 1, FormatType.SNORM, false, false, false, false), new FormatInfo('R8UI', 1, 1, FormatType.UINT, false, false, false, false), new FormatInfo('R8I', 1, 1, FormatType.INT, false, false, false, false), new FormatInfo('R16F', 2, 1, FormatType.FLOAT, false, false, false, false), new FormatInfo('R16UI', 2, 1, FormatType.UINT, false, false, false, false), new FormatInfo('R16I', 2, 1, FormatType.INT, false, false, false, false), new FormatInfo('R32F', 4, 1, FormatType.FLOAT, false, false, false, false), new FormatInfo('R32UI', 4, 1, FormatType.UINT, false, false, false, false), new FormatInfo('R32I', 4, 1, FormatType.INT, false, false, false, false), new FormatInfo('RG8', 2, 2, FormatType.UNORM, false, false, false, false), new FormatInfo('RG8SN', 2, 2, FormatType.SNORM, false, false, false, false), new FormatInfo('RG8UI', 2, 2, FormatType.UINT, false, false, false, false), new FormatInfo('RG8I', 2, 2, FormatType.INT, false, false, false, false), new FormatInfo('RG16F', 4, 2, FormatType.FLOAT, false, false, false, false), new FormatInfo('RG16UI', 4, 2, FormatType.UINT, false, false, false, false), new FormatInfo('RG16I', 4, 2, FormatType.INT, false, false, false, false), new FormatInfo('RG32F', 8, 2, FormatType.FLOAT, false, false, false, false), new FormatInfo('RG32UI', 8, 2, FormatType.UINT, false, false, false, false), new FormatInfo('RG32I', 8, 2, FormatType.INT, false, false, false, false), new FormatInfo('RGB8', 3, 3, FormatType.UNORM, false, false, false, false), new FormatInfo('SRGB8', 3, 3, FormatType.UNORM, false, false, false, false), new FormatInfo('RGB8SN', 3, 3, FormatType.SNORM, false, false, false, false), new FormatInfo('RGB8UI', 3, 3, FormatType.UINT, false, false, false, false), new FormatInfo('RGB8I', 3, 3, FormatType.INT, false, false, false, false), new FormatInfo('RGB16F', 6, 3, FormatType.FLOAT, false, false, false, false), new FormatInfo('RGB16UI', 6, 3, FormatType.UINT, false, false, false, false), new FormatInfo('RGB16I', 6, 3, FormatType.INT, false, false, false, false), new FormatInfo('RGB32F', 12, 3, FormatType.FLOAT, false, false, false, false), new FormatInfo('RGB32UI', 12, 3, FormatType.UINT, false, false, false, false), new FormatInfo('RGB32I', 12, 3, FormatType.INT, false, false, false, false), new FormatInfo('RGBA8', 4, 4, FormatType.UNORM, true, false, false, false), new FormatInfo('BGRA8', 4, 4, FormatType.UNORM, true, false, false, false), new FormatInfo('SRGB8_A8', 4, 4, FormatType.UNORM, true, false, false, false), new FormatInfo('RGBA8SN', 4, 4, FormatType.SNORM, true, false, false, false), new FormatInfo('RGBA8UI', 4, 4, FormatType.UINT, true, false, false, false), new FormatInfo('RGBA8I', 4, 4, FormatType.INT, true, false, false, false), new FormatInfo('RGBA16F', 8, 4, FormatType.FLOAT, true, false, false, false), new FormatInfo('RGBA16UI', 8, 4, FormatType.UINT, true, false, false, false), new FormatInfo('RGBA16I', 8, 4, FormatType.INT, true, false, false, false), new FormatInfo('RGBA32F', 16, 4, FormatType.FLOAT, true, false, false, false), new FormatInfo('RGBA32UI', 16, 4, FormatType.UINT, true, false, false, false), new FormatInfo('RGBA32I', 16, 4, FormatType.INT, true, false, false, false), new FormatInfo('R5G6B5', 2, 3, FormatType.UNORM, false, false, false, false), new FormatInfo('R11G11B10F', 4, 3, FormatType.FLOAT, false, false, false, false), new FormatInfo('RGB5A1', 2, 4, FormatType.UNORM, true, false, false, false), new FormatInfo('RGBA4', 2, 4, FormatType.UNORM, true, false, false, false), new FormatInfo('RGB10A2', 2, 4, FormatType.UNORM, true, false, false, false), new FormatInfo('RGB10A2UI', 2, 4, FormatType.UINT, true, false, false, false), new FormatInfo('RGB9E5', 2, 4, FormatType.FLOAT, true, false, false, false), new FormatInfo('DEPTH', 4, 1, FormatType.FLOAT, false, true, false, false), new FormatInfo('DEPTH_STENCIL', 5, 2, FormatType.FLOAT, false, true, true, false), new FormatInfo('BC1', 1, 3, FormatType.UNORM, false, false, false, true), new FormatInfo('BC1_ALPHA', 1, 4, FormatType.UNORM, true, false, false, true), new FormatInfo('BC1_SRGB', 1, 3, FormatType.UNORM, false, false, false, true), new FormatInfo('BC1_SRGB_ALPHA', 1, 4, FormatType.UNORM, true, false, false, true), new FormatInfo('BC2', 1, 4, FormatType.UNORM, true, false, false, true), new FormatInfo('BC2_SRGB', 1, 4, FormatType.UNORM, true, false, false, true), new FormatInfo('BC3', 1, 4, FormatType.UNORM, true, false, false, true), new FormatInfo('BC3_SRGB', 1, 4, FormatType.UNORM, true, false, false, true), new FormatInfo('BC4', 1, 1, FormatType.UNORM, false, false, false, true), new FormatInfo('BC4_SNORM', 1, 1, FormatType.SNORM, false, false, false, true), new FormatInfo('BC5', 1, 2, FormatType.UNORM, false, false, false, true), new FormatInfo('BC5_SNORM', 1, 2, FormatType.SNORM, false, false, false, true), new FormatInfo('BC6H_UF16', 1, 3, FormatType.UFLOAT, false, false, false, true), new FormatInfo('BC6H_SF16', 1, 3, FormatType.FLOAT, false, false, false, true), new FormatInfo('BC7', 1, 4, FormatType.UNORM, true, false, false, true), new FormatInfo('BC7_SRGB', 1, 4, FormatType.UNORM, true, false, false, true), new FormatInfo('ETC_RGB8', 1, 3, FormatType.UNORM, false, false, false, true), new FormatInfo('ETC2_RGB8', 1, 3, FormatType.UNORM, false, false, false, true), new FormatInfo('ETC2_SRGB8', 1, 3, FormatType.UNORM, false, false, false, true), new FormatInfo('ETC2_RGB8_A1', 1, 4, FormatType.UNORM, true, false, false, true), new FormatInfo('ETC2_SRGB8_A1', 1, 4, FormatType.UNORM, true, false, false, true), new FormatInfo('ETC2_RGBA8', 2, 4, FormatType.UNORM, true, false, false, true), new FormatInfo('ETC2_SRGB8_A8', 2, 4, FormatType.UNORM, true, false, false, true), new FormatInfo('EAC_R11', 1, 1, FormatType.UNORM, false, false, false, true), new FormatInfo('EAC_R11SN', 1, 1, FormatType.SNORM, false, false, false, true), new FormatInfo('EAC_RG11', 2, 2, FormatType.UNORM, false, false, false, true), new FormatInfo('EAC_RG11SN', 2, 2, FormatType.SNORM, false, false, false, true), new FormatInfo('PVRTC_RGB2', 2, 3, FormatType.UNORM, false, false, false, true), new FormatInfo('PVRTC_RGBA2', 2, 4, FormatType.UNORM, true, false, false, true), new FormatInfo('PVRTC_RGB4', 2, 3, FormatType.UNORM, false, false, false, true), new FormatInfo('PVRTC_RGBA4', 2, 4, FormatType.UNORM, true, false, false, true), new FormatInfo('PVRTC2_2BPP', 2, 4, FormatType.UNORM, true, false, false, true), new FormatInfo('PVRTC2_4BPP', 2, 4, FormatType.UNORM, true, false, false, true), new FormatInfo('ASTC_RGBA_4x4', 1, 4, FormatType.UNORM, true, false, false, true), new FormatInfo('ASTC_RGBA_5x4', 1, 4, FormatType.UNORM, true, false, false, true), new FormatInfo('ASTC_RGBA_5x5', 1, 4, FormatType.UNORM, true, false, false, true), new FormatInfo('ASTC_RGBA_6x5', 1, 4, FormatType.UNORM, true, false, false, true), new FormatInfo('ASTC_RGBA_6x6', 1, 4, FormatType.UNORM, true, false, false, true), new FormatInfo('ASTC_RGBA_8x5', 1, 4, FormatType.UNORM, true, false, false, true), new FormatInfo('ASTC_RGBA_8x6', 1, 4, FormatType.UNORM, true, false, false, true), new FormatInfo('ASTC_RGBA_8x8', 1, 4, FormatType.UNORM, true, false, false, true), new FormatInfo('ASTC_RGBA_10x5', 1, 4, FormatType.UNORM, true, false, false, true), new FormatInfo('ASTC_RGBA_10x6', 1, 4, FormatType.UNORM, true, false, false, true), new FormatInfo('ASTC_RGBA_10x8', 1, 4, FormatType.UNORM, true, false, false, true), new FormatInfo('ASTC_RGBA_10x10', 1, 4, FormatType.UNORM, true, false, false, true), new FormatInfo('ASTC_RGBA_12x10', 1, 4, FormatType.UNORM, true, false, false, true), new FormatInfo('ASTC_RGBA_12x12', 1, 4, FormatType.UNORM, true, false, false, true), new FormatInfo('ASTC_SRGBA_4x4', 1, 4, FormatType.UNORM, true, false, false, true), new FormatInfo('ASTC_SRGBA_5x4', 1, 4, FormatType.UNORM, true, false, false, true), new FormatInfo('ASTC_SRGBA_5x5', 1, 4, FormatType.UNORM, true, false, false, true), new FormatInfo('ASTC_SRGBA_6x5', 1, 4, FormatType.UNORM, true, false, false, true), new FormatInfo('ASTC_SRGBA_6x6', 1, 4, FormatType.UNORM, true, false, false, true), new FormatInfo('ASTC_SRGBA_8x5', 1, 4, FormatType.UNORM, true, false, false, true), new FormatInfo('ASTC_SRGBA_8x6', 1, 4, FormatType.UNORM, true, false, false, true), new FormatInfo('ASTC_SRGBA_8x8', 1, 4, FormatType.UNORM, true, false, false, true), new FormatInfo('ASTC_SRGBA_10x5', 1, 4, FormatType.UNORM, true, false, false, true), new FormatInfo('ASTC_SRGBA_10x6', 1, 4, FormatType.UNORM, true, false, false, true), new FormatInfo('ASTC_SRGBA_10x8', 1, 4, FormatType.UNORM, true, false, false, true), new FormatInfo('ASTC_SRGBA_10x10', 1, 4, FormatType.UNORM, true, false, false, true), new FormatInfo('ASTC_SRGBA_12x10', 1, 4, FormatType.UNORM, true, false, false, true), new FormatInfo('ASTC_SRGBA_12x12', 1, 4, FormatType.UNORM, true, false, false, true)]);
      var DESCRIPTOR_BUFFER_TYPE = DescriptorType.UNIFORM_BUFFER | DescriptorType.DYNAMIC_UNIFORM_BUFFER | DescriptorType.STORAGE_BUFFER | DescriptorType.DYNAMIC_STORAGE_BUFFER;
      var DESCRIPTOR_SAMPLER_TYPE = DescriptorType.SAMPLER_TEXTURE | DescriptorType.SAMPLER | DescriptorType.TEXTURE | DescriptorType.STORAGE_IMAGE | DescriptorType.INPUT_ATTACHMENT;
      var DESCRIPTOR_DYNAMIC_TYPE = DescriptorType.DYNAMIC_STORAGE_BUFFER | DescriptorType.DYNAMIC_UNIFORM_BUFFER;
      var DRAW_INFO_SIZE = 28;
      function IsPowerOf2(x) {
        return x > 0 && (x & x - 1) === 0;
      }
      function FormatSize(format, width, height, depth) {
        if (!FormatInfos[format].isCompressed) {
          return width * height * depth * FormatInfos[format].size;
        } else {
          switch (format) {
            case Format.BC1:
            case Format.BC1_ALPHA:
            case Format.BC1_SRGB:
            case Format.BC1_SRGB_ALPHA:
              return Math.ceil(width / 4) * Math.ceil(height / 4) * 8 * depth;
            case Format.BC2:
            case Format.BC2_SRGB:
            case Format.BC3:
            case Format.BC3_SRGB:
            case Format.BC4:
            case Format.BC4_SNORM:
            case Format.BC6H_SF16:
            case Format.BC6H_UF16:
            case Format.BC7:
            case Format.BC7_SRGB:
              return Math.ceil(width / 4) * Math.ceil(height / 4) * 16 * depth;
            case Format.BC5:
            case Format.BC5_SNORM:
              return Math.ceil(width / 4) * Math.ceil(height / 4) * 32 * depth;
            case Format.ETC_RGB8:
            case Format.ETC2_RGB8:
            case Format.ETC2_SRGB8:
            case Format.ETC2_RGB8_A1:
            case Format.EAC_R11:
            case Format.EAC_R11SN:
              return Math.ceil(width / 4) * Math.ceil(height / 4) * 8 * depth;
            case Format.ETC2_RGBA8:
            case Format.ETC2_SRGB8_A1:
            case Format.EAC_RG11:
            case Format.EAC_RG11SN:
              return Math.ceil(width / 4) * Math.ceil(height / 4) * 16 * depth;
            case Format.PVRTC_RGB2:
            case Format.PVRTC_RGBA2:
            case Format.PVRTC2_2BPP:
              return Math.ceil(width / 8) * Math.ceil(height / 4) * 8 * depth;
            case Format.PVRTC_RGB4:
            case Format.PVRTC_RGBA4:
            case Format.PVRTC2_4BPP:
              return Math.ceil(width / 4) * Math.ceil(height / 4) * 8 * depth;
            case Format.ASTC_RGBA_4X4:
            case Format.ASTC_SRGBA_4X4:
              return Math.ceil(width / 4) * Math.ceil(height / 4) * 16 * depth;
            case Format.ASTC_RGBA_5X4:
            case Format.ASTC_SRGBA_5X4:
              return Math.ceil(width / 5) * Math.ceil(height / 4) * 16 * depth;
            case Format.ASTC_RGBA_5X5:
            case Format.ASTC_SRGBA_5X5:
              return Math.ceil(width / 5) * Math.ceil(height / 5) * 16 * depth;
            case Format.ASTC_RGBA_6X5:
            case Format.ASTC_SRGBA_6X5:
              return Math.ceil(width / 6) * Math.ceil(height / 5) * 16 * depth;
            case Format.ASTC_RGBA_6X6:
            case Format.ASTC_SRGBA_6X6:
              return Math.ceil(width / 6) * Math.ceil(height / 6) * 16 * depth;
            case Format.ASTC_RGBA_8X5:
            case Format.ASTC_SRGBA_8X5:
              return Math.ceil(width / 8) * Math.ceil(height / 5) * 16 * depth;
            case Format.ASTC_RGBA_8X6:
            case Format.ASTC_SRGBA_8X6:
              return Math.ceil(width / 8) * Math.ceil(height / 6) * 16 * depth;
            case Format.ASTC_RGBA_8X8:
            case Format.ASTC_SRGBA_8X8:
              return Math.ceil(width / 8) * Math.ceil(height / 8) * 16 * depth;
            case Format.ASTC_RGBA_10X5:
            case Format.ASTC_SRGBA_10X5:
              return Math.ceil(width / 10) * Math.ceil(height / 5) * 16 * depth;
            case Format.ASTC_RGBA_10X6:
            case Format.ASTC_SRGBA_10X6:
              return Math.ceil(width / 10) * Math.ceil(height / 6) * 16 * depth;
            case Format.ASTC_RGBA_10X8:
            case Format.ASTC_SRGBA_10X8:
              return Math.ceil(width / 10) * Math.ceil(height / 8) * 16 * depth;
            case Format.ASTC_RGBA_10X10:
            case Format.ASTC_SRGBA_10X10:
              return Math.ceil(width / 10) * Math.ceil(height / 10) * 16 * depth;
            case Format.ASTC_RGBA_12X10:
            case Format.ASTC_SRGBA_12X10:
              return Math.ceil(width / 12) * Math.ceil(height / 10) * 16 * depth;
            case Format.ASTC_RGBA_12X12:
            case Format.ASTC_SRGBA_12X12:
              return Math.ceil(width / 12) * Math.ceil(height / 12) * 16 * depth;
            default:
              {
                return 0;
              }
          }
        }
      }
      function FormatSurfaceSize(format, width, height, depth, mips) {
        var size = 0;
        for (var i = 0; i < mips; ++i) {
          size += FormatSize(format, width, height, depth);
          width = Math.max(width >> 1, 1);
          height = Math.max(height >> 1, 1);
        }
        return size;
      }
      var _type2size = [0, 4, 8, 12, 16, 4, 8, 12, 16, 4, 8, 12, 16, 4, 8, 12, 16, 16, 24, 32, 24, 36, 48, 32, 48, 64, 4, 4, 4, 4, 4, 4];
      function GetTypeSize(type) {
        return _type2size[type] || 0;
      }
      function getTypedArrayConstructor(info) {
        if (info.isCompressed) {
          return Uint8Array;
        }
        var stride = info.size / info.count;
        switch (info.type) {
          case FormatType.UNORM:
          case FormatType.UINT:
            {
              switch (stride) {
                case 1:
                  return Uint8Array;
                case 2:
                  return Uint16Array;
                case 4:
                  return Uint32Array;
                default:
                  return Uint8Array;
              }
            }
          case FormatType.SNORM:
          case FormatType.INT:
            {
              switch (stride) {
                case 1:
                  return Int8Array;
                case 2:
                  return Int16Array;
                case 4:
                  return Int32Array;
                default:
                  return Int8Array;
              }
            }
          case FormatType.FLOAT:
            {
              switch (stride) {
                case 2:
                  return Uint16Array;
                case 4:
                  return Float32Array;
                default:
                  return Float32Array;
              }
            }
        }
        return Float32Array;
      }
      function formatAlignment(format) {
        switch (format) {
          case Format.BC1:
          case Format.BC1_ALPHA:
          case Format.BC1_SRGB:
          case Format.BC1_SRGB_ALPHA:
          case Format.BC2:
          case Format.BC2_SRGB:
          case Format.BC3:
          case Format.BC3_SRGB:
          case Format.BC4:
          case Format.BC4_SNORM:
          case Format.BC6H_SF16:
          case Format.BC6H_UF16:
          case Format.BC7:
          case Format.BC7_SRGB:
          case Format.BC5:
          case Format.BC5_SNORM:
          case Format.ETC_RGB8:
          case Format.ETC2_RGB8:
          case Format.ETC2_SRGB8:
          case Format.ETC2_RGB8_A1:
          case Format.EAC_R11:
          case Format.EAC_R11SN:
          case Format.ETC2_RGBA8:
          case Format.ETC2_SRGB8_A1:
          case Format.EAC_RG11:
          case Format.EAC_RG11SN:
            return {
              width: 4,
              height: 4
            };
          case Format.PVRTC_RGB2:
          case Format.PVRTC_RGBA2:
          case Format.PVRTC2_2BPP:
            return {
              width: 8,
              height: 4
            };
          case Format.PVRTC_RGB4:
          case Format.PVRTC_RGBA4:
          case Format.PVRTC2_4BPP:
            return {
              width: 4,
              height: 4
            };
          case Format.ASTC_RGBA_4X4:
          case Format.ASTC_SRGBA_4X4:
            return {
              width: 4,
              height: 4
            };
          case Format.ASTC_RGBA_5X4:
          case Format.ASTC_SRGBA_5X4:
            return {
              width: 5,
              height: 4
            };
          case Format.ASTC_RGBA_5X5:
          case Format.ASTC_SRGBA_5X5:
            return {
              width: 5,
              height: 5
            };
          case Format.ASTC_RGBA_6X5:
          case Format.ASTC_SRGBA_6X5:
            return {
              width: 6,
              height: 5
            };
          case Format.ASTC_RGBA_6X6:
          case Format.ASTC_SRGBA_6X6:
            return {
              width: 6,
              height: 6
            };
          case Format.ASTC_RGBA_8X5:
          case Format.ASTC_SRGBA_8X5:
            return {
              width: 8,
              height: 5
            };
          case Format.ASTC_RGBA_8X6:
          case Format.ASTC_SRGBA_8X6:
            return {
              width: 8,
              height: 6
            };
          case Format.ASTC_RGBA_8X8:
          case Format.ASTC_SRGBA_8X8:
            return {
              width: 8,
              height: 8
            };
          case Format.ASTC_RGBA_10X5:
          case Format.ASTC_SRGBA_10X5:
            return {
              width: 10,
              height: 5
            };
          case Format.ASTC_RGBA_10X6:
          case Format.ASTC_SRGBA_10X6:
            return {
              width: 10,
              height: 6
            };
          case Format.ASTC_RGBA_10X8:
          case Format.ASTC_SRGBA_10X8:
            return {
              width: 10,
              height: 8
            };
          case Format.ASTC_RGBA_10X10:
          case Format.ASTC_SRGBA_10X10:
            return {
              width: 10,
              height: 10
            };
          case Format.ASTC_RGBA_12X10:
          case Format.ASTC_SRGBA_12X10:
            return {
              width: 12,
              height: 10
            };
          case Format.ASTC_RGBA_12X12:
          case Format.ASTC_SRGBA_12X12:
            return {
              width: 12,
              height: 12
            };
          default:
            return {
              width: 1,
              height: 1
            };
        }
      }
      function alignTo(size, alignment) {
        return Math.ceil(size / alignment) * alignment;
      }

      var defines = /*#__PURE__*/Object.freeze({
        __proto__: null,
        get ObjectType () { return ObjectType; },
        get Status () { return Status; },
        get API () { return API; },
        get SurfaceTransform () { return SurfaceTransform; },
        get Feature () { return Feature; },
        get Format () { return Format; },
        get FormatType () { return FormatType; },
        get Type () { return Type$1; },
        get BufferUsageBit () { return BufferUsageBit; },
        get BufferFlagBit () { return BufferFlagBit; },
        get MemoryAccessBit () { return MemoryAccessBit; },
        get MemoryUsageBit () { return MemoryUsageBit; },
        get TextureType () { return TextureType; },
        get TextureUsageBit () { return TextureUsageBit; },
        get TextureFlagBit () { return TextureFlagBit; },
        get FormatFeatureBit () { return FormatFeatureBit; },
        get SampleCount () { return SampleCount; },
        get VsyncMode () { return VsyncMode; },
        get Filter () { return Filter$1; },
        get Address () { return Address; },
        get ComparisonFunc () { return ComparisonFunc; },
        get StencilOp () { return StencilOp; },
        get BlendFactor () { return BlendFactor; },
        get BlendOp () { return BlendOp; },
        get ColorMask () { return ColorMask; },
        get ShaderStageFlagBit () { return ShaderStageFlagBit; },
        get LoadOp () { return LoadOp; },
        get StoreOp () { return StoreOp; },
        get AccessFlagBit () { return AccessFlagBit; },
        get ResolveMode () { return ResolveMode; },
        get PipelineBindPoint () { return PipelineBindPoint; },
        get PrimitiveMode () { return PrimitiveMode; },
        get PolygonMode () { return PolygonMode; },
        get ShadeModel () { return ShadeModel; },
        get CullMode () { return CullMode; },
        get DynamicStateFlagBit () { return DynamicStateFlagBit; },
        get StencilFace () { return StencilFace; },
        get DescriptorType () { return DescriptorType; },
        get QueueType () { return QueueType; },
        get QueryType () { return QueryType; },
        get CommandBufferType () { return CommandBufferType; },
        get ClearFlagBit () { return ClearFlagBit; },
        get BarrierType () { return BarrierType; },
        get PassType () { return PassType; },
        Size: Size,
        DeviceCaps: DeviceCaps,
        DeviceOptions: DeviceOptions,
        Offset: Offset,
        Rect: Rect,
        Extent: Extent,
        TextureSubresLayers: TextureSubresLayers,
        TextureSubresRange: TextureSubresRange,
        TextureCopy: TextureCopy,
        TextureBlit: TextureBlit,
        BufferTextureCopy: BufferTextureCopy,
        Viewport: Viewport,
        Color: Color,
        BindingMappingInfo: BindingMappingInfo,
        SwapchainInfo: SwapchainInfo,
        DeviceInfo: DeviceInfo,
        BufferInfo: BufferInfo,
        BufferViewInfo: BufferViewInfo,
        DrawInfo: DrawInfo,
        DispatchInfo: DispatchInfo,
        IndirectBuffer: IndirectBuffer,
        TextureInfo: TextureInfo,
        TextureViewInfo: TextureViewInfo,
        SamplerInfo: SamplerInfo,
        Uniform: Uniform,
        UniformBlock: UniformBlock,
        UniformSamplerTexture: UniformSamplerTexture,
        UniformSampler: UniformSampler,
        UniformTexture: UniformTexture,
        UniformStorageImage: UniformStorageImage,
        UniformStorageBuffer: UniformStorageBuffer,
        UniformInputAttachment: UniformInputAttachment,
        ShaderStage: ShaderStage,
        Attribute: Attribute,
        ShaderInfo: ShaderInfo,
        InputAssemblerInfo: InputAssemblerInfo,
        ColorAttachment: ColorAttachment,
        DepthStencilAttachment: DepthStencilAttachment,
        SubpassInfo: SubpassInfo,
        SubpassDependency: SubpassDependency,
        RenderPassInfo: RenderPassInfo,
        GeneralBarrierInfo: GeneralBarrierInfo,
        TextureBarrierInfo: TextureBarrierInfo,
        BufferBarrierInfo: BufferBarrierInfo,
        FramebufferInfo: FramebufferInfo,
        DescriptorSetLayoutBinding: DescriptorSetLayoutBinding,
        DescriptorSetLayoutInfo: DescriptorSetLayoutInfo,
        DescriptorSetInfo: DescriptorSetInfo,
        PipelineLayoutInfo: PipelineLayoutInfo,
        InputState: InputState,
        CommandBufferInfo: CommandBufferInfo,
        QueueInfo: QueueInfo,
        QueryPoolInfo: QueryPoolInfo,
        FormatInfo: FormatInfo,
        MemoryStatus: MemoryStatus,
        DynamicStencilStates: DynamicStencilStates,
        DynamicStates: DynamicStates,
        GFXObject: GFXObject,
        get AttributeName () { return AttributeName; },
        FormatInfos: FormatInfos,
        DESCRIPTOR_BUFFER_TYPE: DESCRIPTOR_BUFFER_TYPE,
        DESCRIPTOR_SAMPLER_TYPE: DESCRIPTOR_SAMPLER_TYPE,
        DESCRIPTOR_DYNAMIC_TYPE: DESCRIPTOR_DYNAMIC_TYPE,
        DRAW_INFO_SIZE: DRAW_INFO_SIZE,
        IsPowerOf2: IsPowerOf2,
        FormatSize: FormatSize,
        FormatSurfaceSize: FormatSurfaceSize,
        GetTypeSize: GetTypeSize,
        getTypedArrayConstructor: getTypedArrayConstructor,
        formatAlignment: formatAlignment,
        alignTo: alignTo
      });

      var Buffer = function (_GFXObject) {
        _inheritsLoose(Buffer, _GFXObject);
        function Buffer() {
          var _this;
          _this = _GFXObject.call(this, ObjectType.BUFFER) || this;
          _this._usage = BufferUsageBit.NONE;
          _this._memUsage = MemoryUsageBit.NONE;
          _this._size = 0;
          _this._stride = 1;
          _this._count = 0;
          _this._flags = BufferFlagBit.NONE;
          _this._isBufferView = false;
          return _this;
        }
        _createClass(Buffer, [{
          key: "usage",
          get: function get() {
            return this._usage;
          }
        }, {
          key: "memUsage",
          get: function get() {
            return this._memUsage;
          }
        }, {
          key: "size",
          get: function get() {
            return this._size;
          }
        }, {
          key: "stride",
          get: function get() {
            return this._stride;
          }
        }, {
          key: "count",
          get: function get() {
            return this._count;
          }
        }, {
          key: "flags",
          get: function get() {
            return this._flags;
          }
        }]);
        return Buffer;
      }(GFXObject);

      var CommandBuffer = function (_GFXObject) {
        _inheritsLoose(CommandBuffer, _GFXObject);
        function CommandBuffer() {
          var _this;
          _this = _GFXObject.call(this, ObjectType.COMMAND_BUFFER) || this;
          _this._queue = null;
          _this._type = CommandBufferType.PRIMARY;
          _this._numDrawCalls = 0;
          _this._numInstances = 0;
          _this._numTris = 0;
          return _this;
        }
        _createClass(CommandBuffer, [{
          key: "type",
          get: function get() {
            return this._type;
          }
        }, {
          key: "queue",
          get: function get() {
            return this._queue;
          }
        }, {
          key: "numDrawCalls",
          get: function get() {
            return this._numDrawCalls;
          }
        }, {
          key: "numInstances",
          get: function get() {
            return this._numInstances;
          }
        }, {
          key: "numTris",
          get: function get() {
            return this._numTris;
          }
        }]);
        return CommandBuffer;
      }(GFXObject);

      var Device = function () {
        function Device() {
          this._gfxAPI = API.UNKNOWN;
          this._renderer = '';
          this._vendor = '';
          this._features = new Array(Feature.COUNT);
          this._formatFeatures = new Array(Format.COUNT);
          this._queue = null;
          this._cmdBuff = null;
          this._numDrawCalls = 0;
          this._numInstances = 0;
          this._numTris = 0;
          this._memoryStatus = new MemoryStatus();
          this._caps = new DeviceCaps();
          this._bindingMappingInfo = new BindingMappingInfo();
          this._samplers = new Map();
          this._generalBarrierss = new Map();
          this._textureBarriers = new Map();
          this._bufferBarriers = new Map();
        }
        var _proto = Device.prototype;
        _proto.hasFeature = function hasFeature(feature) {
          return this._features[feature];
        };
        _proto.getFormatFeatures = function getFormatFeatures(format) {
          return this._formatFeatures[format];
        };
        _proto.enableAutoBarrier = function enableAutoBarrier(en) {};
        _proto.getMaxSampleCount = function getMaxSampleCount(format, usage, flags) {
          return SampleCount.X1;
        };
        _createClass(Device, [{
          key: "gfxAPI",
          get: function get() {
            return this._gfxAPI;
          }
        }, {
          key: "queue",
          get: function get() {
            return this._queue;
          }
        }, {
          key: "commandBuffer",
          get: function get() {
            return this._cmdBuff;
          }
        }, {
          key: "renderer",
          get: function get() {
            return this._renderer;
          }
        }, {
          key: "vendor",
          get: function get() {
            return this._vendor;
          }
        }, {
          key: "numDrawCalls",
          get: function get() {
            return this._numDrawCalls;
          }
        }, {
          key: "numInstances",
          get: function get() {
            return this._numInstances;
          }
        }, {
          key: "numTris",
          get: function get() {
            return this._numTris;
          }
        }, {
          key: "memoryStatus",
          get: function get() {
            return this._memoryStatus;
          }
        }, {
          key: "capabilities",
          get: function get() {
            return this._caps;
          }
        }, {
          key: "bindingMappingInfo",
          get: function get() {
            return this._bindingMappingInfo;
          }
        }]);
        return Device;
      }();
      Device.canvas = void 0;
      var DefaultResource = function () {
        function DefaultResource(device) {
          this._texture2D = null;
          this._texture3D = null;
          this._textureCube = null;
          this._texture2DArray = null;
          var bufferSize = 64;
          var buffer = new Uint8Array(bufferSize);
          buffer.fill(255);
          if (device.capabilities.maxTextureSize >= 2) {
            this._texture2D = device.createTexture(new TextureInfo(TextureType.TEX2D, TextureUsageBit.STORAGE | TextureUsageBit.SAMPLED, Format.RGBA8, 2, 2, TextureFlagBit.NONE));
            var copyRegion = new BufferTextureCopy(0, 0, 0, new Offset(0, 0, 0), new Extent(2, 2, 1));
            device.copyBuffersToTexture([buffer], this._texture2D, [copyRegion]);
          }
          if (device.capabilities.maxTextureSize >= 2) {
            this._textureCube = device.createTexture(new TextureInfo(TextureType.CUBE, TextureUsageBit.STORAGE | TextureUsageBit.SAMPLED, Format.RGBA8, 2, 2, TextureFlagBit.NONE, 6));
            var _copyRegion = new BufferTextureCopy(0, 0, 0, new Offset(0, 0, 0), new Extent(2, 2, 1));
            device.copyBuffersToTexture([buffer], this._textureCube, [_copyRegion]);
            _copyRegion.texSubres.baseArrayLayer = 1;
            device.copyBuffersToTexture([buffer], this._textureCube, [_copyRegion]);
            _copyRegion.texSubres.baseArrayLayer = 2;
            device.copyBuffersToTexture([buffer], this._textureCube, [_copyRegion]);
            _copyRegion.texSubres.baseArrayLayer = 3;
            device.copyBuffersToTexture([buffer], this._textureCube, [_copyRegion]);
            _copyRegion.texSubres.baseArrayLayer = 4;
            device.copyBuffersToTexture([buffer], this._textureCube, [_copyRegion]);
            _copyRegion.texSubres.baseArrayLayer = 5;
            device.copyBuffersToTexture([buffer], this._textureCube, [_copyRegion]);
          }
          if (device.capabilities.max3DTextureSize >= 2) {
            this._texture3D = device.createTexture(new TextureInfo(TextureType.TEX3D, TextureUsageBit.STORAGE | TextureUsageBit.SAMPLED, Format.RGBA8, 2, 2, TextureFlagBit.NONE, 1, 1, SampleCount.X1, 2));
            var _copyRegion2 = new BufferTextureCopy(0, 0, 0, new Offset(0, 0, 0), new Extent(2, 2, 2), new TextureSubresLayers(0, 0, 1));
            device.copyBuffersToTexture([buffer], this._texture3D, [_copyRegion2]);
          }
          if (device.capabilities.maxArrayTextureLayers >= 2) {
            this._texture2DArray = device.createTexture(new TextureInfo(TextureType.TEX2D_ARRAY, TextureUsageBit.STORAGE | TextureUsageBit.SAMPLED, Format.RGBA8, 2, 2, TextureFlagBit.NONE, 2));
            var _copyRegion3 = new BufferTextureCopy(0, 0, 0, new Offset(0, 0, 0), new Extent(2, 2, 1), new TextureSubresLayers(0, 0, 1));
            device.copyBuffersToTexture([buffer], this._texture2DArray, [_copyRegion3]);
            _copyRegion3.texSubres.baseArrayLayer = 1;
            device.copyBuffersToTexture([buffer], this._texture2DArray, [_copyRegion3]);
          }
        }
        var _proto2 = DefaultResource.prototype;
        _proto2.getTexture = function getTexture(type) {
          switch (type) {
            case TextureType.TEX2D:
              return this._texture2D;
            case TextureType.TEX3D:
              return this._texture3D;
            case TextureType.CUBE:
              return this._textureCube;
            case TextureType.TEX2D_ARRAY:
              return this._texture2DArray;
            default:
              return null;
          }
        };
        return DefaultResource;
      }();

      var Swapchain = function (_GFXObject) {
        _inheritsLoose(Swapchain, _GFXObject);
        function Swapchain() {
          var _this;
          _this = _GFXObject.call(this, ObjectType.SWAPCHAIN) || this;
          _this._transform = SurfaceTransform.IDENTITY;
          _this._colorTexture = null;
          _this._depthStencilTexture = null;
          return _this;
        }
        _createClass(Swapchain, [{
          key: "colorTexture",
          get: function get() {
            return this._colorTexture;
          }
        }, {
          key: "depthStencilTexture",
          get: function get() {
            return this._depthStencilTexture;
          }
        }, {
          key: "surfaceTransform",
          get: function get() {
            return this._transform;
          }
        }, {
          key: "width",
          get: function get() {
            return this._colorTexture.width;
          }
        }, {
          key: "height",
          get: function get() {
            return this._colorTexture.height;
          }
        }]);
        return Swapchain;
      }(GFXObject);

      var Framebuffer = function (_GFXObject) {
        _inheritsLoose(Framebuffer, _GFXObject);
        function Framebuffer() {
          var _this;
          _this = _GFXObject.call(this, ObjectType.FRAMEBUFFER) || this;
          _this._renderPass = null;
          _this._colorTextures = [];
          _this._depthStencilTexture = null;
          _this._width = 0;
          _this._height = 0;
          return _this;
        }
        _createClass(Framebuffer, [{
          key: "renderPass",
          get: function get() {
            return this._renderPass;
          }
        }, {
          key: "colorTextures",
          get: function get() {
            return this._colorTextures;
          }
        }, {
          key: "depthStencilTexture",
          get: function get() {
            return this._depthStencilTexture;
          }
        }, {
          key: "width",
          get: function get() {
            return this._width;
          }
        }, {
          key: "height",
          get: function get() {
            return this._height;
          }
        }]);
        return Framebuffer;
      }(GFXObject);

      var InputAssembler = function (_GFXObject) {
        _inheritsLoose(InputAssembler, _GFXObject);
        function InputAssembler() {
          var _this;
          _this = _GFXObject.call(this, ObjectType.INPUT_ASSEMBLER) || this;
          _this._attributes = [];
          _this._attributesHash = 0;
          _this._vertexBuffers = [];
          _this._indexBuffer = null;
          _this._indirectBuffer = null;
          _this._drawInfo = new DrawInfo();
          return _this;
        }
        var _proto = InputAssembler.prototype;
        _proto.getVertexBuffer = function getVertexBuffer(stream) {
          if (stream === void 0) {
            stream = 0;
          }
          if (stream < this._vertexBuffers.length) {
            return this._vertexBuffers[stream];
          } else {
            return null;
          }
        };
        _proto.computeAttributesHash = function computeAttributesHash() {
          var res = 'attrs';
          for (var i = 0; i < this.attributes.length; ++i) {
            var at = this.attributes[i];
            res += "," + at.name + "," + at.format + "," + at.isNormalized + "," + at.stream + "," + at.isInstanced + "," + at.location;
          }
          return murmurhash2_32_gc(res, 666);
        };
        _createClass(InputAssembler, [{
          key: "attributes",
          get: function get() {
            return this._attributes;
          }
        }, {
          key: "vertexBuffers",
          get: function get() {
            return this._vertexBuffers;
          }
        }, {
          key: "indexBuffer",
          get: function get() {
            return this._indexBuffer;
          }
        }, {
          key: "indirectBuffer",
          get: function get() {
            return this._indirectBuffer;
          }
        }, {
          key: "attributesHash",
          get: function get() {
            return this._attributesHash;
          }
        }, {
          key: "vertexCount",
          get: function get() {
            return this._drawInfo.vertexCount;
          },
          set: function set(count) {
            this._drawInfo.vertexCount = count;
          }
        }, {
          key: "firstVertex",
          get: function get() {
            return this._drawInfo.firstVertex;
          },
          set: function set(first) {
            this._drawInfo.firstVertex = first;
          }
        }, {
          key: "indexCount",
          get: function get() {
            return this._drawInfo.indexCount;
          },
          set: function set(count) {
            this._drawInfo.indexCount = count;
          }
        }, {
          key: "firstIndex",
          get: function get() {
            return this._drawInfo.firstIndex;
          },
          set: function set(first) {
            this._drawInfo.firstIndex = first;
          }
        }, {
          key: "vertexOffset",
          get: function get() {
            return this._drawInfo.vertexOffset;
          },
          set: function set(offset) {
            this._drawInfo.vertexOffset = offset;
          }
        }, {
          key: "instanceCount",
          get: function get() {
            return this._drawInfo.instanceCount;
          },
          set: function set(count) {
            this._drawInfo.instanceCount = count;
          }
        }, {
          key: "firstInstance",
          get: function get() {
            return this._drawInfo.firstInstance;
          },
          set: function set(first) {
            this._drawInfo.firstInstance = first;
          }
        }, {
          key: "drawInfo",
          get: function get() {
            return this._drawInfo;
          },
          set: function set(info) {
            this._drawInfo = info;
          }
        }]);
        return InputAssembler;
      }(GFXObject);

      var DescriptorSet = function (_GFXObject) {
        _inheritsLoose(DescriptorSet, _GFXObject);
        function DescriptorSet() {
          var _this;
          _this = _GFXObject.call(this, ObjectType.DESCRIPTOR_SET) || this;
          _this._layout = null;
          _this._buffers = [];
          _this._textures = [];
          _this._samplers = [];
          _this._isDirty = false;
          return _this;
        }
        var _proto = DescriptorSet.prototype;
        _proto.bindBuffer = function bindBuffer(binding, buffer, index) {
          if (index === void 0) {
            index = 0;
          }
          var bindingIndex = this._layout.bindingIndices[binding];
          var info = this._layout.bindings[bindingIndex];
          if (!info) {
            return;
          }
          if (info.descriptorType & DESCRIPTOR_BUFFER_TYPE) {
            var descriptorIndex = this._layout.descriptorIndices[binding];
            if (this._buffers[descriptorIndex + index] !== buffer) {
              this._buffers[descriptorIndex + index] = buffer;
              this._isDirty = true;
            }
          }
        };
        _proto.bindSampler = function bindSampler(binding, sampler, index) {
          if (index === void 0) {
            index = 0;
          }
          var bindingIndex = this._layout.bindingIndices[binding];
          var info = this._layout.bindings[bindingIndex];
          if (!info) {
            return;
          }
          if (info.descriptorType & DESCRIPTOR_SAMPLER_TYPE) {
            var descriptorIndex = this._layout.descriptorIndices[binding];
            if (this._samplers[descriptorIndex + index] !== sampler) {
              this._samplers[descriptorIndex + index] = sampler;
              this._isDirty = true;
            }
          }
        };
        _proto.bindTexture = function bindTexture(binding, texture, index, flags) {
          if (index === void 0) {
            index = 0;
          }
          var bindingIndex = this._layout.bindingIndices[binding];
          var info = this._layout.bindings[bindingIndex];
          if (!info) {
            return;
          }
          if (info.descriptorType & DESCRIPTOR_SAMPLER_TYPE) {
            var descriptorIndex = this._layout.descriptorIndices[binding];
            if (this._textures[descriptorIndex + index] !== texture) {
              this._textures[descriptorIndex + index] = texture;
              this._isDirty = true;
            }
          }
        };
        _proto.getBuffer = function getBuffer(binding, index) {
          if (index === void 0) {
            index = 0;
          }
          var descriptorIndex = this._layout.descriptorIndices[binding];
          return this._buffers[descriptorIndex + index];
        };
        _proto.getSampler = function getSampler(binding, index) {
          if (index === void 0) {
            index = 0;
          }
          var descriptorIndex = this._layout.descriptorIndices[binding];
          return this._samplers[descriptorIndex + index];
        };
        _proto.getTexture = function getTexture(binding, index) {
          if (index === void 0) {
            index = 0;
          }
          var descriptorIndex = this._layout.descriptorIndices[binding];
          return this._textures[descriptorIndex + index];
        };
        _createClass(DescriptorSet, [{
          key: "layout",
          get: function get() {
            return this._layout;
          }
        }]);
        return DescriptorSet;
      }(GFXObject);

      var DescriptorSetLayout = function (_GFXObject) {
        _inheritsLoose(DescriptorSetLayout, _GFXObject);
        function DescriptorSetLayout() {
          var _this;
          _this = _GFXObject.call(this, ObjectType.DESCRIPTOR_SET_LAYOUT) || this;
          _this._bindings = [];
          _this._bindingIndices = [];
          _this._descriptorIndices = [];
          return _this;
        }
        _createClass(DescriptorSetLayout, [{
          key: "bindings",
          get: function get() {
            return this._bindings;
          }
        }, {
          key: "bindingIndices",
          get: function get() {
            return this._bindingIndices;
          }
        }, {
          key: "descriptorIndices",
          get: function get() {
            return this._descriptorIndices;
          }
        }]);
        return DescriptorSetLayout;
      }(GFXObject);

      var PipelineLayout = function (_GFXObject) {
        _inheritsLoose(PipelineLayout, _GFXObject);
        function PipelineLayout() {
          var _this;
          _this = _GFXObject.call(this, ObjectType.PIPELINE_LAYOUT) || this;
          _this._setLayouts = [];
          return _this;
        }
        _createClass(PipelineLayout, [{
          key: "setLayouts",
          get: function get() {
            return this._setLayouts;
          }
        }]);
        return PipelineLayout;
      }(GFXObject);

      var RasterizerState = function () {
        function RasterizerState(isDiscard, polygonMode, shadeModel, cullMode, isFrontFaceCCW, depthBiasEnabled, depthBias, depthBiasClamp, depthBiasSlop, isDepthClip, isMultisample, lineWidth) {
          if (isDiscard === void 0) {
            isDiscard = false;
          }
          if (polygonMode === void 0) {
            polygonMode = PolygonMode.FILL;
          }
          if (shadeModel === void 0) {
            shadeModel = ShadeModel.GOURAND;
          }
          if (cullMode === void 0) {
            cullMode = CullMode.BACK;
          }
          if (isFrontFaceCCW === void 0) {
            isFrontFaceCCW = true;
          }
          if (depthBiasEnabled === void 0) {
            depthBiasEnabled = false;
          }
          if (depthBias === void 0) {
            depthBias = 0;
          }
          if (depthBiasClamp === void 0) {
            depthBiasClamp = 0.0;
          }
          if (depthBiasSlop === void 0) {
            depthBiasSlop = 0.0;
          }
          if (isDepthClip === void 0) {
            isDepthClip = true;
          }
          if (isMultisample === void 0) {
            isMultisample = false;
          }
          if (lineWidth === void 0) {
            lineWidth = 1.0;
          }
          this.isDiscard = isDiscard;
          this.polygonMode = polygonMode;
          this.shadeModel = shadeModel;
          this.cullMode = cullMode;
          this.isFrontFaceCCW = isFrontFaceCCW;
          this.depthBiasEnabled = depthBiasEnabled;
          this.depthBias = depthBias;
          this.depthBiasClamp = depthBiasClamp;
          this.depthBiasSlop = depthBiasSlop;
          this.isDepthClip = isDepthClip;
          this.isMultisample = isMultisample;
          this.lineWidth = lineWidth;
        }
        var _proto = RasterizerState.prototype;
        _proto.reset = function reset() {
          this.isDiscard = false;
          this.polygonMode = PolygonMode.FILL;
          this.shadeModel = ShadeModel.GOURAND;
          this.cullMode = CullMode.BACK;
          this.isFrontFaceCCW = true;
          this.depthBiasEnabled = false;
          this.depthBias = 0;
          this.depthBiasClamp = 0.0;
          this.depthBiasSlop = 0.0;
          this.isDepthClip = true;
          this.isMultisample = false;
          this.lineWidth = 1.0;
        };
        _proto.assign = function assign(rs) {
          Object.assign(this, rs);
        };
        _proto.destroy = function destroy() {};
        _createClass(RasterizerState, [{
          key: "native",
          get: function get() {
            return this;
          }
        }]);
        return RasterizerState;
      }();
      var DepthStencilState = function () {
        function DepthStencilState(depthTest, depthWrite, depthFunc, stencilTestFront, stencilFuncFront, stencilReadMaskFront, stencilWriteMaskFront, stencilFailOpFront, stencilZFailOpFront, stencilPassOpFront, stencilRefFront, stencilTestBack, stencilFuncBack, stencilReadMaskBack, stencilWriteMaskBack, stencilFailOpBack, stencilZFailOpBack, stencilPassOpBack, stencilRefBack) {
          if (depthTest === void 0) {
            depthTest = true;
          }
          if (depthWrite === void 0) {
            depthWrite = true;
          }
          if (depthFunc === void 0) {
            depthFunc = ComparisonFunc.LESS;
          }
          if (stencilTestFront === void 0) {
            stencilTestFront = false;
          }
          if (stencilFuncFront === void 0) {
            stencilFuncFront = ComparisonFunc.ALWAYS;
          }
          if (stencilReadMaskFront === void 0) {
            stencilReadMaskFront = 0xffff;
          }
          if (stencilWriteMaskFront === void 0) {
            stencilWriteMaskFront = 0xffff;
          }
          if (stencilFailOpFront === void 0) {
            stencilFailOpFront = StencilOp.KEEP;
          }
          if (stencilZFailOpFront === void 0) {
            stencilZFailOpFront = StencilOp.KEEP;
          }
          if (stencilPassOpFront === void 0) {
            stencilPassOpFront = StencilOp.KEEP;
          }
          if (stencilRefFront === void 0) {
            stencilRefFront = 1;
          }
          if (stencilTestBack === void 0) {
            stencilTestBack = false;
          }
          if (stencilFuncBack === void 0) {
            stencilFuncBack = ComparisonFunc.ALWAYS;
          }
          if (stencilReadMaskBack === void 0) {
            stencilReadMaskBack = 0xffff;
          }
          if (stencilWriteMaskBack === void 0) {
            stencilWriteMaskBack = 0xffff;
          }
          if (stencilFailOpBack === void 0) {
            stencilFailOpBack = StencilOp.KEEP;
          }
          if (stencilZFailOpBack === void 0) {
            stencilZFailOpBack = StencilOp.KEEP;
          }
          if (stencilPassOpBack === void 0) {
            stencilPassOpBack = StencilOp.KEEP;
          }
          if (stencilRefBack === void 0) {
            stencilRefBack = 1;
          }
          this.depthTest = depthTest;
          this.depthWrite = depthWrite;
          this.depthFunc = depthFunc;
          this.stencilTestFront = stencilTestFront;
          this.stencilFuncFront = stencilFuncFront;
          this.stencilReadMaskFront = stencilReadMaskFront;
          this.stencilWriteMaskFront = stencilWriteMaskFront;
          this.stencilFailOpFront = stencilFailOpFront;
          this.stencilZFailOpFront = stencilZFailOpFront;
          this.stencilPassOpFront = stencilPassOpFront;
          this.stencilRefFront = stencilRefFront;
          this.stencilTestBack = stencilTestBack;
          this.stencilFuncBack = stencilFuncBack;
          this.stencilReadMaskBack = stencilReadMaskBack;
          this.stencilWriteMaskBack = stencilWriteMaskBack;
          this.stencilFailOpBack = stencilFailOpBack;
          this.stencilZFailOpBack = stencilZFailOpBack;
          this.stencilPassOpBack = stencilPassOpBack;
          this.stencilRefBack = stencilRefBack;
        }
        var _proto2 = DepthStencilState.prototype;
        _proto2.reset = function reset() {
          this.depthTest = true;
          this.depthWrite = true;
          this.depthFunc = ComparisonFunc.LESS;
          this.stencilTestFront = false;
          this.stencilFuncFront = ComparisonFunc.ALWAYS;
          this.stencilReadMaskFront = 0xffff;
          this.stencilWriteMaskFront = 0xffff;
          this.stencilFailOpFront = StencilOp.KEEP;
          this.stencilZFailOpFront = StencilOp.KEEP;
          this.stencilPassOpFront = StencilOp.KEEP;
          this.stencilRefFront = 1;
          this.stencilTestBack = false;
          this.stencilFuncBack = ComparisonFunc.ALWAYS;
          this.stencilReadMaskBack = 0xffff;
          this.stencilWriteMaskBack = 0xffff;
          this.stencilFailOpBack = StencilOp.KEEP;
          this.stencilZFailOpBack = StencilOp.KEEP;
          this.stencilPassOpBack = StencilOp.KEEP;
          this.stencilRefBack = 1;
        };
        _proto2.assign = function assign(dss) {
          Object.assign(this, dss);
        };
        _proto2.destroy = function destroy() {};
        _createClass(DepthStencilState, [{
          key: "native",
          get: function get() {
            return this;
          }
        }]);
        return DepthStencilState;
      }();
      var BlendTarget = function () {
        function BlendTarget(blend, blendSrc, blendDst, blendEq, blendSrcAlpha, blendDstAlpha, blendAlphaEq, blendColorMask) {
          if (blend === void 0) {
            blend = false;
          }
          if (blendSrc === void 0) {
            blendSrc = BlendFactor.ONE;
          }
          if (blendDst === void 0) {
            blendDst = BlendFactor.ZERO;
          }
          if (blendEq === void 0) {
            blendEq = BlendOp.ADD;
          }
          if (blendSrcAlpha === void 0) {
            blendSrcAlpha = BlendFactor.ONE;
          }
          if (blendDstAlpha === void 0) {
            blendDstAlpha = BlendFactor.ZERO;
          }
          if (blendAlphaEq === void 0) {
            blendAlphaEq = BlendOp.ADD;
          }
          if (blendColorMask === void 0) {
            blendColorMask = ColorMask.ALL;
          }
          this.blend = blend;
          this.blendSrc = blendSrc;
          this.blendDst = blendDst;
          this.blendEq = blendEq;
          this.blendSrcAlpha = blendSrcAlpha;
          this.blendDstAlpha = blendDstAlpha;
          this.blendAlphaEq = blendAlphaEq;
          this.blendColorMask = blendColorMask;
        }
        var _proto3 = BlendTarget.prototype;
        _proto3.reset = function reset() {
          this.blend = false;
          this.blendSrc = BlendFactor.ONE;
          this.blendDst = BlendFactor.ZERO;
          this.blendEq = BlendOp.ADD;
          this.blendSrcAlpha = BlendFactor.ONE;
          this.blendDstAlpha = BlendFactor.ZERO;
          this.blendAlphaEq = BlendOp.ADD;
          this.blendColorMask = ColorMask.ALL;
        };
        _proto3.assign = function assign(target) {
          Object.assign(this, target);
        };
        _proto3.destroy = function destroy() {};
        return BlendTarget;
      }();
      var BlendState = function () {
        function BlendState(isA2C, isIndepend, blendColor, targets) {
          if (isA2C === void 0) {
            isA2C = false;
          }
          if (isIndepend === void 0) {
            isIndepend = false;
          }
          if (blendColor === void 0) {
            blendColor = new Color();
          }
          if (targets === void 0) {
            targets = [new BlendTarget()];
          }
          this.isA2C = isA2C;
          this.isIndepend = isIndepend;
          this.blendColor = blendColor;
          this.targets = targets;
        }
        var _proto4 = BlendState.prototype;
        _proto4.setTarget = function setTarget(index, target) {
          var tg = this.targets[index];
          if (!tg) {
            tg = this.targets[index] = new BlendTarget();
          }
          Object.assign(tg, target);
        };
        _proto4.reset = function reset() {
          this.isA2C = false;
          this.isIndepend = false;
          this.blendColor.x = 0;
          this.blendColor.y = 0;
          this.blendColor.z = 0;
          this.blendColor.w = 0;
          this.targets.length = 1;
          this.targets[0].reset();
        };
        _proto4.destroy = function destroy() {};
        _createClass(BlendState, [{
          key: "native",
          get: function get() {
            return this;
          }
        }]);
        return BlendState;
      }();

      var PipelineStateInfo = function PipelineStateInfo(shader, pipelineLayout, renderPass, inputState, rasterizerState, depthStencilState, blendState, primitive, dynamicStates, bindPoint) {
        if (shader === void 0) {
          shader = null;
        }
        if (pipelineLayout === void 0) {
          pipelineLayout = null;
        }
        if (renderPass === void 0) {
          renderPass = null;
        }
        if (inputState === void 0) {
          inputState = new InputState();
        }
        if (rasterizerState === void 0) {
          rasterizerState = new RasterizerState();
        }
        if (depthStencilState === void 0) {
          depthStencilState = new DepthStencilState();
        }
        if (blendState === void 0) {
          blendState = new BlendState();
        }
        if (primitive === void 0) {
          primitive = PrimitiveMode.TRIANGLE_LIST;
        }
        if (dynamicStates === void 0) {
          dynamicStates = DynamicStateFlagBit.NONE;
        }
        if (bindPoint === void 0) {
          bindPoint = PipelineBindPoint.GRAPHICS;
        }
        this.shader = shader;
        this.pipelineLayout = pipelineLayout;
        this.renderPass = renderPass;
        this.inputState = inputState;
        this.rasterizerState = rasterizerState;
        this.depthStencilState = depthStencilState;
        this.blendState = blendState;
        this.primitive = primitive;
        this.dynamicStates = dynamicStates;
        this.bindPoint = bindPoint;
      };
      var PipelineState = function (_GFXObject) {
        _inheritsLoose(PipelineState, _GFXObject);
        function PipelineState() {
          var _this;
          _this = _GFXObject.call(this, ObjectType.PIPELINE_STATE) || this;
          _this._shader = null;
          _this._pipelineLayout = null;
          _this._primitive = PrimitiveMode.TRIANGLE_LIST;
          _this._is = null;
          _this._rs = new RasterizerState();
          _this._dss = new DepthStencilState();
          _this._bs = new BlendState();
          _this._dynamicStates = DynamicStateFlagBit.NONE;
          _this._renderPass = null;
          return _this;
        }
        _createClass(PipelineState, [{
          key: "shader",
          get: function get() {
            return this._shader;
          }
        }, {
          key: "pipelineLayout",
          get: function get() {
            return this._pipelineLayout;
          }
        }, {
          key: "primitive",
          get: function get() {
            return this._primitive;
          }
        }, {
          key: "rasterizerState",
          get: function get() {
            return this._rs;
          }
        }, {
          key: "depthStencilState",
          get: function get() {
            return this._dss;
          }
        }, {
          key: "blendState",
          get: function get() {
            return this._bs;
          }
        }, {
          key: "inputState",
          get: function get() {
            return this._is;
          }
        }, {
          key: "dynamicStates",
          get: function get() {
            return this._dynamicStates;
          }
        }, {
          key: "renderPass",
          get: function get() {
            return this._renderPass;
          }
        }]);
        return PipelineState;
      }(GFXObject);

      var Queue = function (_GFXObject) {
        _inheritsLoose(Queue, _GFXObject);
        function Queue() {
          var _this;
          _this = _GFXObject.call(this, ObjectType.QUEUE) || this;
          _this._type = QueueType.GRAPHICS;
          return _this;
        }
        _createClass(Queue, [{
          key: "type",
          get: function get() {
            return this._type;
          }
        }]);
        return Queue;
      }(GFXObject);

      var RenderPass = function (_GFXObject) {
        _inheritsLoose(RenderPass, _GFXObject);
        function RenderPass() {
          var _this;
          _this = _GFXObject.call(this, ObjectType.RENDER_PASS) || this;
          _this._colorInfos = [];
          _this._depthStencilInfo = null;
          _this._subpasses = [];
          _this._hash = 0;
          return _this;
        }
        var _proto = RenderPass.prototype;
        _proto.computeHash = function computeHash() {
          var res = '';
          if (this._subpasses.length) {
            for (var i = 0; i < this._subpasses.length; ++i) {
              var subpass = this._subpasses[i];
              if (subpass.inputs.length) {
                res += 'ia';
                for (var j = 0; j < subpass.inputs.length; ++j) {
                  var ia = this._colorInfos[subpass.inputs[j]];
                  res += "," + ia.format + "," + ia.sampleCount;
                }
              }
              if (subpass.colors.length) {
                res += 'ca';
                for (var _j = 0; _j < subpass.inputs.length; ++_j) {
                  var ca = this._colorInfos[subpass.inputs[_j]];
                  res += "," + ca.format + "," + ca.sampleCount;
                }
              }
              if (subpass.depthStencil >= 0) {
                var ds = this._colorInfos[subpass.depthStencil];
                res += "ds," + ds.format + "," + ds.sampleCount;
              }
            }
          } else {
            res += 'ca';
            for (var _i = 0; _i < this._colorInfos.length; ++_i) {
              var _ca = this._colorInfos[_i];
              res += "," + _ca.format + "," + _ca.sampleCount;
            }
            var _ds = this._depthStencilInfo;
            if (_ds) {
              res += "ds," + _ds.format + "," + _ds.sampleCount;
            }
          }
          return murmurhash2_32_gc(res, 666);
        };
        _createClass(RenderPass, [{
          key: "colorAttachments",
          get: function get() {
            return this._colorInfos;
          }
        }, {
          key: "depthStencilAttachment",
          get: function get() {
            return this._depthStencilInfo;
          }
        }, {
          key: "subPasses",
          get: function get() {
            return this._subpasses;
          }
        }, {
          key: "hash",
          get: function get() {
            return this._hash;
          }
        }]);
        return RenderPass;
      }(GFXObject);

      var Sampler = function (_GFXObject) {
        _inheritsLoose(Sampler, _GFXObject);
        function Sampler(info, hash) {
          var _this;
          _this = _GFXObject.call(this, ObjectType.SAMPLER) || this;
          _this._info = new SamplerInfo();
          _this._hash = 0;
          _this._info.copy(info);
          _this._hash = hash;
          return _this;
        }
        Sampler.computeHash = function computeHash(info) {
          var hash = info.minFilter;
          hash |= info.magFilter << 2;
          hash |= info.mipFilter << 4;
          hash |= info.addressU << 6;
          hash |= info.addressV << 8;
          hash |= info.addressW << 10;
          hash |= info.maxAnisotropy << 12;
          hash |= info.cmpFunc << 16;
          return hash;
        };
        Sampler.unpackFromHash = function unpackFromHash(hash) {
          var info = new SamplerInfo();
          info.minFilter = (hash & (1 << 2) - 1) >> 0;
          info.magFilter = (hash & (1 << 2) - 1) >> 2;
          info.mipFilter = (hash & (1 << 2) - 1) >> 4;
          info.addressU = (hash & (1 << 2) - 1) >> 6;
          info.addressV = (hash & (1 << 2) - 1) >> 8;
          info.addressW = (hash & (1 << 2) - 1) >> 10;
          info.maxAnisotropy = (hash & (1 << 4) - 1) >> 12;
          info.cmpFunc = (hash & (1 << 3) - 1) >> 16;
          return info;
        };
        _createClass(Sampler, [{
          key: "info",
          get: function get() {
            return this._info;
          }
        }, {
          key: "hash",
          get: function get() {
            return this._hash;
          }
        }]);
        return Sampler;
      }(GFXObject);

      var Shader = function (_GFXObject) {
        _inheritsLoose(Shader, _GFXObject);
        function Shader() {
          var _this;
          _this = _GFXObject.call(this, ObjectType.SHADER) || this;
          _this._name = '';
          _this._stages = [];
          _this._attributes = [];
          _this._blocks = [];
          _this._samplers = [];
          return _this;
        }
        _createClass(Shader, [{
          key: "name",
          get: function get() {
            return this._name;
          }
        }, {
          key: "attributes",
          get: function get() {
            return this._attributes;
          }
        }, {
          key: "blocks",
          get: function get() {
            return this._blocks;
          }
        }, {
          key: "samplers",
          get: function get() {
            return this._samplers;
          }
        }]);
        return Shader;
      }(GFXObject);

      var Texture = function (_GFXObject) {
        _inheritsLoose(Texture, _GFXObject);
        function Texture() {
          var _this;
          _this = _GFXObject.call(this, ObjectType.TEXTURE) || this;
          _this._info = new TextureInfo();
          _this._viewInfo = new TextureViewInfo();
          _this._isPowerOf2 = false;
          _this._isTextureView = false;
          _this._size = 0;
          return _this;
        }
        Texture.getLevelCount = function getLevelCount(width, height) {
          return Math.floor(Math.log2(Math.max(width, height)));
        };
        _createClass(Texture, [{
          key: "type",
          get: function get() {
            return this._info.type;
          }
        }, {
          key: "usage",
          get: function get() {
            return this._info.usage;
          }
        }, {
          key: "format",
          get: function get() {
            return this._info.format;
          }
        }, {
          key: "width",
          get: function get() {
            return this._info.width;
          }
        }, {
          key: "height",
          get: function get() {
            return this._info.height;
          }
        }, {
          key: "depth",
          get: function get() {
            return this._info.depth;
          }
        }, {
          key: "layerCount",
          get: function get() {
            return this._info.layerCount;
          }
        }, {
          key: "levelCount",
          get: function get() {
            return this._info.levelCount;
          }
        }, {
          key: "samples",
          get: function get() {
            return this._info.samples;
          }
        }, {
          key: "flags",
          get: function get() {
            return this._info.flags;
          }
        }, {
          key: "size",
          get: function get() {
            return this._size;
          }
        }, {
          key: "info",
          get: function get() {
            return this._info;
          }
        }, {
          key: "viewInfo",
          get: function get() {
            return this._viewInfo;
          }
        }, {
          key: "isTextureView",
          get: function get() {
            return this._isTextureView;
          }
        }]);
        return Texture;
      }(GFXObject);

      var GeneralBarrier = function (_GFXObject) {
        _inheritsLoose(GeneralBarrier, _GFXObject);
        function GeneralBarrier(info, hash) {
          var _this;
          _this = _GFXObject.call(this, ObjectType.GLOBAL_BARRIER) || this;
          _this._info = new GeneralBarrierInfo();
          _this._hash = 0;
          _this._info.copy(info);
          _this._hash = hash;
          return _this;
        }
        GeneralBarrier.computeHash = function computeHash(info) {
          return murmurhash2_32_gc(info.prevAccesses + " " + info.nextAccesses + " " + info.type, 666);
        };
        _createClass(GeneralBarrier, [{
          key: "info",
          get: function get() {
            return this._info;
          }
        }, {
          key: "hash",
          get: function get() {
            return this._hash;
          }
        }]);
        return GeneralBarrier;
      }(GFXObject);

      var TextureBarrier = function (_GFXObject) {
        _inheritsLoose(TextureBarrier, _GFXObject);
        function TextureBarrier(info, hash) {
          var _this;
          _this = _GFXObject.call(this, ObjectType.TEXTURE_BARRIER) || this;
          _this._info = new TextureBarrierInfo();
          _this._hash = 0;
          _this._info.copy(info);
          _this._hash = hash;
          return _this;
        }
        TextureBarrier.computeHash = function computeHash(info) {
          var res = info.prevAccesses + " " + info.nextAccesses;
          res += info.type;
          res += info.baseMipLevel;
          res += info.levelCount;
          res += info.baseSlice;
          res += info.sliceCount;
          res += info.discardContents;
          res += info.srcQueue ? info.srcQueue.type : 0;
          res += info.dstQueue ? info.dstQueue.type : 0;
          return murmurhash2_32_gc(res, 666);
        };
        _createClass(TextureBarrier, [{
          key: "info",
          get: function get() {
            return this._info;
          }
        }, {
          key: "hash",
          get: function get() {
            return this._hash;
          }
        }]);
        return TextureBarrier;
      }(GFXObject);

      var BufferBarrier = function (_GFXObject) {
        _inheritsLoose(BufferBarrier, _GFXObject);
        function BufferBarrier(info, hash) {
          var _this;
          _this = _GFXObject.call(this, ObjectType.BUFFER_BARRIER) || this;
          _this._info = new BufferBarrierInfo();
          _this._hash = 0;
          _this._info.copy(info);
          _this._hash = hash;
          return _this;
        }
        BufferBarrier.computeHash = function computeHash(info) {
          var res = info.prevAccesses + " " + info.nextAccesses;
          res += info.type;
          res += info.offset;
          res += info.size;
          res += info.discardContents;
          res += info.srcQueue ? info.srcQueue.type : 0;
          res += info.dstQueue ? info.dstQueue.type : 0;
          return murmurhash2_32_gc(res, 666);
        };
        _createClass(BufferBarrier, [{
          key: "info",
          get: function get() {
            return this._info;
          }
        }, {
          key: "hash",
          get: function get() {
            return this._hash;
          }
        }]);
        return BufferBarrier;
      }(GFXObject);

      var polyfills = {
        Device: Device,
        Swapchain: Swapchain,
        Buffer: Buffer,
        Texture: Texture,
        Sampler: Sampler,
        Shader: Shader,
        InputAssembler: InputAssembler,
        RenderPass: RenderPass,
        Framebuffer: Framebuffer,
        DescriptorSet: DescriptorSet,
        DescriptorSetLayout: DescriptorSetLayout,
        PipelineLayout: PipelineLayout,
        PipelineState: PipelineState,
        CommandBuffer: CommandBuffer,
        Queue: Queue,
        GeneralBarrier: GeneralBarrier,
        TextureBarrier: TextureBarrier,
        BufferBarrier: BufferBarrier,
        RasterizerState: RasterizerState,
        BlendState: BlendState,
        BlendTarget: BlendTarget,
        DepthStencilState: DepthStencilState,
        PipelineStateInfo: PipelineStateInfo
      };
      Object.assign(polyfills, defines);
      legacyCC.gfx = polyfills;

      var LegacyRenderMode;
      (function (LegacyRenderMode) {
        LegacyRenderMode[LegacyRenderMode["AUTO"] = 0] = "AUTO";
        LegacyRenderMode[LegacyRenderMode["CANVAS"] = 1] = "CANVAS";
        LegacyRenderMode[LegacyRenderMode["WEBGL"] = 2] = "WEBGL";
        LegacyRenderMode[LegacyRenderMode["HEADLESS"] = 3] = "HEADLESS";
      })(LegacyRenderMode || (LegacyRenderMode = {}));
      var RenderType;
      (function (RenderType) {
        RenderType[RenderType["UNKNOWN"] = -1] = "UNKNOWN";
        RenderType[RenderType["CANVAS"] = 0] = "CANVAS";
        RenderType[RenderType["WEBGL"] = 1] = "WEBGL";
        RenderType[RenderType["OPENGL"] = 2] = "OPENGL";
        RenderType[RenderType["HEADLESS"] = 3] = "HEADLESS";
      })(RenderType || (RenderType = {}));
      var DeviceManager = function () {
        function DeviceManager() {
          this.initialized = false;
          this._gfxDevice = void 0;
          this._canvas = null;
          this._swapchain = void 0;
          this._renderType = RenderType.UNKNOWN;
        }
        var _proto = DeviceManager.prototype;
        _proto.init = function init(canvas, bindingMappingInfo) {
          if (this.initialized) {
            return;
          }
          var renderMode = settings.querySettings(Settings.Category.RENDERING, 'renderMode');
          this._canvas = canvas;
          this._renderType = this._determineRenderType(renderMode);
          if (this._renderType === RenderType.WEBGL) {
            var deviceInfo = new DeviceInfo(bindingMappingInfo);
            {
              var useWebGL2 = !!globalThis.WebGL2RenderingContext;
              globalThis.navigator.userAgent.toLowerCase();
              if (sys.browserType === BrowserType.UC) {
                useWebGL2 = false;
              }
              var deviceCtors = [];
              if (useWebGL2 && legacyCC.WebGL2Device) {
                deviceCtors.push(legacyCC.WebGL2Device);
              }
              if (legacyCC.WebGLDevice) {
                deviceCtors.push(legacyCC.WebGLDevice);
              }
              if (legacyCC.EmptyDevice) {
                deviceCtors.push(legacyCC.EmptyDevice);
              }
              Device.canvas = canvas;
              for (var i = 0; i < deviceCtors.length; i++) {
                this._gfxDevice = new deviceCtors[i]();
                if (this._gfxDevice.initialize(deviceInfo)) {
                  break;
                }
              }
              this._initSwapchain();
            }
          } else if (this._renderType === RenderType.HEADLESS && legacyCC.EmptyDevice) {
            this._gfxDevice = new legacyCC.EmptyDevice();
            this._gfxDevice.initialize(new DeviceInfo(bindingMappingInfo));
            this._initSwapchain();
          }
          if (!this._gfxDevice) {
            error('can not support canvas rendering in 3D');
            this._renderType = RenderType.UNKNOWN;
            return;
          }
          if (this._canvas) {
            this._canvas.oncontextmenu = function () {
              return false;
            };
          }
        };
        _proto._initSwapchain = function _initSwapchain() {
          var swapchainInfo = new SwapchainInfo(1, this._canvas);
          var windowSize = screen.windowSize;
          swapchainInfo.width = windowSize.width;
          swapchainInfo.height = windowSize.height;
          this._swapchain = this._gfxDevice.createSwapchain(swapchainInfo);
        };
        _proto._determineRenderType = function _determineRenderType(renderMode) {
          if (typeof renderMode !== 'number' || renderMode > RenderType.HEADLESS || renderMode < LegacyRenderMode.AUTO) {
            renderMode = LegacyRenderMode.AUTO;
          }
          var renderType = RenderType.CANVAS;
          var supportRender = false;
          if (renderMode === LegacyRenderMode.CANVAS) {
            renderType = RenderType.CANVAS;
            supportRender = true;
          } else if (renderMode === LegacyRenderMode.AUTO || renderMode === LegacyRenderMode.WEBGL) {
            renderType = RenderType.WEBGL;
            supportRender = true;
          } else if (renderMode === LegacyRenderMode.HEADLESS) {
            renderType = RenderType.HEADLESS;
            supportRender = true;
          }
          if (!supportRender) {
            throw new Error(getError(3820, renderMode));
          }
          return renderType;
        };
        _createClass(DeviceManager, [{
          key: "gfxDevice",
          get: function get() {
            return this._gfxDevice;
          }
        }, {
          key: "swapchain",
          get: function get() {
            return this._swapchain;
          }
        }]);
        return DeviceManager;
      }();
      var deviceManager = new DeviceManager();

      var index$1 = /*#__PURE__*/Object.freeze({
        __proto__: null,
        DescriptorSet: DescriptorSet,
        Buffer: Buffer,
        CommandBuffer: CommandBuffer,
        get ObjectType () { return ObjectType; },
        get Status () { return Status; },
        get API () { return API; },
        get SurfaceTransform () { return SurfaceTransform; },
        get Feature () { return Feature; },
        get Format () { return Format; },
        get FormatType () { return FormatType; },
        get Type () { return Type$1; },
        get BufferUsageBit () { return BufferUsageBit; },
        get BufferFlagBit () { return BufferFlagBit; },
        get MemoryAccessBit () { return MemoryAccessBit; },
        get MemoryUsageBit () { return MemoryUsageBit; },
        get TextureType () { return TextureType; },
        get TextureUsageBit () { return TextureUsageBit; },
        get TextureFlagBit () { return TextureFlagBit; },
        get FormatFeatureBit () { return FormatFeatureBit; },
        get SampleCount () { return SampleCount; },
        get VsyncMode () { return VsyncMode; },
        get Filter () { return Filter$1; },
        get Address () { return Address; },
        get ComparisonFunc () { return ComparisonFunc; },
        get StencilOp () { return StencilOp; },
        get BlendFactor () { return BlendFactor; },
        get BlendOp () { return BlendOp; },
        get ColorMask () { return ColorMask; },
        get ShaderStageFlagBit () { return ShaderStageFlagBit; },
        get LoadOp () { return LoadOp; },
        get StoreOp () { return StoreOp; },
        get AccessFlagBit () { return AccessFlagBit; },
        get ResolveMode () { return ResolveMode; },
        get PipelineBindPoint () { return PipelineBindPoint; },
        get PrimitiveMode () { return PrimitiveMode; },
        get PolygonMode () { return PolygonMode; },
        get ShadeModel () { return ShadeModel; },
        get CullMode () { return CullMode; },
        get DynamicStateFlagBit () { return DynamicStateFlagBit; },
        get StencilFace () { return StencilFace; },
        get DescriptorType () { return DescriptorType; },
        get QueueType () { return QueueType; },
        get QueryType () { return QueryType; },
        get CommandBufferType () { return CommandBufferType; },
        get ClearFlagBit () { return ClearFlagBit; },
        get BarrierType () { return BarrierType; },
        get PassType () { return PassType; },
        Size: Size,
        DeviceCaps: DeviceCaps,
        DeviceOptions: DeviceOptions,
        Offset: Offset,
        Rect: Rect,
        Extent: Extent,
        TextureSubresLayers: TextureSubresLayers,
        TextureSubresRange: TextureSubresRange,
        TextureCopy: TextureCopy,
        TextureBlit: TextureBlit,
        BufferTextureCopy: BufferTextureCopy,
        Viewport: Viewport,
        Color: Color,
        BindingMappingInfo: BindingMappingInfo,
        SwapchainInfo: SwapchainInfo,
        DeviceInfo: DeviceInfo,
        BufferInfo: BufferInfo,
        BufferViewInfo: BufferViewInfo,
        DrawInfo: DrawInfo,
        DispatchInfo: DispatchInfo,
        IndirectBuffer: IndirectBuffer,
        TextureInfo: TextureInfo,
        TextureViewInfo: TextureViewInfo,
        SamplerInfo: SamplerInfo,
        Uniform: Uniform,
        UniformBlock: UniformBlock,
        UniformSamplerTexture: UniformSamplerTexture,
        UniformSampler: UniformSampler,
        UniformTexture: UniformTexture,
        UniformStorageImage: UniformStorageImage,
        UniformStorageBuffer: UniformStorageBuffer,
        UniformInputAttachment: UniformInputAttachment,
        ShaderStage: ShaderStage,
        Attribute: Attribute,
        ShaderInfo: ShaderInfo,
        InputAssemblerInfo: InputAssemblerInfo,
        ColorAttachment: ColorAttachment,
        DepthStencilAttachment: DepthStencilAttachment,
        SubpassInfo: SubpassInfo,
        SubpassDependency: SubpassDependency,
        RenderPassInfo: RenderPassInfo,
        GeneralBarrierInfo: GeneralBarrierInfo,
        TextureBarrierInfo: TextureBarrierInfo,
        BufferBarrierInfo: BufferBarrierInfo,
        FramebufferInfo: FramebufferInfo,
        DescriptorSetLayoutBinding: DescriptorSetLayoutBinding,
        DescriptorSetLayoutInfo: DescriptorSetLayoutInfo,
        DescriptorSetInfo: DescriptorSetInfo,
        PipelineLayoutInfo: PipelineLayoutInfo,
        InputState: InputState,
        CommandBufferInfo: CommandBufferInfo,
        QueueInfo: QueueInfo,
        QueryPoolInfo: QueryPoolInfo,
        FormatInfo: FormatInfo,
        MemoryStatus: MemoryStatus,
        DynamicStencilStates: DynamicStencilStates,
        DynamicStates: DynamicStates,
        GFXObject: GFXObject,
        get AttributeName () { return AttributeName; },
        FormatInfos: FormatInfos,
        DESCRIPTOR_BUFFER_TYPE: DESCRIPTOR_BUFFER_TYPE,
        DESCRIPTOR_SAMPLER_TYPE: DESCRIPTOR_SAMPLER_TYPE,
        DESCRIPTOR_DYNAMIC_TYPE: DESCRIPTOR_DYNAMIC_TYPE,
        DRAW_INFO_SIZE: DRAW_INFO_SIZE,
        IsPowerOf2: IsPowerOf2,
        FormatSize: FormatSize,
        FormatSurfaceSize: FormatSurfaceSize,
        GetTypeSize: GetTypeSize,
        getTypedArrayConstructor: getTypedArrayConstructor,
        formatAlignment: formatAlignment,
        alignTo: alignTo,
        Device: Device,
        DefaultResource: DefaultResource,
        Swapchain: Swapchain,
        Framebuffer: Framebuffer,
        InputAssembler: InputAssembler,
        DescriptorSetLayout: DescriptorSetLayout,
        PipelineLayout: PipelineLayout,
        BlendState: BlendState,
        BlendTarget: BlendTarget,
        RasterizerState: RasterizerState,
        DepthStencilState: DepthStencilState,
        PipelineStateInfo: PipelineStateInfo,
        PipelineState: PipelineState,
        Queue: Queue,
        RenderPass: RenderPass,
        Sampler: Sampler,
        Shader: Shader,
        Texture: Texture,
        GeneralBarrier: GeneralBarrier,
        TextureBarrier: TextureBarrier,
        get LegacyRenderMode () { return LegacyRenderMode; },
        get RenderType () { return RenderType; },
        DeviceManager: DeviceManager,
        deviceManager: deviceManager
      });
      exports('ax', index$1);

      var m$4 = new Mat4();
      function fillMeshVertices3D(node, renderer, renderData, color) {
        var chunk = renderData.chunk;
        var dataList = renderData.data;
        var vData = chunk.vb;
        var vertexCount = renderData.vertexCount;
        node.getWorldMatrix(m$4);
        var vertexOffset = 0;
        for (var i = 0; i < vertexCount; i++) {
          var vert = dataList[i];
          var x = vert.x;
          var y = vert.y;
          var rhw = m$4.m03 * x + m$4.m07 * y + m$4.m15;
          rhw = rhw ? 1 / rhw : 1;
          vData[vertexOffset + 0] = (m$4.m00 * x + m$4.m04 * y + m$4.m12) * rhw;
          vData[vertexOffset + 1] = (m$4.m01 * x + m$4.m05 * y + m$4.m13) * rhw;
          vData[vertexOffset + 2] = (m$4.m02 * x + m$4.m06 * y + m$4.m14) * rhw;
          Color$1.toArray(vData, color, vertexOffset + 5);
          vertexOffset += 9;
        }
        chunk.bufferId;
        var vid = chunk.vertexOffset;
        var meshBuffer = chunk.meshBuffer;
        var ib = chunk.meshBuffer.iData;
        var indexOffset = meshBuffer.indexOffset;
        for (var _i = 0, count = vertexCount / 4; _i < count; _i++) {
          var start = vid + _i * 4;
          ib[indexOffset++] = start;
          ib[indexOffset++] = start + 1;
          ib[indexOffset++] = start + 2;
          ib[indexOffset++] = start + 1;
          ib[indexOffset++] = start + 3;
          ib[indexOffset++] = start + 2;
        }
        meshBuffer.indexOffset += renderData.indexCount;
        meshBuffer.setDirty();
      }
      function updateOpacity(renderData, opacity) {
        var vfmt = renderData.vertexFormat;
        var vb = renderData.chunk.vb;
        var attr;
        var format;
        var stride;
        var offset = 0;
        for (var i = 0; i < vfmt.length; ++i) {
          attr = vfmt[i];
          format = FormatInfos[attr.format];
          if (format.hasAlpha) {
            stride = renderData.floatStride;
            if (format.size / format.count === 1) {
              var alpha = ~~clamp$1(Math.round(opacity * 255), 0, 255);
              for (var color = offset; color < vb.length; color += stride) {
                vb[color] = (vb[color] & 0xffffff00 | alpha) >>> 0;
              }
            } else if (format.size / format.count === 4) {
              for (var _alpha = offset + 3; _alpha < vb.length; _alpha += stride) {
                vb[_alpha] = opacity;
              }
            }
          }
          offset += format.size >> 2;
        }
      }

      var minigame = {};

      var Cache = function () {
        function Cache(map) {
          this._map = null;
          this._count = 0;
          if (map) {
            this._map = map;
            this._count = Object.keys(map).length;
          } else {
            this._map = createMap(true);
            this._count = 0;
          }
        }
        var _proto = Cache.prototype;
        _proto.add = function add(key, val) {
          if (!(key in this._map)) {
            this._count++;
          }
          return this._map[key] = val;
        };
        _proto.get = function get(key) {
          return this._map[key];
        };
        _proto.has = function has(key) {
          return key in this._map;
        };
        _proto.remove = function remove(key) {
          var out = this._map[key];
          if (key in this._map) {
            delete this._map[key];
            this._count--;
          }
          return out;
        };
        _proto.clear = function clear() {
          if (this._count !== 0) {
            this._map = createMap(true);
            this._count = 0;
          }
        };
        _proto.forEach = function forEach(func) {
          for (var _key in this._map) {
            func(this._map[_key], _key);
          }
        };
        _proto.find = function find(predicate) {
          for (var _key2 in this._map) {
            if (predicate(this._map[_key2], _key2)) {
              return this._map[_key2];
            }
          }
          return null;
        };
        _proto.destroy = function destroy() {
          this._map = null;
        };
        _createClass(Cache, [{
          key: "map",
          get: function get() {
            return this._map;
          }
        }, {
          key: "count",
          get: function get() {
            return this._count;
          }
        }]);
        return Cache;
      }();

      var Pipeline = function () {
        function Pipeline(name, funcs) {
          this.id = Pipeline._pipelineId++;
          this.name = '';
          this.pipes = [];
          this.name = name;
          for (var i = 0, l = funcs.length; i < l; i++) {
            this.pipes.push(funcs[i]);
          }
        }
        var _proto = Pipeline.prototype;
        _proto.insert = function insert(func, index) {
          if (index > this.pipes.length) {
            warnID(4921);
            return this;
          }
          this.pipes.splice(index, 0, func);
          return this;
        };
        _proto.append = function append(func) {
          this.pipes.push(func);
          return this;
        };
        _proto.remove = function remove(index) {
          this.pipes.splice(index, 1);
          return this;
        };
        _proto.sync = function sync(task) {
          var pipes = this.pipes;
          if (pipes.length === 0) {
            return null;
          }
          task.isFinished = false;
          for (var i = 0, l = pipes.length; i < l;) {
            var pipe = pipes[i];
            var result = pipe(task);
            if (result) {
              task.isFinished = true;
              return result;
            }
            i++;
            if (i !== l) {
              task.input = task.output;
              task.output = null;
            }
          }
          task.isFinished = true;
          return task.output;
        };
        _proto.async = function async(task) {
          var pipes = this.pipes;
          if (pipes.length === 0) {
            return;
          }
          task.isFinished = false;
          this._flow(0, task);
        };
        _proto._flow = function _flow(index, task) {
          var _this = this;
          var pipe = this.pipes[index];
          pipe(task, function (result) {
            if (result) {
              task.isFinished = true;
              task.dispatch('complete', result);
            } else {
              index++;
              if (index < _this.pipes.length) {
                task.input = task.output;
                task.output = null;
                _this._flow(index, task);
              } else {
                task.isFinished = true;
                task.dispatch('complete', result, task.output);
              }
            }
          });
        };
        return Pipeline;
      }();
      Pipeline._pipelineId = 0;

      (function () {
        function WeakCache(map) {
          this._weakMap = {};
          if (typeof window.WeakRef === 'undefined') throw new Error('this platform does not support WeakRef!');
          if (map) {
            for (var _key in map) {
              this._weakMap[_key] = new WeakRef(map[_key]);
            }
          }
        }
        var _proto = WeakCache.prototype;
        _proto.add = function add(key, val) {
          this._weakMap[key] = new WeakRef(val);
          return val;
        };
        _proto.has = function has(key) {
          return key in this._weakMap && !!this._weakMap[key].deref();
        };
        _proto.get = function get(key) {
          return this._weakMap[key] && this._weakMap[key].deref();
        };
        _proto.remove = function remove(key) {
          var out = this._weakMap[key];
          delete this._weakMap[key];
          return out && out.deref();
        };
        _proto.clear = function clear() {
          this._weakMap = createMap(true);
        };
        _proto.forEach = function forEach(func) {
          for (var _key2 in this._weakMap) {
            var _val = this.get(_key2);
            if (_val) {
              func(_val, _key2);
            }
          }
        };
        _proto.find = function find(predicate) {
          for (var _key3 in this._weakMap) {
            var _val2 = this.get(_key3);
            if (_val2 && predicate(_val2, _key3)) {
              return this._weakMap[_key3].deref();
            }
          }
          return null;
        };
        _proto.destroy = function destroy() {
          this._weakMap = {};
        };
        _createClass(WeakCache, [{
          key: "count",
          get: function get() {
            return Object.values(this._weakMap).filter(function (weakRef) {
              return weakRef.deref();
            }).length;
          }
        }]);
        return WeakCache;
      })();

      var assets = new Cache();
      var files = new Cache();
      var parsed = new Cache();
      var bundles = new Cache();
      var pipeline = new Pipeline('normal load', []);
      var fetchPipeline = new Pipeline('fetch', []);
      var transformPipeline = new Pipeline('transform url', []);
      var references = null;
      var assetsOverrideMap = new Map();
      var RequestType;
      (function (RequestType) {
        RequestType["UUID"] = "uuid";
        RequestType["PATH"] = "path";
        RequestType["DIR"] = "dir";
        RequestType["URL"] = "url";
        RequestType["SCENE"] = "scene";
      })(RequestType || (RequestType = {}));
      var presets = {
        "default": {
          priority: 0
        },
        preload: {
          maxConcurrency: 6,
          maxRequestsPerFrame: 2,
          priority: -1
        },
        scene: {
          maxConcurrency: 20,
          maxRequestsPerFrame: 20,
          priority: 1
        },
        bundle: {
          maxConcurrency: 20,
          maxRequestsPerFrame: 20,
          priority: 2
        },
        remote: {
          maxRetryCount: 4
        }
      };
      var BuiltinBundleName;
      (function (BuiltinBundleName) {
        BuiltinBundleName["INTERNAL"] = "internal";
        BuiltinBundleName["RESOURCES"] = "resources";
        BuiltinBundleName["MAIN"] = "main";
        BuiltinBundleName["START_SCENE"] = "start-scene";
      })(BuiltinBundleName || (BuiltinBundleName = {}));

      var Task = function () {
        Task.create = function create(options) {
          var out;
          if (Task._deadPool.length !== 0) {
            out = Task._deadPool.pop();
            out.set(options);
          } else {
            out = new Task(options);
          }
          return out;
        };
        function Task(options) {
          this.id = Task._taskId++;
          this.onComplete = null;
          this.onProgress = null;
          this.onError = null;
          this.source = null;
          this.output = null;
          this.input = null;
          this.progress = null;
          this.options = null;
          this.isFinished = true;
          this.set(options);
        }
        var _proto = Task.prototype;
        _proto.set = function set(options) {
          if (options === void 0) {
            options = Object.create(null);
          }
          this.onComplete = options.onComplete || null;
          this.onProgress = options.onProgress || null;
          this.onError = options.onError || null;
          this.source = this.input = options.input;
          this.output = null;
          this.progress = options.progress;
          this.options = options.options || Object.create(null);
        };
        _proto.dispatch = function dispatch(event, param1, param2, param3, param4) {
          switch (event) {
            case 'complete':
              if (this.onComplete) {
                this.onComplete(param1, param2);
              }
              break;
            case 'progress':
              if (this.onProgress) {
                this.onProgress(param1, param2, param3, param4);
              }
              break;
            case 'error':
              if (this.onError) {
                this.onError(param1, param2, param3, param4);
              }
              break;
            default:
              {
                var str = "on" + event[0].toUpperCase() + event.substr(1);
                if (typeof this[str] === 'function') {
                  this[str](param1, param2, param3, param4);
                }
                break;
              }
          }
        };
        _proto.recycle = function recycle() {
          if (Task._deadPool.length === Task.MAX_DEAD_NUM) {
            return;
          }
          this.onComplete = null;
          this.onProgress = null;
          this.onError = null;
          this.source = this.output = this.input = null;
          this.progress = null;
          this.options = null;
          Task._deadPool.push(this);
        };
        _createClass(Task, [{
          key: "isFinish",
          get: function get() {
            return this.isFinished;
          },
          set: function set(val) {
            this.isFinished = val;
          }
        }]);
        return Task;
      }();
      Task.MAX_DEAD_NUM = 500;
      Task._taskId = 0;
      Task._deadPool = [];

      var separator = '@';
      var HexChars = '0123456789abcdef'.split('');
      var _t = ['', '', '', ''];
      var UuidTemplate = _t.concat(_t, '-', _t, '-', _t, '-', _t, '-', _t, _t, _t);
      var Indices = UuidTemplate.map(function (x, i) {
        return x === '-' ? NaN : i;
      }).filter(Number.isFinite);
      function decodeUuid(base64) {
        var strs = base64.split(separator);
        var uuid = strs[0];
        if (uuid.length !== 22) {
          return base64;
        }
        UuidTemplate[0] = base64[0];
        UuidTemplate[1] = base64[1];
        for (var i = 2, j = 2; i < 22; i += 2) {
          var lhs = BASE64_VALUES[base64.charCodeAt(i)];
          var rhs = BASE64_VALUES[base64.charCodeAt(i + 1)];
          UuidTemplate[Indices[j++]] = HexChars[lhs >> 2];
          UuidTemplate[Indices[j++]] = HexChars[(lhs & 3) << 2 | rhs >> 4];
          UuidTemplate[Indices[j++]] = HexChars[rhs & 0xF];
        }
        return base64.replace(uuid, UuidTemplate.join(''));
      }

      var _uuidRegex = /.*[/\\][0-9a-fA-F]{2}[/\\]([0-9a-fA-F-@]{8,}).*/;
      function getUuidFromURL(url) {
        var matches = _uuidRegex.exec(url);
        if (matches) {
          return matches[1];
        }
        return '';
      }
      function getUrlWithUuid(uuid, options) {
        options = options || Object.create(null);
        options.__isNative__ = options.isNative;
        if (options.nativeExt) {
          options.ext = options.nativeExt;
        }
        var bundle = bundles.find(function (b) {
          return !!b.getAssetInfo(uuid);
        });
        if (bundle) {
          options.bundle = bundle.name;
        }
        return transform(uuid, options);
      }
      function isScene(asset) {
        return !!asset && (asset instanceof legacyCC.SceneAsset || asset instanceof legacyCC.Scene);
      }
      function normalize(url) {
        if (url) {
          if (url.charCodeAt(0) === 46 && url.charCodeAt(1) === 47) {
            url = url.slice(2);
          } else if (url.charCodeAt(0) === 47) {
            url = url.slice(1);
          }
        }
        return url;
      }
      function transform(input, options) {
        var subTask = Task.create({
          input: input,
          options: options
        });
        var urls = [];
        try {
          var result = transformPipeline.sync(subTask);
          for (var _iterator = _createForOfIteratorHelperLoose(result), _step; !(_step = _iterator()).done;) {
            var requestItem = _step.value;
            var url = requestItem.url;
            requestItem.recycle();
            urls.push(url);
          }
        } catch (e) {
          for (var _iterator2 = _createForOfIteratorHelperLoose(subTask.output), _step2; !(_step2 = _iterator2()).done;) {
            var item = _step2.value;
            item.recycle();
          }
          error(e.message, e.stack);
        }
        subTask.recycle();
        return urls.length > 1 ? urls : urls[0];
      }

      var helper = /*#__PURE__*/Object.freeze({
        __proto__: null,
        getUuidFromURL: getUuidFromURL,
        getUrlWithUuid: getUrlWithUuid,
        isScene: isScene,
        normalize: normalize,
        transform: transform,
        decodeUuid: decodeUuid
      });

      var _dec$32, _class$2$, _class2$2K, _initializer$2q;
      var ccclass$m = ccclass$n,
        serializable$i = serializable$j,
        property$2 = property$3;
      var Asset = exports('e2', (_dec$32 = ccclass$m('cc.Asset'), _dec$32(_class$2$ = (_class2$2K = function (_Eventify) {
        _inheritsLoose(Asset, _Eventify);
        Asset.deserialize = function deserialize(data) {
          return legacyCC.deserialize(data);
        };
        function Asset() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Eventify.call.apply(_Eventify, [this].concat(args)) || this;
          _this.loaded = true;
          _this._native = _initializer$2q && _initializer$2q();
          _this._nativeUrl = '';
          _this._file = null;
          _this._ref = 0;
          Object.defineProperty(_assertThisInitialized(_this), '_uuid', {
            value: '',
            writable: true
          });
          return _this;
        }
        var _proto = Asset.prototype;
        _proto.toString = function toString() {
          return this.nativeUrl;
        };
        _proto.serialize = function serialize() {};
        _proto._setRawAsset = function _setRawAsset(filename, inLibrary) {
          if (inLibrary === void 0) {
            inLibrary = true;
          }
          if (inLibrary !== false) {
            this._native = filename || '';
          } else {
            this._native = "/" + filename;
          }
        };
        _proto.addRef = function addRef() {
          this._ref++;
          return this;
        };
        _proto.decRef = function decRef(autoRelease) {
          if (autoRelease === void 0) {
            autoRelease = true;
          }
          if (this._ref > 0) {
            this._ref--;
          }
          if (autoRelease) {
            legacyCC.assetManager._releaseManager.tryRelease(this);
          }
          return this;
        };
        _proto.onLoaded = function onLoaded() {};
        _proto.initDefault = function initDefault(uuid) {
          if (uuid) {
            this._uuid = uuid;
          }
          this.isDefault = true;
        };
        _proto.validate = function validate() {
          return true;
        };
        _proto.destroy = function destroy() {
          debug(getError(12101, this._uuid));
          return _Eventify.prototype.destroy.call(this);
        };
        _createClass(Asset, [{
          key: "nativeUrl",
          get: function get() {
            if (!this._nativeUrl) {
              if (!this._native) return '';
              var name = this._native;
              if (name.charCodeAt(0) === 47) {
                return name.slice(1);
              }
              if (name.charCodeAt(0) === 46) {
                this._nativeUrl = getUrlWithUuid(this._uuid, {
                  nativeExt: name,
                  isNative: true
                });
              } else {
                this._nativeUrl = getUrlWithUuid(this._uuid, {
                  __nativeName__: name,
                  nativeExt: extname(name),
                  isNative: true
                });
              }
            }
            return this._nativeUrl;
          }
        }, {
          key: "uuid",
          get: function get() {
            return this._uuid;
          }
        }, {
          key: "_nativeAsset",
          get: function get() {
            return this._file;
          },
          set: function set(obj) {
            this._file = obj;
          }
        }, {
          key: "nativeAsset",
          get: function get() {
            return this._file;
          }
        }, {
          key: "_nativeDep",
          get: function get() {
            if (this._native) {
              return {
                __isNative__: true,
                uuid: this._uuid,
                ext: this._native
              };
            }
            return undefined;
          }
        }, {
          key: "refCount",
          get: function get() {
            return this._ref;
          }
        }]);
        return Asset;
      }(Eventify(CCObject)), (_initializer$2q = applyDecoratedInitializer(_class2$2K.prototype, "_native", [serializable$i], function () {
        return '';
      }), _applyDecoratedDescriptor(_class2$2K.prototype, "_nativeAsset", [property$2], Object.getOwnPropertyDescriptor(_class2$2K.prototype, "_nativeAsset"), _class2$2K.prototype)), _class2$2K)) || _class$2$));
      Asset.prototype.createNode = null;
      legacyCC.Asset = Asset;

      var CUSTOM_PIXEL_FORMAT = 1024;
      var PixelFormat;
      (function (PixelFormat) {
        PixelFormat[PixelFormat["RGB565"] = Format.R5G6B5] = "RGB565";
        PixelFormat[PixelFormat["RGB5A1"] = Format.RGB5A1] = "RGB5A1";
        PixelFormat[PixelFormat["RGBA4444"] = Format.RGBA4] = "RGBA4444";
        PixelFormat[PixelFormat["RGB888"] = Format.RGB8] = "RGB888";
        PixelFormat[PixelFormat["RGB32F"] = Format.RGB32F] = "RGB32F";
        PixelFormat[PixelFormat["RGBA8888"] = Format.RGBA8] = "RGBA8888";
        PixelFormat[PixelFormat["RGBA32F"] = Format.RGBA32F] = "RGBA32F";
        PixelFormat[PixelFormat["A8"] = Format.A8] = "A8";
        PixelFormat[PixelFormat["I8"] = Format.L8] = "I8";
        PixelFormat[PixelFormat["AI8"] = Format.LA8] = "AI8";
        PixelFormat[PixelFormat["RGB_PVRTC_2BPPV1"] = Format.PVRTC_RGB2] = "RGB_PVRTC_2BPPV1";
        PixelFormat[PixelFormat["RGBA_PVRTC_2BPPV1"] = Format.PVRTC_RGBA2] = "RGBA_PVRTC_2BPPV1";
        PixelFormat[PixelFormat["RGB_A_PVRTC_2BPPV1"] = CUSTOM_PIXEL_FORMAT] = "RGB_A_PVRTC_2BPPV1";
        PixelFormat[PixelFormat["RGB_PVRTC_4BPPV1"] = Format.PVRTC_RGB4] = "RGB_PVRTC_4BPPV1";
        PixelFormat[PixelFormat["RGBA_PVRTC_4BPPV1"] = Format.PVRTC_RGBA4] = "RGBA_PVRTC_4BPPV1";
        PixelFormat[PixelFormat["RGB_A_PVRTC_4BPPV1"] = CUSTOM_PIXEL_FORMAT + 1] = "RGB_A_PVRTC_4BPPV1";
        PixelFormat[PixelFormat["RGB_ETC1"] = Format.ETC_RGB8] = "RGB_ETC1";
        PixelFormat[PixelFormat["RGBA_ETC1"] = CUSTOM_PIXEL_FORMAT + 2] = "RGBA_ETC1";
        PixelFormat[PixelFormat["RGB_ETC2"] = Format.ETC2_RGB8] = "RGB_ETC2";
        PixelFormat[PixelFormat["RGBA_ETC2"] = Format.ETC2_RGBA8] = "RGBA_ETC2";
        PixelFormat[PixelFormat["RGBA_ASTC_4x4"] = Format.ASTC_RGBA_4X4] = "RGBA_ASTC_4x4";
        PixelFormat[PixelFormat["RGBA_ASTC_5x4"] = Format.ASTC_RGBA_5X4] = "RGBA_ASTC_5x4";
        PixelFormat[PixelFormat["RGBA_ASTC_5x5"] = Format.ASTC_RGBA_5X5] = "RGBA_ASTC_5x5";
        PixelFormat[PixelFormat["RGBA_ASTC_6x5"] = Format.ASTC_RGBA_6X5] = "RGBA_ASTC_6x5";
        PixelFormat[PixelFormat["RGBA_ASTC_6x6"] = Format.ASTC_RGBA_6X6] = "RGBA_ASTC_6x6";
        PixelFormat[PixelFormat["RGBA_ASTC_8x5"] = Format.ASTC_RGBA_8X5] = "RGBA_ASTC_8x5";
        PixelFormat[PixelFormat["RGBA_ASTC_8x6"] = Format.ASTC_RGBA_8X6] = "RGBA_ASTC_8x6";
        PixelFormat[PixelFormat["RGBA_ASTC_8x8"] = Format.ASTC_RGBA_8X8] = "RGBA_ASTC_8x8";
        PixelFormat[PixelFormat["RGBA_ASTC_10x5"] = Format.ASTC_RGBA_10X5] = "RGBA_ASTC_10x5";
        PixelFormat[PixelFormat["RGBA_ASTC_10x6"] = Format.ASTC_RGBA_10X6] = "RGBA_ASTC_10x6";
        PixelFormat[PixelFormat["RGBA_ASTC_10x8"] = Format.ASTC_RGBA_10X8] = "RGBA_ASTC_10x8";
        PixelFormat[PixelFormat["RGBA_ASTC_10x10"] = Format.ASTC_RGBA_10X10] = "RGBA_ASTC_10x10";
        PixelFormat[PixelFormat["RGBA_ASTC_12x10"] = Format.ASTC_RGBA_12X10] = "RGBA_ASTC_12x10";
        PixelFormat[PixelFormat["RGBA_ASTC_12x12"] = Format.ASTC_RGBA_12X12] = "RGBA_ASTC_12x12";
      })(PixelFormat || (PixelFormat = {}));
      var WrapMode$1;
      (function (WrapMode) {
        WrapMode[WrapMode["REPEAT"] = Address.WRAP] = "REPEAT";
        WrapMode[WrapMode["CLAMP_TO_EDGE"] = Address.CLAMP] = "CLAMP_TO_EDGE";
        WrapMode[WrapMode["MIRRORED_REPEAT"] = Address.MIRROR] = "MIRRORED_REPEAT";
        WrapMode[WrapMode["CLAMP_TO_BORDER"] = Address.BORDER] = "CLAMP_TO_BORDER";
      })(WrapMode$1 || (WrapMode$1 = {}));
      var Filter;
      (function (Filter) {
        Filter[Filter["NONE"] = Filter$1.NONE] = "NONE";
        Filter[Filter["LINEAR"] = Filter$1.LINEAR] = "LINEAR";
        Filter[Filter["NEAREST"] = Filter$1.POINT] = "NEAREST";
      })(Filter || (Filter = {}));

      var _dec$31, _class$2_, _class2$2J, _class3$Q;
      var COMPRESSED_HEADER_LENGTH = 4;
      var COMPRESSED_MIPMAP_DATA_SIZE_LENGTH = 4;
      var COMPRESSED_MIPMAP_LEVEL_COUNT_LENGTH = 4;
      var COMPRESSED_MIPMAP_MAGIC = 0x50494d43;
      var compressType = Enum({
        PVR: 0,
        PKM: 1,
        ASTC: 2
      });
      var PVR_HEADER_LENGTH = 13;
      var PVR_MAGIC = 0x03525650;
      var PVR_HEADER_MAGIC = 0;
      var PVR_HEADER_HEIGHT = 6;
      var PVR_HEADER_WIDTH = 7;
      var PVR_HEADER_METADATA = 12;
      var ETC_PKM_HEADER_LENGTH = 16;
      var ETC_PKM_FORMAT_OFFSET = 6;
      var ETC_PKM_WIDTH_OFFSET = 12;
      var ETC_PKM_HEIGHT_OFFSET = 14;
      var ETC1_RGB_NO_MIPMAPS = 0;
      var ETC2_RGB_NO_MIPMAPS = 1;
      var ETC2_RGBA_NO_MIPMAPS = 3;
      var ASTC_MAGIC = 0x5CA1AB13;
      var ASTC_HEADER_LENGTH = 16;
      var ASTC_HEADER_MAGIC = 4;
      var ASTC_HEADER_SIZE_X_BEGIN = 7;
      var ASTC_HEADER_SIZE_Y_BEGIN = 10;
      function getASTCFormat(xdim, ydim) {
        if (xdim === 4) {
          return PixelFormat.RGBA_ASTC_4x4;
        }
        if (xdim === 5) {
          if (ydim === 4) {
            return PixelFormat.RGBA_ASTC_5x4;
          }
          return PixelFormat.RGBA_ASTC_5x5;
        }
        if (xdim === 6) {
          if (ydim === 5) {
            return PixelFormat.RGBA_ASTC_6x5;
          }
          return PixelFormat.RGBA_ASTC_6x6;
        }
        if (xdim === 8) {
          if (ydim === 5) {
            return PixelFormat.RGBA_ASTC_8x5;
          }
          if (ydim === 6) {
            return PixelFormat.RGBA_ASTC_8x6;
          }
          return PixelFormat.RGBA_ASTC_8x8;
        }
        if (xdim === 10) {
          if (ydim === 5) {
            return PixelFormat.RGBA_ASTC_10x5;
          }
          if (ydim === 6) {
            return PixelFormat.RGBA_ASTC_10x6;
          }
          if (ydim === 8) {
            return PixelFormat.RGBA_ASTC_10x8;
          }
          return PixelFormat.RGBA_ASTC_10x10;
        }
        if (ydim === 10) {
          return PixelFormat.RGBA_ASTC_12x10;
        }
        return PixelFormat.RGBA_ASTC_12x12;
      }
      function readBEUint16(header, offset) {
        return header[offset] << 8 | header[offset + 1];
      }
      function isImageBitmap(imageSource) {
        return !!(sys.hasFeature(sys.Feature.IMAGE_BITMAP) && imageSource instanceof ImageBitmap);
      }
      function isNativeImage(imageSource) {
        return imageSource instanceof HTMLImageElement || imageSource instanceof HTMLCanvasElement || isImageBitmap(imageSource);
      }
      var ImageAsset = exports('e8', (_dec$31 = ccclass$n('cc.ImageAsset'), _dec$31(_class$2_ = (_class2$2J = (_class3$Q = function (_Asset) {
        _inheritsLoose(ImageAsset, _Asset);
        ImageAsset.mergeCompressedTextureMips = function mergeCompressedTextureMips(files) {
          var out = new Uint8Array(0);
          var err = null;
          try {
            var fileHeaderLength = COMPRESSED_HEADER_LENGTH + COMPRESSED_MIPMAP_LEVEL_COUNT_LENGTH + files.length * COMPRESSED_MIPMAP_DATA_SIZE_LENGTH;
            var fileLength = 0;
            for (var _iterator = _createForOfIteratorHelperLoose(files), _step; !(_step = _iterator()).done;) {
              var _file = _step.value;
              fileLength += _file.byteLength;
            }
            fileLength += fileHeaderLength;
            out = new Uint8Array(fileLength);
            var outView = new DataView(out.buffer, out.byteOffset, out.byteLength);
            outView.setUint32(0, COMPRESSED_MIPMAP_MAGIC, true);
            outView.setUint32(COMPRESSED_HEADER_LENGTH, files.length, true);
            var dataOffset = fileHeaderLength;
            for (var i = 0; i < files.length; i++) {
              var file = files[i];
              outView.setUint32(COMPRESSED_HEADER_LENGTH + COMPRESSED_MIPMAP_LEVEL_COUNT_LENGTH + i * COMPRESSED_MIPMAP_DATA_SIZE_LENGTH, file.byteLength, true);
              if (file instanceof ArrayBuffer) {
                var srcArray = new Uint8Array(file);
                out.set(srcArray, dataOffset);
              } else {
                var _srcArray = new Uint8Array(file.buffer, file.byteOffset, file.byteLength);
                out.set(_srcArray, dataOffset);
              }
              dataOffset += file.byteLength;
            }
          } catch (e) {
            err = e;
            console.warn(err);
          }
          return out;
        };
        ImageAsset.parseCompressedTextures = function parseCompressedTextures(file, type) {
          var out = {
            _data: new Uint8Array(0),
            _compressed: true,
            width: 0,
            height: 0,
            format: 0,
            mipmapLevelDataSize: []
          };
          var buffer = file instanceof ArrayBuffer ? file : file.buffer;
          var bufferView = new DataView(buffer);
          var magicNumber = bufferView.getUint32(0, true);
          if (magicNumber === COMPRESSED_MIPMAP_MAGIC) {
            var mipmapLevelNumber = bufferView.getUint32(COMPRESSED_HEADER_LENGTH, true);
            var mipmapLevelDataSize = bufferView.getUint32(COMPRESSED_HEADER_LENGTH + COMPRESSED_MIPMAP_LEVEL_COUNT_LENGTH, true);
            var fileHeaderByteLength = COMPRESSED_HEADER_LENGTH + COMPRESSED_MIPMAP_LEVEL_COUNT_LENGTH + mipmapLevelNumber * COMPRESSED_MIPMAP_DATA_SIZE_LENGTH;
            ImageAsset.parseCompressedTexture(file, 0, fileHeaderByteLength, mipmapLevelDataSize, type, out);
            var beginOffset = fileHeaderByteLength + mipmapLevelDataSize;
            for (var i = 1; i < mipmapLevelNumber; i++) {
              var endOffset = bufferView.getUint32(COMPRESSED_HEADER_LENGTH + COMPRESSED_MIPMAP_LEVEL_COUNT_LENGTH + i * COMPRESSED_MIPMAP_DATA_SIZE_LENGTH, true);
              ImageAsset.parseCompressedTexture(file, i, beginOffset, endOffset, type, out);
              beginOffset += endOffset;
            }
          } else {
            ImageAsset.parseCompressedTexture(file, 0, 0, 0, type, out);
          }
          return out;
        };
        ImageAsset.parseCompressedTexture = function parseCompressedTexture(file, levelIndex, beginOffset, endOffset, type, out) {
          switch (type) {
            case compressType.PVR:
              ImageAsset.parsePVRTexture(file, levelIndex, beginOffset, endOffset, out);
              break;
            case compressType.PKM:
              ImageAsset.parsePKMTexture(file, levelIndex, beginOffset, endOffset, out);
              break;
            case compressType.ASTC:
              ImageAsset.parseASTCTexture(file, levelIndex, beginOffset, endOffset, out);
              break;
          }
        };
        ImageAsset.parsePVRTexture = function parsePVRTexture(file, levelIndex, beginOffset, endOffset, out) {
          var buffer = file instanceof ArrayBuffer ? file : file.buffer;
          var header = new Int32Array(buffer, beginOffset, PVR_HEADER_LENGTH);
          if (header[PVR_HEADER_MAGIC] === PVR_MAGIC) {
            var byteOffset = beginOffset + header[PVR_HEADER_METADATA] + 52;
            var length = endOffset - header.byteLength;
            if (endOffset > 0) {
              var srcView = new Uint8Array(buffer, byteOffset, length);
              var dstView = new Uint8Array(out._data.byteLength + srcView.byteLength);
              dstView.set(out._data);
              dstView.set(srcView, out._data.byteLength);
              out._data = dstView;
              out.mipmapLevelDataSize[levelIndex] = length;
            } else {
              out._data = new Uint8Array(buffer, byteOffset);
            }
            out.width = levelIndex > 0 ? out.width : header[PVR_HEADER_WIDTH];
            out.height = levelIndex > 0 ? out.height : header[PVR_HEADER_HEIGHT];
          } else if (header[11] === 0x21525650) {
            var _byteOffset = beginOffset + header[0];
            var _length = endOffset - header.byteLength;
            if (endOffset > 0) {
              var _srcView = new Uint8Array(buffer, _byteOffset, _length);
              var _dstView = new Uint8Array(out._data.byteLength + _srcView.byteLength);
              _dstView.set(out._data);
              _dstView.set(_srcView, out._data.byteLength);
              out._data = _dstView;
              out.mipmapLevelDataSize[levelIndex] = _length;
            } else {
              out._data = new Uint8Array(buffer, _byteOffset);
            }
            out.width = levelIndex > 0 ? out.width : header[1];
            out.height = levelIndex > 0 ? out.height : header[2];
          } else {
            throw new Error('Invalid magic number in PVR header');
          }
        };
        ImageAsset.parsePKMTexture = function parsePKMTexture(file, levelIndex, beginOffset, endOffset, out) {
          var buffer = file instanceof ArrayBuffer ? file : file.buffer;
          var header = new Uint8Array(buffer, beginOffset, ETC_PKM_HEADER_LENGTH);
          var format = readBEUint16(header, ETC_PKM_FORMAT_OFFSET);
          if (format !== ETC1_RGB_NO_MIPMAPS && format !== ETC2_RGB_NO_MIPMAPS && format !== ETC2_RGBA_NO_MIPMAPS) {
            throw new Error('Invalid magic number in ETC header');
          }
          var byteOffset = beginOffset + ETC_PKM_HEADER_LENGTH;
          var length = endOffset - ETC_PKM_HEADER_LENGTH;
          if (endOffset > 0) {
            var srcView = new Uint8Array(buffer, byteOffset, length);
            var dstView = new Uint8Array(out._data.byteLength + srcView.byteLength);
            dstView.set(out._data);
            dstView.set(srcView, out._data.byteLength);
            out._data = dstView;
            out.mipmapLevelDataSize[levelIndex] = length;
          } else {
            out._data = new Uint8Array(buffer, byteOffset);
          }
          out.width = levelIndex > 0 ? out.width : readBEUint16(header, ETC_PKM_WIDTH_OFFSET);
          out.height = levelIndex > 0 ? out.height : readBEUint16(header, ETC_PKM_HEIGHT_OFFSET);
        };
        ImageAsset.parseASTCTexture = function parseASTCTexture(file, levelIndex, beginOffset, endOffset, out) {
          var buffer = file instanceof ArrayBuffer ? file : file.buffer;
          var header = new Uint8Array(buffer, beginOffset, ASTC_HEADER_LENGTH);
          var magicval = header[0] + (header[1] << 8) + (header[2] << 16) + (header[3] << 24);
          if (magicval !== ASTC_MAGIC) {
            throw new Error('Invalid magic number in ASTC header');
          }
          var xdim = header[ASTC_HEADER_MAGIC];
          var ydim = header[ASTC_HEADER_MAGIC + 1];
          var zdim = header[ASTC_HEADER_MAGIC + 2];
          if ((xdim < 3 || xdim > 6 || ydim < 3 || ydim > 6 || zdim < 3 || zdim > 6) && (xdim < 4 || xdim === 7 || xdim === 9 || xdim === 11 || xdim > 12 || ydim < 4 || ydim === 7 || ydim === 9 || ydim === 11 || ydim > 12 || zdim !== 1)) {
            throw new Error('Invalid block number in ASTC header');
          }
          var format = getASTCFormat(xdim, ydim);
          var byteOffset = beginOffset + ASTC_HEADER_LENGTH;
          var length = endOffset - ASTC_HEADER_LENGTH;
          if (endOffset > 0) {
            var srcView = new Uint8Array(buffer, byteOffset, length);
            var dstView = new Uint8Array(out._data.byteLength + srcView.byteLength);
            dstView.set(out._data);
            dstView.set(srcView, out._data.byteLength);
            out._data = dstView;
            out.mipmapLevelDataSize[levelIndex] = length;
          } else {
            out._data = new Uint8Array(buffer, byteOffset);
          }
          out.width = levelIndex > 0 ? out.width : header[ASTC_HEADER_SIZE_X_BEGIN] + (header[ASTC_HEADER_SIZE_X_BEGIN + 1] << 8) + (header[ASTC_HEADER_SIZE_X_BEGIN + 2] << 16);
          out.height = levelIndex > 0 ? out.height : header[ASTC_HEADER_SIZE_Y_BEGIN] + (header[ASTC_HEADER_SIZE_Y_BEGIN + 1] << 8) + (header[ASTC_HEADER_SIZE_Y_BEGIN + 2] << 16);
          out.format = format;
        };
        var _proto = ImageAsset.prototype;
        _proto.extractMipmap0 = function extractMipmap0() {
          if (this.mipmapLevelDataSize && this.mipmapLevelDataSize.length > 0) {
            var mipmapSize = this.mipmapLevelDataSize[0];
            var data = this.data;
            var dataView = new Uint8Array(data.buffer, 0, mipmapSize);
            var mipmap = new ImageAsset({
              _data: dataView,
              _compressed: true,
              width: this.width,
              height: this.height,
              format: this.format,
              mipmapLevelDataSize: []
            });
            mipmap._uuid = "" + this._uuid;
            return mipmap;
          } else {
            return this;
          }
        };
        _proto.extractMipmaps = function extractMipmaps() {
          var images = [];
          if (this.mipmapLevelDataSize && this.mipmapLevelDataSize.length > 0) {
            var mipmapLevelDataSize = this.mipmapLevelDataSize;
            var data = this.data;
            var byteOffset = 0;
            var height = this.height;
            var width = this.width;
            for (var _iterator2 = _createForOfIteratorHelperLoose(mipmapLevelDataSize), _step2; !(_step2 = _iterator2()).done;) {
              var mipmapSize = _step2.value;
              var dataView = new Uint8Array(data.buffer, byteOffset, mipmapSize);
              var mipmap = new ImageAsset({
                _data: dataView,
                _compressed: true,
                width: width,
                height: height,
                format: this.format,
                mipmapLevelDataSize: []
              });
              byteOffset += mipmapSize;
              mipmap._uuid = "" + this._uuid;
              width = Math.max(width >> 1, 1);
              height = Math.max(height >> 1, 1);
              images.push(mipmap);
            }
          } else {
            images.push(this);
          }
          return images;
        };
        function ImageAsset(nativeAsset) {
          var _this;
          _this = _Asset.call(this) || this;
          _this._nativeData = void 0;
          _this._exportedExts = undefined;
          _this._format = PixelFormat.RGBA8888;
          _this._width = 0;
          _this._height = 0;
          _this._nativeData = {
            _data: null,
            width: 0,
            height: 0,
            format: 0,
            _compressed: false,
            mipmapLevelDataSize: []
          };
          if (nativeAsset !== undefined) {
            _this.reset(nativeAsset);
          }
          return _this;
        }
        _proto.reset = function reset(data) {
          if (isImageBitmap(data)) {
            this._nativeData = data;
          } else if (!(data instanceof HTMLElement)) {
            this._nativeData = data;
            this._format = data.format;
          } else {
            this._nativeData = data;
          }
        };
        _proto.destroy = function destroy() {
          if (this.data && this.data instanceof HTMLImageElement) {
            this.data.src = '';
            this._setRawAsset('');
          } else if (isImageBitmap(this.data)) {
            var _this$data;
            (_this$data = this.data) === null || _this$data === void 0 ? void 0 : _this$data.close();
          }
          return _Asset.prototype.destroy.call(this);
        };
        _proto._serialize = function _serialize() {
        };
        _proto._deserialize = function _deserialize(data) {
          var fmtStr = '';
          if (typeof data === 'string') {
            fmtStr = data;
          } else {
            this._width = data.w;
            this._height = data.h;
            fmtStr = data.fmt;
          }
          var device = _getGlobalDevice();
          var extensionIDs = fmtStr.split('_');
          var preferedExtensionIndex = Number.MAX_VALUE;
          var format = this._format;
          var ext = '';
          var SupportTextureFormats = macro.SUPPORT_TEXTURE_FORMATS;
          for (var _iterator4 = _createForOfIteratorHelperLoose(extensionIDs), _step4; !(_step4 = _iterator4()).done;) {
            var extensionID = _step4.value;
            var extFormat = extensionID.split('@');
            var i = parseInt(extFormat[0], undefined);
            var tmpExt = ImageAsset.extnames[i] || extFormat[0];
            var index = SupportTextureFormats.indexOf(tmpExt);
            if (index !== -1 && index < preferedExtensionIndex) {
              var fmt = extFormat[1] ? parseInt(extFormat[1]) : this._format;
              if (tmpExt === '.astc' && (!device || !(device.getFormatFeatures(Format.ASTC_RGBA_4X4) & FormatFeatureBit.SAMPLED_TEXTURE))) {
                continue;
              } else if (tmpExt === '.pvr' && (!device || !(device.getFormatFeatures(Format.PVRTC_RGBA4) & FormatFeatureBit.SAMPLED_TEXTURE))) {
                continue;
              } else if ((fmt === PixelFormat.RGB_ETC1 || fmt === PixelFormat.RGBA_ETC1) && (!device || !(device.getFormatFeatures(Format.ETC_RGB8) & FormatFeatureBit.SAMPLED_TEXTURE))) {
                continue;
              } else if ((fmt === PixelFormat.RGB_ETC2 || fmt === PixelFormat.RGBA_ETC2) && (!device || !(device.getFormatFeatures(Format.ETC2_RGB8) & FormatFeatureBit.SAMPLED_TEXTURE))) {
                continue;
              } else if (tmpExt === '.webp' && !sys.hasFeature(sys.Feature.WEBP)) {
                continue;
              }
              preferedExtensionIndex = index;
              ext = tmpExt;
              format = fmt;
            }
          }
          if (ext) {
            this._setRawAsset(ext);
            this._format = format;
          } else {
            warnID(3121);
          }
        };
        _proto.initDefault = function initDefault(uuid) {
          _Asset.prototype.initDefault.call(this, uuid);
          if (!ImageAsset._sharedPlaceHolderCanvas) {
            var canvas = ccwindow.document.createElement('canvas');
            var context = canvas.getContext('2d');
            var l = canvas.width = canvas.height = 2;
            context.fillStyle = '#ff00ff';
            context.fillRect(0, 0, l, l);
            this.reset(canvas);
            ImageAsset._sharedPlaceHolderCanvas = canvas;
          } else {
            this.reset(ImageAsset._sharedPlaceHolderCanvas);
          }
        };
        _proto.validate = function validate() {
          return !!this.data;
        };
        _createClass(ImageAsset, [{
          key: "_nativeAsset",
          get: function get() {
            return this._nativeData;
          },
          set: function set(value) {
            if (!(value instanceof HTMLElement) && !isImageBitmap(value)) {
              value.format = value.format || this._format;
            }
            this.reset(value);
          }
        }, {
          key: "data",
          get: function get() {
            if (isNativeImage(this._nativeData)) {
              return this._nativeData;
            }
            return this._nativeData && this._nativeData._data;
          }
        }, {
          key: "width",
          get: function get() {
            return this._nativeData.width || this._width;
          }
        }, {
          key: "height",
          get: function get() {
            return this._nativeData.height || this._height;
          }
        }, {
          key: "format",
          get: function get() {
            return this._format;
          }
        }, {
          key: "isCompressed",
          get: function get() {
            return this._format >= PixelFormat.RGB_ETC1 && this._format <= PixelFormat.RGBA_ASTC_12x12 || this._format >= PixelFormat.RGB_A_PVRTC_2BPPV1 && this._format <= PixelFormat.RGBA_ETC1;
          }
        }, {
          key: "mipmapLevelDataSize",
          get: function get() {
            return this._nativeData.mipmapLevelDataSize;
          }
        }, {
          key: "url",
          get: function get() {
            return this.nativeUrl;
          }
        }]);
        return ImageAsset;
      }(Asset), _class3$Q.extnames = ['.png', '.jpg', '.jpeg', '.bmp', '.webp', '.pvr', '.pkm', '.astc'], _class3$Q._sharedPlaceHolderCanvas = null, _class3$Q), (_applyDecoratedDescriptor(_class2$2J.prototype, "_nativeAsset", [override], Object.getOwnPropertyDescriptor(_class2$2J.prototype, "_nativeAsset"), _class2$2J.prototype)), _class2$2J)) || _class$2_));
      function _getGlobalDevice() {
        return deviceManager.gfxDevice;
      }
      legacyCC.ImageAsset = ImageAsset;

      var _dec$30, _class$2Z, _class2$2I, _initializer$2p, _initializer2$1R, _initializer3$1g, _initializer4$_, _initializer5$J, _initializer6$y, _initializer7$s, _initializer8$r, _class3$P;
      ccenum(Format);
      var idGenerator$2 = new IDGenerator('Tex');
      var TextureBase = (_dec$30 = ccclass$n('cc.TextureBase'), _dec$30(_class$2Z = (_class2$2I = (_class3$P = function (_Asset) {
        _inheritsLoose(TextureBase, _Asset);
        function TextureBase() {
          var _this;
          _this = _Asset.call(this) || this;
          _this._format = _initializer$2p && _initializer$2p();
          _this._minFilter = _initializer2$1R && _initializer2$1R();
          _this._magFilter = _initializer3$1g && _initializer3$1g();
          _this._mipFilter = _initializer4$_ && _initializer4$_();
          _this._wrapS = _initializer5$J && _initializer5$J();
          _this._wrapT = _initializer6$y && _initializer6$y();
          _this._wrapR = _initializer7$s && _initializer7$s();
          _this._anisotropy = _initializer8$r && _initializer8$r();
          _this._width = 1;
          _this._height = 1;
          _this._id = void 0;
          _this._samplerInfo = new SamplerInfo();
          _this._gfxSampler = null;
          _this._gfxDevice = null;
          _this._textureHash = 0;
          _this._id = idGenerator$2.getNewId();
          _this._gfxDevice = _this._getGFXDevice();
          _this._textureHash = murmurhash2_32_gc(_this._id, 666);
          return _this;
        }
        var _proto = TextureBase.prototype;
        _proto.getId = function getId() {
          return this._id;
        };
        _proto.getPixelFormat = function getPixelFormat() {
          return this._format;
        };
        _proto.getAnisotropy = function getAnisotropy() {
          return this._anisotropy;
        };
        _proto.setWrapMode = function setWrapMode(wrapS, wrapT, wrapR) {
          if (wrapR === undefined) wrapR = wrapS;
          this._wrapS = wrapS;
          this._samplerInfo.addressU = wrapS;
          this._wrapT = wrapT;
          this._samplerInfo.addressV = wrapT;
          this._wrapR = wrapR;
          this._samplerInfo.addressW = wrapR;
          if (this._gfxDevice) {
            this._gfxSampler = this._gfxDevice.getSampler(this._samplerInfo);
          }
        };
        _proto.setFilters = function setFilters(minFilter, magFilter) {
          this._minFilter = minFilter;
          this._samplerInfo.minFilter = minFilter;
          this._magFilter = magFilter;
          this._samplerInfo.magFilter = magFilter;
          if (this._gfxDevice) {
            this._gfxSampler = this._gfxDevice.getSampler(this._samplerInfo);
          }
        };
        _proto.setMipFilter = function setMipFilter(mipFilter) {
          this._mipFilter = mipFilter;
          this._samplerInfo.mipFilter = mipFilter;
          if (this._gfxDevice) {
            this._gfxSampler = this._gfxDevice.getSampler(this._samplerInfo);
          }
        };
        _proto.setAnisotropy = function setAnisotropy(anisotropy) {
          this._anisotropy = anisotropy;
          this._samplerInfo.maxAnisotropy = anisotropy;
          if (this._gfxDevice) {
            this._gfxSampler = this._gfxDevice.getSampler(this._samplerInfo);
          }
        };
        _proto.destroy = function destroy() {
          var _cclegacy$director$ro;
          var destroyed = _Asset.prototype.destroy.call(this);
          if (destroyed && (_cclegacy$director$ro = legacyCC.director.root) !== null && _cclegacy$director$ro !== void 0 && _cclegacy$director$ro.batcher2D) {
            legacyCC.director.root.batcher2D._releaseDescriptorSetCache(this._textureHash);
          }
          return destroyed;
        };
        _proto.getHash = function getHash() {
          return this._textureHash;
        };
        _proto.getGFXTexture = function getGFXTexture() {
          return null;
        };
        _proto.getSamplerInfo = function getSamplerInfo() {
          return this._samplerInfo;
        };
        _proto.getGFXSampler = function getGFXSampler() {
          if (!this._gfxSampler) {
            if (this._gfxDevice) {
              this._gfxSampler = this._gfxDevice.getSampler(this._samplerInfo);
            } else {
              errorID(9302);
            }
          }
          return this._gfxSampler;
        };
        _proto._serialize = function _serialize(ctxForExporting) {
          return '';
        };
        _proto._deserialize = function _deserialize(serializedData, handle) {
          var data = serializedData;
          var fields = data.split(',');
          fields.unshift('');
          if (fields.length >= 5) {
            this.setFilters(parseInt(fields[1]), parseInt(fields[2]));
            this.setWrapMode(parseInt(fields[3]), parseInt(fields[4]));
          }
          if (fields.length >= 7) {
            this.setMipFilter(parseInt(fields[5]));
            this.setAnisotropy(parseInt(fields[6]));
          }
        };
        _proto._getGFXDevice = function _getGFXDevice() {
          return deviceManager.gfxDevice;
        };
        _proto._getGFXFormat = function _getGFXFormat() {
          return this._getGFXPixelFormat(this._format);
        };
        _proto._setGFXFormat = function _setGFXFormat(format) {
          this._format = format === undefined ? PixelFormat.RGBA8888 : format;
        };
        _proto._getGFXPixelFormat = function _getGFXPixelFormat(format) {
          if (format === PixelFormat.RGBA_ETC1) {
            format = PixelFormat.RGB_ETC1;
          } else if (format === PixelFormat.RGB_A_PVRTC_4BPPV1) {
            format = PixelFormat.RGB_PVRTC_4BPPV1;
          } else if (format === PixelFormat.RGB_A_PVRTC_2BPPV1) {
            format = PixelFormat.RGB_PVRTC_2BPPV1;
          }
          return format;
        };
        _createClass(TextureBase, [{
          key: "isCompressed",
          get: function get() {
            return this._format >= PixelFormat.RGB_ETC1 && this._format <= PixelFormat.RGBA_ASTC_12x12 || this._format >= PixelFormat.RGB_A_PVRTC_2BPPV1 && this._format <= PixelFormat.RGBA_ETC1;
          }
        }, {
          key: "width",
          get: function get() {
            return this._width;
          }
        }, {
          key: "height",
          get: function get() {
            return this._height;
          }
        }]);
        return TextureBase;
      }(Asset), _class3$P.PixelFormat = PixelFormat, _class3$P.WrapMode = WrapMode$1, _class3$P.Filter = Filter, _class3$P), (_initializer$2p = applyDecoratedInitializer(_class2$2I.prototype, "_format", [serializable$j], function () {
        return PixelFormat.RGBA8888;
      }), _initializer2$1R = applyDecoratedInitializer(_class2$2I.prototype, "_minFilter", [serializable$j], function () {
        return Filter.LINEAR;
      }), _initializer3$1g = applyDecoratedInitializer(_class2$2I.prototype, "_magFilter", [serializable$j], function () {
        return Filter.LINEAR;
      }), _initializer4$_ = applyDecoratedInitializer(_class2$2I.prototype, "_mipFilter", [serializable$j], function () {
        return Filter.NONE;
      }), _initializer5$J = applyDecoratedInitializer(_class2$2I.prototype, "_wrapS", [serializable$j], function () {
        return WrapMode$1.REPEAT;
      }), _initializer6$y = applyDecoratedInitializer(_class2$2I.prototype, "_wrapT", [serializable$j], function () {
        return WrapMode$1.REPEAT;
      }), _initializer7$s = applyDecoratedInitializer(_class2$2I.prototype, "_wrapR", [serializable$j], function () {
        return WrapMode$1.REPEAT;
      }), _initializer8$r = applyDecoratedInitializer(_class2$2I.prototype, "_anisotropy", [serializable$j], function () {
        return 0;
      })), _class2$2I)) || _class$2Z);
      legacyCC.TextureBase = TextureBase;

      var _dec$2$, _class$2Y, _dec2$26, _class2$2H, _dec3$1q, _class3$O;
      var Script = exports('ee', (_dec$2$ = ccclass$n('cc.Script'), _dec$2$(_class$2Y = function (_Asset) {
        _inheritsLoose(Script, _Asset);
        function Script() {
          return _Asset.apply(this, arguments) || this;
        }
        return Script;
      }(Asset)) || _class$2Y));
      legacyCC._Script = Script;
      var JavaScript = exports('ef', (_dec2$26 = ccclass$n('cc.JavaScript'), _dec2$26(_class2$2H = function (_Script) {
        _inheritsLoose(JavaScript, _Script);
        function JavaScript() {
          return _Script.apply(this, arguments) || this;
        }
        return JavaScript;
      }(Script)) || _class2$2H));
      legacyCC._JavaScript = JavaScript;
      var TypeScript = exports('eg', (_dec3$1q = ccclass$n('cc.TypeScript'), _dec3$1q(_class3$O = function (_Script2) {
        _inheritsLoose(TypeScript, _Script2);
        function TypeScript() {
          return _Script2.apply(this, arguments) || this;
        }
        return TypeScript;
      }(Script)) || _class3$O));
      legacyCC._TypeScript = TypeScript;

      var _dec$2_, _class$2X, _class2$2G, _initializer$2o, _initializer2$1Q, _initializer3$1f, _initializer4$Z, _initializer5$I;
      var EventHandler = exports('dy', (_dec$2_ = ccclass$n('cc.ClickEvent'), _dec$2_(_class$2X = (_class2$2G = function () {
        function EventHandler() {
          this.target = _initializer$2o && _initializer$2o();
          this.component = _initializer2$1Q && _initializer2$1Q();
          this._componentId = _initializer3$1f && _initializer3$1f();
          this.handler = _initializer4$Z && _initializer4$Z();
          this.customEventData = _initializer5$I && _initializer5$I();
        }
        EventHandler.emitEvents = function emitEvents(events) {
          for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
            args[_key - 1] = arguments[_key];
          }
          for (var i = 0, l = events.length; i < l; i++) {
            var event = events[i];
            if (!(event instanceof EventHandler)) {
              continue;
            }
            event.emit(args);
          }
        };
        var _proto = EventHandler.prototype;
        _proto.emit = function emit(params) {
          var target = this.target;
          if (!legacyCC.isValid(target)) {
            return;
          }
          this._genCompIdIfNeeded();
          var compType = legacyCC.js.getClassById(this._componentId);
          var comp = target.getComponent(compType);
          if (!legacyCC.isValid(comp)) {
            return;
          }
          var handler = comp[this.handler];
          if (typeof handler !== 'function') {
            return;
          }
          if (this.customEventData != null && this.customEventData !== '') {
            params = params.slice();
            params.push(this.customEventData);
          }
          handler.apply(comp, params);
        };
        _proto._compName2Id = function _compName2Id(compName) {
          var comp = legacyCC.js.getClassByName(compName);
          return legacyCC.js.getClassId(comp);
        };
        _proto._compId2Name = function _compId2Name(compId) {
          var comp = legacyCC.js.getClassById(compId);
          return legacyCC.js.getClassName(comp);
        };
        _proto._genCompIdIfNeeded = function _genCompIdIfNeeded() {
          if (!this._componentId) {
            this._componentName = this.component;
            this.component = '';
          }
        };
        _createClass(EventHandler, [{
          key: "_componentName",
          get: function get() {
            this._genCompIdIfNeeded();
            return this._compId2Name(this._componentId);
          },
          set: function set(value) {
            this._componentId = this._compName2Id(value);
          }
        }]);
        return EventHandler;
      }(), (_initializer$2o = applyDecoratedInitializer(_class2$2G.prototype, "target", [serializable$j], function () {
        return null;
      }), _initializer2$1Q = applyDecoratedInitializer(_class2$2G.prototype, "component", [serializable$j], function () {
        return '';
      }), _initializer3$1f = applyDecoratedInitializer(_class2$2G.prototype, "_componentId", [serializable$j], function () {
        return '';
      }), _initializer4$Z = applyDecoratedInitializer(_class2$2G.prototype, "handler", [serializable$j], function () {
        return '';
      }), _initializer5$I = applyDecoratedInitializer(_class2$2G.prototype, "customEventData", [serializable$j], function () {
        return '';
      })), _class2$2G)) || _class$2X));

      var _dec$2Z, _dec2$25, _class$2W, _class2$2F, _initializer$2n, _initializer2$1P, _initializer3$1e, _class3$N;
      var idGenerator$1 = new IDGenerator('Comp');
      var IsOnLoadCalled$1 = CCObject.Flags.IsOnLoadCalled;
      var NullNode = null;
      var Component = exports('dz', (_dec$2Z = ccclass$n('cc.Component'), _dec2$25 = type$7(Script), _dec$2Z(_class$2W = (_class2$2F = (_class3$N = function (_CCObject) {
        _inheritsLoose(Component, _CCObject);
        function Component() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _CCObject.call.apply(_CCObject, [this].concat(args)) || this;
          _this.node = _initializer$2n && _initializer$2n();
          _this._enabled = _initializer2$1P && _initializer2$1P();
          _this.__prefab = _initializer3$1e && _initializer3$1e();
          _this._sceneGetter = null;
          _this._id = idGenerator$1.getNewId();
          return _this;
        }
        var _proto = Component.prototype;
        _proto._getRenderScene = function _getRenderScene() {
          if (this._sceneGetter) {
            return this._sceneGetter();
          }
          return this.node.scene.renderScene;
        };
        _proto.addComponent = function addComponent(typeOrClassName) {
          return this.node.addComponent(typeOrClassName);
        };
        _proto.getComponent = function getComponent(typeOrClassName) {
          return this.node.getComponent(typeOrClassName);
        };
        _proto.getComponents = function getComponents(typeOrClassName) {
          return this.node.getComponents(typeOrClassName);
        };
        _proto.getComponentInChildren = function getComponentInChildren(typeOrClassName) {
          return this.node.getComponentInChildren(typeOrClassName);
        };
        _proto.getComponentsInChildren = function getComponentsInChildren(typeOrClassName) {
          return this.node.getComponentsInChildren(typeOrClassName);
        };
        _proto.destroy = function destroy() {
          if (_CCObject.prototype.destroy.call(this)) {
            if (this._enabled && this.node.activeInHierarchy) {
              legacyCC.director._compScheduler.disableComp(this);
            }
            return true;
          }
          return false;
        };
        _proto._onPreDestroy = function _onPreDestroy() {
          this.unscheduleAllCallbacks();
          legacyCC.director._nodeActivator.destroyComp(this);
          this.node._removeComponent(this);
        };
        _proto._instantiate = function _instantiate(cloned) {
          if (!cloned) {
            cloned = legacyCC.instantiate._clone(this, this);
          }
          if (cloned) {
            cloned.node = NullNode;
          }
          return cloned;
        };
        _proto.schedule = function schedule(callback, interval, repeat, delay) {
          if (interval === void 0) {
            interval = 0;
          }
          if (repeat === void 0) {
            repeat = legacyCC.macro.REPEAT_FOREVER;
          }
          if (delay === void 0) {
            delay = 0;
          }
          assertID(Boolean(callback), 1619);
          interval = interval || 0;
          assertID(interval >= 0, 1620);
          repeat = Number.isNaN(repeat) ? legacyCC.macro.REPEAT_FOREVER : repeat;
          delay = delay || 0;
          var scheduler = legacyCC.director.getScheduler();
          var paused = scheduler.isTargetPaused(this);
          scheduler.schedule(callback, this, interval, repeat, delay, paused);
        };
        _proto.scheduleOnce = function scheduleOnce(callback, delay) {
          if (delay === void 0) {
            delay = 0;
          }
          this.schedule(callback, 0, 0, delay);
        };
        _proto.unschedule = function unschedule(callback_fn) {
          if (!callback_fn) {
            return;
          }
          legacyCC.director.getScheduler().unschedule(callback_fn, this);
        };
        _proto.unscheduleAllCallbacks = function unscheduleAllCallbacks() {
          legacyCC.director.getScheduler().unscheduleAllForTarget(this);
        };
        _createClass(Component, [{
          key: "name",
          get: function get() {
            if (this._name) {
              return this._name;
            }
            var className = getClassName(this);
            var trimLeft = className.lastIndexOf('.');
            if (trimLeft >= 0) {
              className = className.slice(trimLeft + 1);
            }
            if (this.node) {
              return this.node.name + "<" + className + ">";
            } else {
              return className;
            }
          },
          set: function set(value) {
            this._name = value;
          }
        }, {
          key: "uuid",
          get: function get() {
            return this._id;
          }
        }, {
          key: "__scriptAsset",
          get: function get() {
            return null;
          }
        }, {
          key: "enabled",
          get: function get() {
            return this._enabled;
          },
          set: function set(value) {
            if (this._enabled !== value) {
              this._enabled = value;
              if (this.node.activeInHierarchy) {
                var compScheduler = legacyCC.director._compScheduler;
                if (value) {
                  compScheduler.enableComp(this);
                } else {
                  compScheduler.disableComp(this);
                }
              }
            }
          }
        }, {
          key: "enabledInHierarchy",
          get: function get() {
            return this._enabled && this.node && this.node.activeInHierarchy;
          }
        }, {
          key: "_isOnLoadCalled",
          get: function get() {
            return this._objFlags & IsOnLoadCalled$1;
          }
        }, {
          key: "internalUpdate",
          get: function get() {
            return this.update;
          }
        }, {
          key: "internalLateUpdate",
          get: function get() {
            return this.lateUpdate;
          }
        }, {
          key: "internalPreload",
          get: function get() {
            return this.__preload;
          }
        }, {
          key: "internalOnLoad",
          get: function get() {
            return this.onLoad;
          }
        }, {
          key: "internalStart",
          get: function get() {
            return this.start;
          }
        }, {
          key: "internalOnEnable",
          get: function get() {
            return this.onEnable;
          }
        }, {
          key: "internalOnDisable",
          get: function get() {
            return this.onDisable;
          }
        }, {
          key: "internalOnDestroy",
          get: function get() {
            return this.onDestroy;
          }
        }]);
        return Component;
      }(CCObject), _class3$N.EventHandler = EventHandler, _class3$N._executionOrder = 0, _class3$N._requireComponent = null, _class3$N.system = null, _class3$N), (_applyDecoratedDescriptor(_class2$2F.prototype, "__scriptAsset", [_dec2$25], Object.getOwnPropertyDescriptor(_class2$2F.prototype, "__scriptAsset"), _class2$2F.prototype), _initializer$2n = applyDecoratedInitializer(_class2$2F.prototype, "node", [serializable$j], function () {
        return NullNode;
      }), _initializer2$1P = applyDecoratedInitializer(_class2$2F.prototype, "_enabled", [serializable$j], function () {
        return true;
      }), _initializer3$1e = applyDecoratedInitializer(_class2$2F.prototype, "__prefab", [serializable$j], function () {
        return null;
      })), _class2$2F)) || _class$2W));
      value(Component, '_registerEditorProps', function (cls, props) {
        var reqComp = props.requireComponent;
        if (reqComp) {
          if (Array.isArray(reqComp)) {
            reqComp = reqComp.filter(Boolean);
          }
          cls._requireComponent = reqComp;
        }
        var order = props.executionOrder;
        if (order && typeof order === 'number') {
          cls._executionOrder = order;
        }
      });
      legacyCC.Component = Component;

      var _dec$2Y, _class$2V, _class2$2E, _initializer$2m;
      var MissingScript = exports('dV', (_dec$2Y = ccclass$n('cc.MissingScript'), _dec$2Y(_class$2V = (_class2$2E = function (_Component) {
        _inheritsLoose(MissingScript, _Component);
        MissingScript.safeFindClass = function safeFindClass(id) {
          var cls = getClassById(id);
          if (cls) {
            return cls;
          }
          legacyCC.deserialize.reportMissingClass(id);
          return undefined;
        };
        function MissingScript() {
          var _this;
          _this = _Component.call(this) || this;
          _this._$erialized = _initializer$2m && _initializer$2m();
          return _this;
        }
        var _proto = MissingScript.prototype;
        _proto.onLoad = function onLoad() {
          warnID(4600, this.node.name);
        };
        return MissingScript;
      }(Component), (_initializer$2m = applyDecoratedInitializer(_class2$2E.prototype, "_$erialized", [serializable$j, editorOnly], function () {
        return null;
      })), _class2$2E)) || _class$2V));
      legacyCC._MissingScript = MissingScript;
      try {
        var props = MissingScript.__values__;
        if (props.length === 0 || props[props.length - 1] !== '_$erialized') {
          error("The '_$erialized' prop in MissingScript is missing. Please contact jare.");
          error("    Error props: ['" + props + "']");
        }
      } catch (e) {
        error("Error when checking MissingScript 5, " + e);
      }

      var VERSION = 1;
      var MAGIC = 0x4E4F4343;
      var CHUNK_ALIGN_AS = 8;
      var CCON = function () {
        function CCON(document, chunks) {
          this._document = void 0;
          this._chunks = void 0;
          this._document = document;
          this._chunks = chunks;
        }
        _createClass(CCON, [{
          key: "document",
          get: function get() {
            return this._document;
          }
        }, {
          key: "chunks",
          get: function get() {
            return this._chunks;
          }
        }]);
        return CCON;
      }();
      function parseCCONJson(json) {
        var cconPreface = json;
        return {
          chunks: cconPreface.chunks,
          document: cconPreface.document
        };
      }
      function decodeCCONBinary(bytes) {
        if (bytes.length < 16) {
          throw new InvalidCCONError(getError(13102));
        }
        var dataView = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
        var magic = dataView.getUint32(0, true);
        if (magic !== MAGIC) {
          throw new InvalidCCONError(getError(13100));
        }
        var version = dataView.getUint32(4, true);
        if (version !== VERSION) {
          throw new InvalidCCONError(getError(13101, version));
        }
        var dataByteLength = dataView.getUint32(8, true);
        if (dataByteLength !== dataView.byteLength) {
          throw new InvalidCCONError(getError(13102));
        }
        var chunksStart = 12;
        var jsonDataLength = dataView.getUint32(chunksStart, true);
        chunksStart += 4;
        var jsonData = new Uint8Array(dataView.buffer, chunksStart + dataView.byteOffset, jsonDataLength);
        chunksStart += jsonDataLength;
        var jsonString = decodeJson(jsonData);
        var json;
        try {
          json = JSON.parse(jsonString);
        } catch (err) {
          throw new InvalidCCONError(err);
        }
        var chunks = [];
        while (chunksStart < dataView.byteLength) {
          if (chunksStart % CHUNK_ALIGN_AS !== 0) {
            var padding = CHUNK_ALIGN_AS - chunksStart % CHUNK_ALIGN_AS;
            chunksStart += padding;
          }
          var chunkDataLength = dataView.getUint32(chunksStart, true);
          chunksStart += 4;
          chunks.push(new Uint8Array(dataView.buffer, chunksStart + dataView.byteOffset, chunkDataLength));
          chunksStart += chunkDataLength;
        }
        if (chunksStart !== dataView.byteLength) {
          throw new InvalidCCONError(getError(13102));
        }
        return new CCON(json, chunks);
      }
      function decodeJson(data) {
        if (typeof TextDecoder !== 'undefined') {
          return new TextDecoder().decode(data);
        } else if ('Buffer' in globalThis) {
          var _ref2 = globalThis,
            _Buffer2 = _ref2.Buffer;
          return _Buffer2.from(data.buffer, data.byteOffset, data.byteLength).toString();
        } else {
          throw new Error(getError(13104));
        }
      }
      var InvalidCCONError = function (_Error) {
        _inheritsLoose(InvalidCCONError, _Error);
        function InvalidCCONError() {
          return _Error.apply(this, arguments) || this;
        }
        return InvalidCCONError;
      }(_wrapNativeSuper(Error));
      (function () {
        function BufferBuilder() {
          this._viewOrPaddings = [];
          this._length = 0;
        }
        var _proto = BufferBuilder.prototype;
        _proto.alignAs = function alignAs(align) {
          if (align !== 0) {
            var remainder = this._length % align;
            if (remainder !== 0) {
              var padding = align - remainder;
              this._viewOrPaddings.push(padding);
              this._length += padding;
              return padding;
            }
          }
          return 0;
        };
        _proto.append = function append(view) {
          var result = this._length;
          this._viewOrPaddings.push(view);
          this._length += view.byteLength;
          return result;
        };
        _proto.get = function get() {
          var result = new Uint8Array(this._length);
          var counter = 0;
          this._viewOrPaddings.forEach(function (viewOrPadding) {
            if (typeof viewOrPadding === 'number') {
              counter += viewOrPadding;
            } else {
              result.set(new Uint8Array(viewOrPadding.buffer, viewOrPadding.byteOffset, viewOrPadding.byteLength), counter);
              counter += viewOrPadding.byteLength;
            }
          });
          return result;
        };
        _createClass(BufferBuilder, [{
          key: "byteLength",
          get: function get() {
            return this._length;
          }
        }]);
        return BufferBuilder;
      })();
      legacyCC.internal.parseCCONJson = parseCCONJson;
      legacyCC.internal.decodeCCONBinary = decodeCCONBinary;
      legacyCC.internal.CCON = CCON;

      function compileObjectTypeJit(sources, defaultValue, accessorToSet, propNameLiteralToSet, assumeHavePropIfIsValue) {
        if (defaultValue instanceof legacyCC.ValueType) {
          if (!assumeHavePropIfIsValue) {
            sources.push('if(prop){');
          }
          var ctorCode = getClassName(defaultValue);
          sources.push("s._deserializeFastDefinedObject(o" + accessorToSet + ",prop," + ctorCode + ");");
          if (!assumeHavePropIfIsValue) {
            sources.push("}else o" + accessorToSet + "=null;");
          }
        } else {
          sources.push("\nif (prop) {\n    s._deserializeAndAssignField(o, prop, " + propNameLiteralToSet + ");\n} else {\n    o" + accessorToSet + "=null;\n}\n");
        }
      }
      var compileDeserialize = compileDeserializeJIT ;
      var DELIMITER = CCClass.Attr.DELIMETER;
      var POSTFIX_TYPE = DELIMITER + "type";
      var POSTFIX_DEFAULT = DELIMITER + "default";
      var POSTFIX_FORMERLY_SERIALIZED_AS = DELIMITER + "formerlySerializedAs";
      function compileDeserializeJIT(self, klass) {
        var attrs = CCClass.Attr.getClassAttrs(klass);
        var props = klass.__values__;
        var sources = ['var prop;'];
        var fastMode = canBeDeserializedInFastMode(klass);
        for (var p = 0; p < props.length; p++) {
          var propName = props[p];
          var accessorToSet = void 0;
          var propNameLiteralToSet = void 0;
          if (CCClass.IDENTIFIER_RE.test(propName)) {
            propNameLiteralToSet = "\"" + propName + "\"";
            accessorToSet = "." + propName;
          } else {
            propNameLiteralToSet = CCClass.escapeForJS(propName);
            accessorToSet = "[" + propNameLiteralToSet + "]";
          }
          var accessorToGet = accessorToSet;
          if (attrs[propName + POSTFIX_FORMERLY_SERIALIZED_AS]) {
            var propNameToRead = attrs[propName + POSTFIX_FORMERLY_SERIALIZED_AS];
            if (CCClass.IDENTIFIER_RE.test(propNameToRead)) {
              accessorToGet = "." + propNameToRead;
            } else {
              accessorToGet = "[" + CCClass.escapeForJS(propNameToRead) + "]";
            }
          }
          sources.push("prop=d" + accessorToGet + ";");
          sources.push("if(typeof " + ('prop') + "!==\"undefined\"){");
          var defaultValue = CCClass.getDefault(attrs[propName + POSTFIX_DEFAULT]);
          var userType = attrs[propName + POSTFIX_TYPE];
          if (fastMode && (defaultValue !== undefined || userType)) {
            var isPrimitiveTypeInFastMode = isPrimitivePropertyByDefaultOrType(defaultValue, userType);
            if (isPrimitiveTypeInFastMode) {
              sources.push("o" + accessorToSet + "=prop;");
            } else {
              compileObjectTypeJit(sources, defaultValue, accessorToSet, propNameLiteralToSet, true);
            }
          } else {
            sources.push("" + ("if(typeof " + ('prop') + "!==\"object\"){" + 'o') + accessorToSet + "=prop;" + "}else{");
            compileObjectTypeJit(sources, defaultValue, accessorToSet, propNameLiteralToSet, false);
            sources.push('}');
          }
          sources.push('}');
        }
        if (isChildClassOf(klass, legacyCC.Node) || isChildClassOf(klass, legacyCC.Component)) {
          {
            sources.push('d._id&&(o._id=d._id);');
          }
        }
        if (props[props.length - 1] === '_$erialized') {
          sources.push('o._$erialized=JSON.parse(JSON.stringify(d));');
          sources.push('s._fillPlainObject(o._$erialized,d);');
        }
        return Function('s', 'o', 'd', 'k', sources.join(''));
      }
      function canBeDeserializedInFastMode(klass) {
        return BUILTIN_CLASSID_RE.test(getClassId(klass));
      }
      function isPrimitivePropertyByDefaultOrType(defaultValue, userType) {
        if (defaultValue === undefined) {
          return userType instanceof CCClass.Attr.PrimitiveType || userType === ENUM_TAG || userType === BITMASK_TAG;
        } else {
          var defaultType = typeof defaultValue;
          return defaultType === 'string' || defaultType === 'number' || defaultType === 'boolean';
        }
      }
      var DeserializerPool = function (_js$Pool) {
        _inheritsLoose(DeserializerPool, _js$Pool);
        function DeserializerPool() {
          return _js$Pool.call(this, function (deserializer) {
            deserializer.clear();
          }, 1) || this;
        }
        return DeserializerPool;
      }(Pool$1);
      DeserializerPool.prototype.get = function (details, classFinder, reportMissingClass, customEnv, ignoreEditorOnly) {
        var cache = this._get();
        if (cache) {
          cache.reset(details, classFinder, reportMissingClass, customEnv, ignoreEditorOnly);
          return cache;
        } else {
          return new _Deserializer(details, classFinder, reportMissingClass, customEnv, ignoreEditorOnly);
        }
      };
      var _Deserializer = function () {
        function _Deserializer(result, classFinder, reportMissingClass, customEnv, ignoreEditorOnly) {
          this.deserializedList = void 0;
          this.deserializedData = void 0;
          this._ignoreEditorOnly = void 0;
          this.result = result;
          this.customEnv = customEnv;
          this.deserializedList = [];
          this.deserializedData = null;
          this._classFinder = classFinder;
          this._reportMissingClass = reportMissingClass;
          this._onDereferenced = classFinder === null || classFinder === void 0 ? void 0 : classFinder.onDereferenced;
        }
        var _proto = _Deserializer.prototype;
        _proto.reset = function reset(result, classFinder, reportMissingClass, customEnv, ignoreEditorOnly) {
          this.result = result;
          this.customEnv = customEnv;
          this._classFinder = classFinder;
          this._reportMissingClass = reportMissingClass;
          this._onDereferenced = classFinder === null || classFinder === void 0 ? void 0 : classFinder.onDereferenced;
        };
        _proto.clear = function clear() {
          this.result = null;
          this.customEnv = null;
          this.deserializedList.length = 0;
          this.deserializedData = null;
          this._classFinder = null;
          this._reportMissingClass = null;
          this._onDereferenced = null;
        };
        _proto.deserialize = function deserialize(serializedData) {
          var fromCCON = false;
          var jsonObj;
          if (serializedData instanceof CCON) {
            fromCCON = true;
            jsonObj = serializedData.document;
            if (serializedData.chunks.length > 0) {
              assertIsTrue(serializedData.chunks.length === 1);
              this._mainBinChunk = serializedData.chunks[0];
            }
          } else {
            jsonObj = serializedData;
          }
          this._serializedData = jsonObj;
          this._context = {
            fromCCON: fromCCON
          };
          var serializedRootObject = Array.isArray(jsonObj) ? jsonObj[0] : jsonObj;
          {
            this.deserializedData = this._deserializeObject(serializedRootObject, 0);
          }
          this._serializedData = undefined;
          this._mainBinChunk = undefined;
          this._context = undefined;
          return this.deserializedData;
        };
        _proto._deserializeObject = function _deserializeObject(serialized, globalIndex, owner, propName) {
          switch (serialized.__type__) {
            case 'TypedArray':
              return this._deserializeTypedArrayView(serialized);
            case 'TypedArrayRef':
              return this._deserializeTypedArrayViewRef(serialized);
            default:
              if (serialized.__type__) {
                return this._deserializeTypeTaggedObject(serialized, globalIndex, owner, propName);
              } else if (!Array.isArray(serialized)) {
                return this._deserializePlainObject(serialized);
              } else {
                return this._deserializeArray(serialized);
              }
          }
        };
        _proto._deserializeTypedArrayView = function _deserializeTypedArrayView(value) {
          return globalThis[value.ctor].from(value.array);
        };
        _proto._deserializeTypedArrayViewRef = function _deserializeTypedArrayViewRef(value) {
          var offset = value.offset,
            length = value.length,
            constructorName = value.ctor;
          var obj = new globalThis[constructorName](this._mainBinChunk.buffer, this._mainBinChunk.byteOffset + offset, length);
          return obj;
        };
        _proto._deserializeArray = function _deserializeArray(value) {
          var obj = new Array(value.length);
          var prop;
          for (var i = 0; i < value.length; i++) {
            prop = value[i];
            if (typeof prop === 'object' && prop) {
              var isAssetType = this._deserializeAndAssignField(obj, prop, "" + i);
              if (isAssetType) {
                obj[i] = null;
              }
            } else {
              obj[i] = prop;
            }
          }
          return obj;
        };
        _proto._deserializePlainObject = function _deserializePlainObject(value) {
          var obj = {};
          this._fillPlainObject(obj, value);
          return obj;
        };
        _proto._deserializeTypeTaggedObject = function _deserializeTypeTaggedObject(value, globalIndex, owner, propName) {
          var _this = this;
          var type = value.__type__;
          var klass = this._classFinder(type, value, owner, propName);
          if (!klass) {
            var notReported = this._classFinder === getClassById;
            if (notReported) {
              this._reportMissingClass(type);
            }
            return null;
          }
          var createObject = function createObject(constructor) {
            var obj = new constructor();
            if (globalIndex >= 0) {
              _this.deserializedList[globalIndex] = obj;
            }
            return obj;
          };
          {
            var obj = createObject(klass);
            this._deserializeInto(value, obj, klass);
            return obj;
          }
        };
        _proto._deserializeInto = function _deserializeInto(value, object, constructor, skipCustomized) {
          if (skipCustomized === void 0) {
            skipCustomized = false;
          }
          if (!skipCustomized && object[deserializeTag]) {
            this._runCustomizedDeserialize(value, object, constructor);
            return;
          }
          if (object._deserialize) {
            object._deserialize(value.content, this);
            return;
          }
          if (legacyCC.Class._isCCClass(constructor)) {
            this._deserializeFireClass(object, value, constructor);
          } else {
            this._deserializeFastDefinedObject(object, value, constructor);
          }
        };
        _proto._runCustomizedDeserialize = function _runCustomizedDeserialize(value, object, constructor) {
          var _this2 = this;
          var serializationInput = {
            readProperty: function readProperty(name) {
              var serializedField = value[name];
              if (typeof serializedField !== 'object' || !serializedField) {
                return serializedField;
              } else {
                return _this2._deserializeObjectField(serializedField);
              }
            },
            readThis: function readThis() {
              _this2._deserializeInto(value, object, constructor, true);
            },
            readSuper: function readSuper() {
              var superConstructor = getSuper(constructor);
              if (superConstructor) {
                _this2._deserializeInto(value, object, superConstructor);
              }
            }
          };
          object[deserializeTag](serializationInput, this._context);
        };
        _proto._deserializeFireClass = function _deserializeFireClass(obj, serialized, klass) {
          var deserialize;
          if (klass.hasOwnProperty('__deserialize__')) {
            deserialize = klass.__deserialize__;
          } else {
            deserialize = compileDeserialize(this, klass);
            try {
              if (klass === MissingScript) {
                var props = klass.__values__;
                if (props.length === 0 || props[props.length - 1] !== '_$erialized') {
                  error("The '_$erialized' prop of MissingScript is missing. Will force the raw data to be save.");
                  error("    Error props: ['" + props + "']. Please contact jare.");
                }
                var rawDeserialize = deserialize;
                deserialize = function deserialize(deserializer, object, deserialized, constructor) {
                  rawDeserialize(deserializer, object, deserialized, constructor);
                  if (!object._$erialized) {
                    error("Unable to stash previously serialized data. " + JSON.stringify(deserialized));
                  }
                };
              }
            } catch (e) {
              error("Error when checking MissingScript 6, " + e);
            }
            value(klass, '__deserialize__', deserialize, true);
          }
          deserialize(this, obj, serialized, klass);
        };
        _proto._deserializeAndAssignField = function _deserializeAndAssignField(obj, serializedField, propName) {
          var id = serializedField.__id__;
          if (typeof id === 'number') {
            var field = this.deserializedList[id];
            if (field) {
              obj[propName] = field;
            } else {
              var _this$_onDereferenced;
              var source = this._serializedData[id];
              {
                obj[propName] = this._deserializeObject(source, id, undefined, propName);
              }
              (_this$_onDereferenced = this._onDereferenced) === null || _this$_onDereferenced === void 0 ? void 0 : _this$_onDereferenced.call(this, this.deserializedList, id, obj, propName);
            }
          } else {
            var uuid = serializedField.__uuid__;
            if (uuid) {
              var expectedType = serializedField.__expectedType__;
              this.result.push(obj, propName, uuid, expectedType);
            } else {
              obj[propName] = this._deserializeObject(serializedField, -1);
            }
          }
          return false;
        };
        _proto._deserializeObjectField = function _deserializeObjectField(serializedField) {
          var id = serializedField.__id__;
          if (typeof id === 'number') {
            var field = this.deserializedList[id];
            if (field) {
              return field;
            } else {
              var source = this._serializedData[id];
              var _field = this._deserializeObject(source, id, undefined, undefined);
              return _field;
            }
          } else {
            var uuid = serializedField.__uuid__;
            if (uuid) {
              serializedField.__expectedType__;
              throw new Error("Asset reference field serialization is currently not supported in custom serialization.");
            } else {
              return this._deserializeObject(serializedField, -1);
            }
          }
        };
        _proto._fillPlainObject = function _fillPlainObject(instance, serialized) {
          for (var propName in serialized) {
            if (!serialized.hasOwnProperty(propName)) {
              continue;
            }
            var prop = serialized[propName];
            if (typeof prop !== 'object') {
              if (propName !== '__type__') {
                instance[propName] = prop;
              }
            } else if (prop) {
              var isAssetType = this._deserializeAndAssignField(instance, prop, propName);
              if (isAssetType) {
                instance[propName] = null;
              }
            } else {
              instance[propName] = null;
            }
          }
        };
        _proto._deserializeFastDefinedObject = function _deserializeFastDefinedObject(instance, serialized, klass) {
          if (klass === legacyCC.Vec2) {
            instance.x = serialized.x || 0;
            instance.y = serialized.y || 0;
            return;
          } else if (klass === legacyCC.Vec3) {
            instance.x = serialized.x || 0;
            instance.y = serialized.y || 0;
            instance.z = serialized.z || 0;
            return;
          } else if (klass === legacyCC.Color) {
            instance.r = serialized.r || 0;
            instance.g = serialized.g || 0;
            instance.b = serialized.b || 0;
            var a = serialized.a;
            instance.a = a === undefined ? 255 : a;
            return;
          } else if (klass === legacyCC.Size) {
            instance.width = serialized.width || 0;
            instance.height = serialized.height || 0;
            return;
          }
          var attrs = CCClass.Attr.getClassAttrs(klass);
          var props = klass.__values__;
          if (!props) {
            error("Unable to deserialize " + getClassName(klass) + ". " + 'For non-CCClass types, they can only be marked as serializable by `CCClass.fastDefine`.');
          }
          for (var i = 0; i < props.length; i++) {
            var propName = props[i];
            var value = serialized[propName];
            var exists = value !== undefined || serialized.hasOwnProperty(propName);
            if (!exists) {
              value = CCClass.getDefault(attrs[propName + POSTFIX_DEFAULT]);
            }
            if (typeof value !== 'object') {
              instance[propName] = value;
            } else if (value) {
              this._deserializeAndAssignField(instance, value, propName);
            } else {
              instance[propName] = null;
            }
          }
        };
        _createClass(_Deserializer, [{
          key: "ignoreEditorOnly",
          get: function get() {
            return this._ignoreEditorOnly;
          }
        }]);
        return _Deserializer;
      }();
      _Deserializer.pool = new DeserializerPool();
      function deserializeDynamic(data, details, options) {
        var _options$reportMissin;
        options = options || {};
        var classFinder = options.classFinder || getClassById;
        var createAssetRefs = options.createAssetRefs || sys.platform === Platform.EDITOR_CORE;
        var customEnv = options.customEnv;
        var ignoreEditorOnly = options.ignoreEditorOnly;
        var reportMissingClass = (_options$reportMissin = options.reportMissingClass) !== null && _options$reportMissin !== void 0 ? _options$reportMissin : legacyCC.deserialize.reportMissingClass;
        details.init();
        var deserializer = _Deserializer.pool.get(details, classFinder, reportMissingClass, customEnv, ignoreEditorOnly);
        legacyCC.game._isCloning = true;
        var res = deserializer.deserialize(data);
        legacyCC.game._isCloning = false;
        _Deserializer.pool.put(deserializer);
        if (createAssetRefs) {
          details.assignAssetsBy(function (uuid, options) {
            return EditorExtends.serialize.asAsset(uuid, options.type);
          });
        }
        return res;
      }

      function reportMissingClass(id) {
        {
          errorID(5302, id);
        }
      }

      var constructorMap = [Vec2, Vec3, Vec4, Quat, Color$1, Size$1, Rect$1, Mat4];
      function vec4LikeSetter(obj, data) {
        obj.x = data[1];
        obj.y = data[2];
        obj.z = data[3];
        obj.w = data[4];
      }
      var setterMap = [function (obj, data) {
        obj.x = data[1];
        obj.y = data[2];
      }, function (obj, data) {
        obj.x = data[1];
        obj.y = data[2];
        obj.z = data[3];
      }, vec4LikeSetter, vec4LikeSetter, function (obj, data) {
        obj._val = data[1];
      }, function (obj, data) {
        obj.width = data[1];
        obj.height = data[2];
      }, function (obj, data) {
        obj.x = data[1];
        obj.y = data[2];
        obj.width = data[3];
        obj.height = data[4];
      }, function (obj, data) {
        Mat4.fromArray(obj, data, 1);
      }];
      function deserializeBuiltinValueType(data, owner, key, value) {
        var typeIndex = value[0];
        assertIsTrue(typeIndex >= 0 && typeIndex < constructorMap.length);
        var object = new constructorMap[typeIndex]();
        var setter = setterMap[typeIndex];
        setter(object, value);
        owner[key] = object;
      }
      function deserializeBuiltinValueTypeInto(data, owner, key, value) {
        var typeIndex = value[0];
        assertIsTrue(typeIndex >= 0 && typeIndex < constructorMap.length);
        {
          var object = owner[key];
          var _setter = setterMap[typeIndex];
          _setter(object, value);
        }
      }

      var SUPPORT_MIN_FORMAT_VERSION = 1;
      var EMPTY_PLACEHOLDER = 0;
      var DataTypeID = {
        SimpleType: 0,
        InstanceRef: 1,
        Array_InstanceRef: 2,
        Array_AssetRefByInnerObj: 3,
        Class: 4,
        ValueTypeCreated: 5,
        AssetRefByInnerObj: 6,
        TRS: 7,
        ValueType: 8,
        Array_Class: 9,
        CustomizedClass: 10,
        Dict: 11,
        Array: 12,
        ARRAY_LENGTH: 13
      };
      var CLASS_TYPE = 0;
      var CLASS_KEYS = 1;
      var CLASS_PROP_TYPE_OFFSET = 2;
      var MASK_CLASS = 0;
      var OBJ_DATA_MASK = 0;
      var CUSTOM_OBJ_DATA_CLASS = 0;
      var CUSTOM_OBJ_DATA_CONTENT = 1;
      var DICT_JSON_LAYOUT = 0;
      var ARRAY_ITEM_VALUES = 0;
      var Refs = {
        EACH_RECORD_LENGTH: 3,
        OWNER_OFFSET: 0,
        KEY_OFFSET: 1,
        TARGET_OFFSET: 2
      };
      var File = {
        Version: 0,
        Context: 0,
        SharedUuids: 1,
        SharedStrings: 2,
        SharedClasses: 3,
        SharedMasks: 4,
        Instances: 5,
        InstanceTypes: 6,
        Refs: 7,
        DependObjs: 8,
        DependKeys: 9,
        DependUuidIndices: 10,
        ARRAY_LENGTH: 11
      };
      var PACKED_SECTIONS = File.Instances;
      var Details = exports('e0', function () {
        function Details() {
          this.uuidObjList = null;
          this.uuidPropList = null;
          this.uuidList = null;
          this.uuidTypeList = [];
        }
        var _proto = Details.prototype;
        _proto.init = function init(data) {
          if (data) {
            this.uuidObjList = data[File.DependObjs];
            this.uuidPropList = data[File.DependKeys];
            this.uuidList = data[File.DependUuidIndices];
          } else {
            var used = this.uuidList;
            if (!used) {
              this.uuidList = [];
              this.uuidObjList = [];
              this.uuidPropList = [];
              this.uuidTypeList = [];
            }
          }
        };
        _proto.reset = function reset() {
          {
            var used = this.uuidList;
            if (used) {
              this.uuidList.length = 0;
              this.uuidObjList.length = 0;
              this.uuidPropList.length = 0;
              this.uuidTypeList.length = 0;
            }
          }
        };
        _proto.push = function push(obj, propName, uuid, type) {
          this.uuidObjList.push(obj);
          this.uuidPropList.push(propName);
          this.uuidList.push(uuid);
          this.uuidTypeList.push(type || '');
        };
        return Details;
      }());
      Details.pool = new Pool$1(function (obj) {
        obj.reset();
      }, 5);
      Details.pool.get = function () {
        return this._get() || new Details();
      };
      function dereference(refs, instances, strings) {
        var dataLength = refs.length - 1;
        var i = 0;
        var instanceOffset = refs[dataLength] * Refs.EACH_RECORD_LENGTH;
        for (; i < instanceOffset; i += Refs.EACH_RECORD_LENGTH) {
          var _owner = refs[i];
          var target = instances[refs[i + Refs.TARGET_OFFSET]];
          var keyIndex = refs[i + Refs.KEY_OFFSET];
          if (keyIndex >= 0) {
            _owner[strings[keyIndex]] = target;
          } else {
            _owner[~keyIndex] = target;
          }
        }
        for (; i < dataLength; i += Refs.EACH_RECORD_LENGTH) {
          var _owner2 = instances[refs[i]];
          var _target = instances[refs[i + Refs.TARGET_OFFSET]];
          var _keyIndex = refs[i + Refs.KEY_OFFSET];
          if (_keyIndex >= 0) {
            _owner2[strings[_keyIndex]] = _target;
          } else {
            _owner2[~_keyIndex] = _target;
          }
        }
      }
      function deserializeCCObject(data, objectData) {
        var mask = data[File.SharedMasks][objectData[OBJ_DATA_MASK]];
        var clazz = mask[MASK_CLASS];
        var ctor = clazz[CLASS_TYPE];
        var obj = new ctor();
        var keys = clazz[CLASS_KEYS];
        var classTypeOffset = clazz[CLASS_PROP_TYPE_OFFSET];
        var maskTypeOffset = mask[mask.length - 1];
        var i = MASK_CLASS + 1;
        for (; i < maskTypeOffset; ++i) {
          var _key = keys[mask[i]];
          obj[_key] = objectData[i];
        }
        for (; i < objectData.length; ++i) {
          var _key2 = keys[mask[i]];
          var type = clazz[mask[i] + classTypeOffset];
          var op = ASSIGNMENTS[type];
          op(data, obj, _key2, objectData[i]);
        }
        return obj;
      }
      function deserializeCustomCCObject(data, ctor, value) {
        var obj = new ctor();
        if (obj._deserialize) {
          obj._deserialize(value, data[File.Context]);
        } else {
          errorID(5303, getClassName(ctor));
        }
        return obj;
      }
      function assignSimple(data, owner, key, value) {
        owner[key] = value;
      }
      function assignInstanceRef(data, owner, key, value) {
        if (value >= 0) {
          owner[key] = data[File.Instances][value];
        } else {
          data[File.Refs][~value * Refs.EACH_RECORD_LENGTH] = owner;
        }
      }
      function genArrayParser(parser) {
        return function (data, owner, key, value) {
          for (var i = 0; i < value.length; ++i) {
            parser(data, value, i, value[i]);
          }
          owner[key] = value;
        };
      }
      function parseAssetRefByInnerObj(data, owner, key, value) {
        owner[key] = null;
        data[File.DependObjs][value] = owner;
      }
      function parseClass(data, owner, key, value) {
        owner[key] = deserializeCCObject(data, value);
      }
      function parseCustomClass(data, owner, key, value) {
        var ctor = data[File.SharedClasses][value[CUSTOM_OBJ_DATA_CLASS]];
        owner[key] = deserializeCustomCCObject(data, ctor, value[CUSTOM_OBJ_DATA_CONTENT]);
      }
      function parseTRS(data, owner, key, value) {
        var typedArray = owner[key];
        typedArray.set(value);
      }
      function parseDict(data, owner, key, value) {
        var dict = value[DICT_JSON_LAYOUT];
        owner[key] = dict;
        for (var i = DICT_JSON_LAYOUT + 1; i < value.length; i += 3) {
          var subKey = value[i];
          var subType = value[i + 1];
          var subValue = value[i + 2];
          var op = ASSIGNMENTS[subType];
          op(data, dict, subKey, subValue);
        }
      }
      function parseArray(data, owner, key, value) {
        var array = value[ARRAY_ITEM_VALUES];
        for (var i = 0; i < array.length; ++i) {
          var subValue = array[i];
          var type = value[i + 1];
          if (type !== DataTypeID.SimpleType) {
            var op = ASSIGNMENTS[type];
            op(data, array, i, subValue);
          }
        }
        owner[key] = array;
      }
      var ASSIGNMENTS = new Array(DataTypeID.ARRAY_LENGTH);
      ASSIGNMENTS[DataTypeID.SimpleType] = assignSimple;
      ASSIGNMENTS[DataTypeID.InstanceRef] = assignInstanceRef;
      ASSIGNMENTS[DataTypeID.Array_InstanceRef] = genArrayParser(assignInstanceRef);
      ASSIGNMENTS[DataTypeID.Array_AssetRefByInnerObj] = genArrayParser(parseAssetRefByInnerObj);
      ASSIGNMENTS[DataTypeID.Class] = parseClass;
      ASSIGNMENTS[DataTypeID.ValueTypeCreated] = deserializeBuiltinValueTypeInto;
      ASSIGNMENTS[DataTypeID.AssetRefByInnerObj] = parseAssetRefByInnerObj;
      ASSIGNMENTS[DataTypeID.TRS] = parseTRS;
      ASSIGNMENTS[DataTypeID.ValueType] = deserializeBuiltinValueType;
      ASSIGNMENTS[DataTypeID.Array_Class] = genArrayParser(parseClass);
      ASSIGNMENTS[DataTypeID.CustomizedClass] = parseCustomClass;
      ASSIGNMENTS[DataTypeID.Dict] = parseDict;
      ASSIGNMENTS[DataTypeID.Array] = parseArray;
      function parseInstances(data) {
        var instances = data[File.Instances];
        var instanceTypes = data[File.InstanceTypes];
        var instanceTypesLen = instanceTypes === EMPTY_PLACEHOLDER ? 0 : instanceTypes.length;
        var rootIndex = instances[instances.length - 1];
        var normalObjectCount = instances.length - instanceTypesLen;
        if (typeof rootIndex !== 'number') {
          rootIndex = 0;
        } else {
          if (rootIndex < 0) {
            rootIndex = ~rootIndex;
          }
          --normalObjectCount;
        }
        var insIndex = 0;
        for (; insIndex < normalObjectCount; ++insIndex) {
          instances[insIndex] = deserializeCCObject(data, instances[insIndex]);
        }
        var classes = data[File.SharedClasses];
        for (var typeIndex = 0; typeIndex < instanceTypesLen; ++typeIndex, ++insIndex) {
          var type = instanceTypes[typeIndex];
          var eachData = instances[insIndex];
          if (type >= 0) {
            var ctor = classes[type];
            instances[insIndex] = deserializeCustomCCObject(data, ctor, eachData);
          } else {
            type = ~type;
            var op = ASSIGNMENTS[type];
            op(data, instances, insIndex, eachData);
          }
        }
        return rootIndex;
      }
      function getMissingClass(hasCustomFinder, type, reportMissingClass) {
        if (!hasCustomFinder) {
          reportMissingClass(type);
        }
        return Object;
      }
      function doLookupClass(classFinder, type, container, index, silent, hasCustomFinder, reportMissingClass) {
        var klass = classFinder(type);
        if (!klass) {
          if (silent) {
            container[index] = function (c, i, t) {
              return function proxy() {
                var actualClass = classFinder(t) || getMissingClass(hasCustomFinder, t, reportMissingClass);
                c[i] = actualClass;
                return new actualClass();
              };
            }(container, index, type);
            return;
          } else {
            klass = getMissingClass(hasCustomFinder, type, reportMissingClass);
          }
        }
        container[index] = klass;
      }
      function lookupClasses(data, silent, customFinder, reportMissingClass) {
        var classFinder = customFinder || getClassById;
        var classes = data[File.SharedClasses];
        for (var i = 0; i < classes.length; ++i) {
          var klassLayout = classes[i];
          if (typeof klassLayout !== 'string') {
            {
              if (typeof klassLayout[CLASS_TYPE] === 'function') {
                throw new Error('Can not deserialize the same JSON data again.');
              }
            }
            var type = klassLayout[CLASS_TYPE];
            doLookupClass(classFinder, type, klassLayout, CLASS_TYPE, silent, customFinder, reportMissingClass);
          } else {
            doLookupClass(classFinder, klassLayout, classes, i, silent, customFinder, reportMissingClass);
          }
        }
      }
      function cacheMasks(data) {
        var masks = data[File.SharedMasks];
        if (masks) {
          var classes = data[File.SharedClasses];
          for (var i = 0; i < masks.length; ++i) {
            var mask = masks[i];
            mask[MASK_CLASS] = classes[mask[MASK_CLASS]];
          }
        }
      }
      function parseResult(data) {
        var instances = data[File.Instances];
        var sharedStrings = data[File.SharedStrings];
        var dependSharedUuids = data[File.SharedUuids];
        var dependObjs = data[File.DependObjs];
        var dependKeys = data[File.DependKeys];
        var dependUuids = data[File.DependUuidIndices];
        for (var i = 0; i < dependObjs.length; ++i) {
          var obj = dependObjs[i];
          if (typeof obj === 'number') {
            dependObjs[i] = instances[obj];
          }
          var _key3 = dependKeys[i];
          if (typeof _key3 === 'number') {
            if (_key3 >= 0) {
              _key3 = sharedStrings[_key3];
            } else {
              _key3 = ~_key3;
            }
            dependKeys[i] = _key3;
          }
          var _uuid2 = dependUuids[i];
          if (typeof _uuid2 === 'number') {
            dependUuids[i] = dependSharedUuids[_uuid2];
          }
        }
      }
      function isCompiledJson(json) {
        if (Array.isArray(json)) {
          var _version = json[0];
          return typeof _version === 'number' || _version instanceof FileInfo;
        } else {
          return false;
        }
      }
      function initializeDeserializationContext(data, details, options) {
        var _options;
        details.init(data);
        (_options = options) !== null && _options !== void 0 ? _options : options = {};
        var version = data[File.Version];
        var preprocessed = false;
        if (typeof version === 'object') {
          preprocessed = version.preprocessed;
          version = version.version;
        }
        if (version < SUPPORT_MIN_FORMAT_VERSION) {
          throw new Error(getError(5304, version));
        }
        var context = options;
        context._version = version;
        context.result = details;
        data[File.Context] = context;
        if (!preprocessed) {
          var _options$reportMissin;
          lookupClasses(data, false, options.classFinder, (_options$reportMissin = options.reportMissingClass) !== null && _options$reportMissin !== void 0 ? _options$reportMissin : deserialize.reportMissingClass);
          cacheMasks(data);
        }
      }
      function deserialize(data, details, options) {
        if (typeof data === 'string') {
          data = JSON.parse(data);
        }
        var isBorrowedDetails = false;
        if (!details) {
          var borrowedDetails = Details.pool.get();
          assertIsTrue(borrowedDetails, "Can not allocate deserialization details");
          details = borrowedDetails;
          isBorrowedDetails = true;
        }
        var res;
        if (!isCompiledJson(data)) {
          res = deserializeDynamic(data, details, options);
        } else {
          initializeDeserializationContext(data, details, options);
          var runtimeData = data;
          legacyCC.game._isCloning = true;
          var instances = runtimeData[File.Instances];
          var rootIndex = parseInstances(runtimeData);
          legacyCC.game._isCloning = false;
          if (runtimeData[File.Refs]) {
            dereference(runtimeData[File.Refs], instances, runtimeData[File.SharedStrings]);
          }
          parseResult(runtimeData);
          res = instances[rootIndex];
        }
        if (isBorrowedDetails) {
          Details.pool.put(details);
        }
        return res;
      }
      deserialize.Details = Details;
      deserialize.reportMissingClass = reportMissingClass;
      var FileInfo = function FileInfo(version) {
        this.preprocessed = true;
        this.version = version;
      };
      function unpackJSONs(data, classFinder, reportMissingClass) {
        if (data[File.Version] < SUPPORT_MIN_FORMAT_VERSION) {
          throw new Error(getError(5304, data[File.Version]));
        }
        lookupClasses(data, true, classFinder, reportMissingClass !== null && reportMissingClass !== void 0 ? reportMissingClass : deserialize.reportMissingClass);
        cacheMasks(data);
        var version = new FileInfo(data[File.Version]);
        var sharedUuids = data[File.SharedUuids];
        var sharedStrings = data[File.SharedStrings];
        var sharedClasses = data[File.SharedClasses];
        var sharedMasks = data[File.SharedMasks];
        var sections = data[PACKED_SECTIONS];
        for (var i = 0; i < sections.length; ++i) {
          var section = sections[i];
          section.unshift(version, sharedUuids, sharedStrings, sharedClasses, sharedMasks);
        }
        return sections;
      }
      function packCustomObjData(type, data, hasNativeDep) {
        return [SUPPORT_MIN_FORMAT_VERSION, EMPTY_PLACEHOLDER, EMPTY_PLACEHOLDER, [type], EMPTY_PLACEHOLDER, hasNativeDep ? [data, ~0] : [data], [0], EMPTY_PLACEHOLDER, [], [], []];
      }
      function hasNativeDep(data) {
        var instances = data[File.Instances];
        var rootInfo = instances[instances.length - 1];
        if (typeof rootInfo !== 'number') {
          return false;
        } else {
          return rootInfo < 0;
        }
      }
      function getDependUuidList(json) {
        var sharedUuids = json[File.SharedUuids];
        return json[File.DependUuidIndices].map(function (index) {
          return sharedUuids[index];
        });
      }
      function parseUuidDependencies(serialized) {
        {
          return getDependUuidList(serialized);
        }
      }
      legacyCC.deserialize = deserialize;

      var dependMap = new WeakMap();
      var nativeDependMap = new WeakSet();
      var onLoadedInvokedMap = new WeakSet();

      function deserializeAsset(json, options) {
        var classFinder;
        {
          classFinder = MissingScript.safeFindClass;
        }
        var tdInfo = Details.pool.get();
        var asset;
        try {
          asset = deserialize(json, tdInfo, {
            classFinder: classFinder,
            customEnv: options
          });
        } catch (e) {
          error(e);
          Details.pool.put(tdInfo);
          throw e;
        }
        asset._uuid = options.__uuid__ || '';
        var uuidList = tdInfo.uuidList;
        var objList = tdInfo.uuidObjList;
        var propList = tdInfo.uuidPropList;
        var typeList = tdInfo.uuidTypeList || [];
        var depends = [];
        for (var i = 0; i < uuidList.length; i++) {
          var dependUuid = uuidList[i];
          depends[i] = {
            uuid: decodeUuid(dependUuid),
            owner: objList[i],
            prop: propList[i],
            type: getClassById(typeList[i])
          };
        }
        dependMap.set(asset, depends);
        if (asset._native) {
          nativeDependMap.add(asset);
        }
        Details.pool.put(tdInfo);
        return asset;
      }

      var DependUtil = function () {
        function DependUtil() {
          this._depends = new Cache();
        }
        var _proto = DependUtil.prototype;
        _proto.init = function init() {
          this._depends.clear();
        };
        _proto.getNativeDep = function getNativeDep(uuid) {
          var depend = this._depends.get(uuid);
          if (depend && depend.nativeDep) {
            return _extends({}, depend.nativeDep);
          }
          return null;
        };
        _proto.getDeps = function getDeps(uuid) {
          if (this._depends.has(uuid)) {
            return this._depends.get(uuid).deps;
          }
          return [];
        };
        _proto.getDepsRecursively = function getDepsRecursively(uuid) {
          var exclude = Object.create(null);
          var depends = [];
          this._descend(uuid, exclude, depends);
          return depends;
        };
        _proto.remove = function remove(uuid) {
          this._depends.remove(uuid);
        };
        _proto.parse = function parse(uuid, json) {
          var out = null;
          if (Array.isArray(json) || json.__type__ || json instanceof CCON) {
            if (this._depends.has(uuid)) {
              return this._depends.get(uuid);
            }
            if (Array.isArray(json) && (!hasNativeDep(json))) {
              out = {
                deps: this._parseDepsFromJson(json)
              };
            } else {
              try {
                var asset = deserializeAsset(json, {
                  __uuid__: uuid
                });
                out = this._parseDepsFromAsset(asset);
                if (out.nativeDep) {
                  out.nativeDep.uuid = uuid;
                }
                parsed.add(uuid + "@import", asset);
              } catch (e) {
                files.remove(uuid + "@import");
                out = {
                  deps: []
                };
              }
            }
          } else {
            if (this._depends.has(uuid)) {
              out = this._depends.get(uuid);
              if (out.parsedFromExistAsset) {
                return out;
              }
            }
            out = this._parseDepsFromAsset(json);
          }
          this._depends.add(uuid, out);
          return out;
        };
        _proto._parseDepsFromAsset = function _parseDepsFromAsset(asset) {
          var out = {
            deps: [],
            parsedFromExistAsset: true
          };
          var deps = dependMap.get(asset);
          assertIsNonNullable(deps);
          for (var i = 0, l = deps.length; i < l; i++) {
            out.deps.push(deps[i].uuid);
          }
          if (nativeDependMap.has(asset)) {
            out.nativeDep = asset._nativeDep;
          }
          return out;
        };
        _proto._parseDepsFromJson = function _parseDepsFromJson(json) {
          var depends = parseUuidDependencies(json);
          depends.forEach(function (uuid, index) {
            return depends[index] = decodeUuid(uuid);
          });
          return depends;
        };
        _proto._descend = function _descend(uuid, exclude, depends) {
          var deps = this.getDeps(uuid);
          for (var i = 0; i < deps.length; i++) {
            var depend = deps[i];
            if (!exclude[depend]) {
              exclude[depend] = true;
              depends.push(depend);
              this._descend(depend, exclude, depends);
            }
          }
        };
        _createClass(DependUtil, null, [{
          key: "instance",
          get: function get() {
            if (!this._instance) {
              this._instance = new DependUtil();
            }
            return this._instance;
          }
        }]);
        return DependUtil;
      }();
      DependUtil._instance = void 0;
      var dependUtil = DependUtil.instance;

      var _dec$2X, _class$2U;
      var _regions = [new BufferTextureCopy()];
      function getMipLevel(width, height) {
        var size = Math.max(width, height);
        var level = 0;
        while (size) {
          size >>= 1;
          level++;
        }
        return level;
      }
      function isPOT(n) {
        return n && (n & n - 1) === 0;
      }
      function canGenerateMipmap(device, w, h) {
        var needCheckPOT = device.gfxAPI === API.WEBGL;
        if (needCheckPOT) {
          return isPOT(w) && isPOT(h);
        }
        return true;
      }
      var SimpleTexture = (_dec$2X = ccclass$n('cc.SimpleTexture'), _dec$2X(_class$2U = function (_TextureBase) {
        _inheritsLoose(SimpleTexture, _TextureBase);
        function SimpleTexture() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _TextureBase.call.apply(_TextureBase, [this].concat(args)) || this;
          _this._gfxTexture = null;
          _this._gfxTextureView = null;
          _this._mipmapLevel = 1;
          _this._textureWidth = 0;
          _this._textureHeight = 0;
          _this._baseLevel = 0;
          _this._maxLevel = 1000;
          return _this;
        }
        var _proto = SimpleTexture.prototype;
        _proto.getGFXTexture = function getGFXTexture() {
          return this._gfxTextureView;
        };
        _proto.destroy = function destroy() {
          this._tryDestroyTextureView();
          this._tryDestroyTexture();
          return _TextureBase.prototype.destroy.call(this);
        };
        _proto.updateImage = function updateImage() {
          this.updateMipmaps(0);
        };
        _proto.updateMipmaps = function updateMipmaps(firstLevel, count) {
        };
        _proto.uploadData = function uploadData(source, level, arrayIndex) {
          if (level === void 0) {
            level = 0;
          }
          if (arrayIndex === void 0) {
            arrayIndex = 0;
          }
          if (!this._gfxTexture || this._mipmapLevel <= level) {
            return;
          }
          var gfxDevice = this._getGFXDevice();
          if (!gfxDevice) {
            return;
          }
          var region = _regions[0];
          region.texExtent.width = this._textureWidth >> level;
          region.texExtent.height = this._textureHeight >> level;
          region.texSubres.mipLevel = level;
          region.texSubres.baseArrayLayer = arrayIndex;
          if (ArrayBuffer.isView(source)) {
            gfxDevice.copyBuffersToTexture([source], this._gfxTexture, _regions);
          } else {
            gfxDevice.copyTexImagesToTexture([source], this._gfxTexture, _regions);
          }
        };
        _proto._assignImage = function _assignImage(image, level, arrayIndex) {
          var data = image.data;
          if (!data) {
            return;
          }
          this.uploadData(data, level, arrayIndex);
          this._checkTextureLoaded();
          if (macro.CLEANUP_IMAGE_CACHE) {
            var deps = dependUtil.getDeps(this._uuid);
            var index = deps.indexOf(image._uuid);
            if (index !== -1) {
              fastRemoveAt$2(deps, index);
              image.decRef();
            }
          }
        };
        _proto._checkTextureLoaded = function _checkTextureLoaded() {
          this._textureReady();
        };
        _proto._textureReady = function _textureReady() {
          this.loaded = true;
          this.emit('load');
        };
        _proto._setMipmapLevel = function _setMipmapLevel(value) {
          this._mipmapLevel = value < 1 ? 1 : value;
        };
        _proto._setMipRange = function _setMipRange(baseLevel, maxLevel) {
          this._baseLevel = baseLevel < 1 ? 0 : baseLevel;
          this._maxLevel = maxLevel < 1 ? 0 : maxLevel;
        };
        _proto.setMipRange = function setMipRange(baseLevel, maxLevel) {
          assertID(baseLevel <= maxLevel, 3124);
          this._setMipRange(baseLevel, maxLevel);
          var device = this._getGFXDevice();
          if (!device) {
            return;
          }
          var textureView = this._createTextureView(device);
          this._tryDestroyTextureView();
          this._gfxTextureView = textureView;
        };
        _proto._getGfxTextureCreateInfo = function _getGfxTextureCreateInfo(presumed) {
          return null;
        };
        _proto._getGfxTextureViewCreateInfo = function _getGfxTextureViewCreateInfo(presumed) {
          return null;
        };
        _proto._tryReset = function _tryReset() {
          this._tryDestroyTextureView();
          this._tryDestroyTexture();
          if (this._mipmapLevel === 0) {
            return;
          }
          var device = this._getGFXDevice();
          if (!device) {
            return;
          }
          this._createTexture(device);
          this._gfxTextureView = this._createTextureView(device);
        };
        _proto.isUsingOfflineMipmaps = function isUsingOfflineMipmaps() {
          return false;
        };
        _proto._createTexture = function _createTexture(device) {
          if (this._width === 0 || this._height === 0) {
            return;
          }
          var flags = TextureFlagBit.NONE;
          if (this._mipFilter !== Filter.NONE && canGenerateMipmap(device, this._width, this._height)) {
            this._mipmapLevel = getMipLevel(this._width, this._height);
            if (!this.isUsingOfflineMipmaps() && !this.isCompressed) {
              flags = TextureFlagBit.GEN_MIPMAP;
            }
          }
          var textureCreateInfo = this._getGfxTextureCreateInfo({
            usage: TextureUsageBit.SAMPLED | TextureUsageBit.TRANSFER_DST | TextureUsageBit.COLOR_ATTACHMENT,
            format: this._getGFXFormat(),
            levelCount: this._mipmapLevel,
            flags: flags
          });
          if (!textureCreateInfo) {
            return;
          }
          var texture = device.createTexture(textureCreateInfo);
          this._textureWidth = textureCreateInfo.width;
          this._textureHeight = textureCreateInfo.height;
          this._gfxTexture = texture;
        };
        _proto._createTextureView = function _createTextureView(device) {
          if (!this._gfxTexture) {
            return null;
          }
          var maxLevel = this._maxLevel < this._mipmapLevel ? this._maxLevel : this._mipmapLevel - 1;
          var textureViewCreateInfo = this._getGfxTextureViewCreateInfo({
            texture: this._gfxTexture,
            format: this._getGFXFormat(),
            baseLevel: this._baseLevel,
            levelCount: maxLevel - this._baseLevel + 1
          });
          if (!textureViewCreateInfo) {
            return null;
          }
          return device.createTexture(textureViewCreateInfo);
        };
        _proto._tryDestroyTexture = function _tryDestroyTexture() {
          if (this._gfxTexture) {
            this._gfxTexture.destroy();
            this._gfxTexture = null;
          }
        };
        _proto._tryDestroyTextureView = function _tryDestroyTextureView() {
          if (this._gfxTextureView) {
            this._gfxTextureView.destroy();
            this._gfxTextureView = null;
          }
        };
        _createClass(SimpleTexture, [{
          key: "mipmapLevel",
          get: function get() {
            return this._mipmapLevel;
          }
        }]);
        return SimpleTexture;
      }(TextureBase)) || _class$2U);
      legacyCC.SimpleTexture = SimpleTexture;

      var _dec$2W, _dec2$24, _class$2T, _class2$2D, _initializer$2l;
      var Texture2D = exports('e9', (_dec$2W = ccclass$n('cc.Texture2D'), _dec2$24 = type$7([ImageAsset]), _dec$2W(_class$2T = (_class2$2D = function (_SimpleTexture) {
        _inheritsLoose(Texture2D, _SimpleTexture);
        function Texture2D() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _SimpleTexture.call.apply(_SimpleTexture, [this].concat(args)) || this;
          _this._mipmaps = _initializer$2l && _initializer$2l();
          _this._generatedMipmaps = [];
          return _this;
        }
        var _proto = Texture2D.prototype;
        _proto._setMipmapParams = function _setMipmapParams(value) {
          var _this2 = this;
          this._generatedMipmaps = value;
          this._setMipmapLevel(this._generatedMipmaps.length);
          if (this._generatedMipmaps.length > 0) {
            var imageAsset = this._generatedMipmaps[0];
            this.reset({
              width: imageAsset.width,
              height: imageAsset.height,
              format: imageAsset.format,
              mipmapLevel: this._generatedMipmaps.length,
              baseLevel: this._baseLevel,
              maxLevel: this._maxLevel
            });
            this._generatedMipmaps.forEach(function (mipmap, level) {
              _this2._assignImage(mipmap, level);
            });
          } else {
            this.reset({
              width: 0,
              height: 0,
              mipmapLevel: this._generatedMipmaps.length,
              baseLevel: this._baseLevel,
              maxLevel: this._maxLevel
            });
          }
        };
        _proto.initialize = function initialize() {
          this.mipmaps = this._mipmaps;
        };
        _proto.onLoaded = function onLoaded() {
          this.initialize();
        };
        _proto.reset = function reset(info) {
          this._width = info.width;
          this._height = info.height;
          this._setGFXFormat(info.format);
          var mipLevels = info.mipmapLevel === undefined ? 1 : info.mipmapLevel;
          this._setMipmapLevel(mipLevels);
          var minLod = info.baseLevel === undefined ? 0 : info.baseLevel;
          var maxLod = info.maxLevel === undefined ? 1000 : info.maxLevel;
          this._setMipRange(minLod, maxLod);
          this._tryReset();
        };
        _proto.create = function create(width, height, format, mipmapLevel, baseLevel, maxLevel) {
          if (format === void 0) {
            format = PixelFormat.RGBA8888;
          }
          if (mipmapLevel === void 0) {
            mipmapLevel = 1;
          }
          if (baseLevel === void 0) {
            baseLevel = 0;
          }
          if (maxLevel === void 0) {
            maxLevel = 1000;
          }
          this.reset({
            width: width,
            height: height,
            format: format,
            mipmapLevel: mipmapLevel,
            baseLevel: baseLevel,
            maxLevel: maxLevel
          });
        };
        _proto.toString = function toString() {
          return this._mipmaps.length !== 0 ? this._mipmaps[0].url : '';
        };
        _proto.updateMipmaps = function updateMipmaps(firstLevel, count) {
          if (firstLevel === void 0) {
            firstLevel = 0;
          }
          if (firstLevel >= this._generatedMipmaps.length) {
            return;
          }
          var nUpdate = Math.min(count === undefined ? this._generatedMipmaps.length : count, this._generatedMipmaps.length - firstLevel);
          for (var i = 0; i < nUpdate; ++i) {
            var level = firstLevel + i;
            this._assignImage(this._generatedMipmaps[level], level);
          }
        };
        _proto.getHtmlElementObj = function getHtmlElementObj() {
          return this._mipmaps[0] && this._mipmaps[0].data instanceof HTMLElement ? this._mipmaps[0].data : null;
        };
        _proto.destroy = function destroy() {
          this._mipmaps = [];
          this._generatedMipmaps = [];
          return _SimpleTexture.prototype.destroy.call(this);
        };
        _proto.description = function description() {
          var url = this._mipmaps[0] ? this._mipmaps[0].url : '';
          return "<cc.Texture2D | Name = " + url + " | Dimension = " + this.width + " x " + this.height + ">";
        };
        _proto.releaseTexture = function releaseTexture() {
          this.destroy();
        };
        _proto._serialize = function _serialize(ctxForExporting) {
          return null;
        };
        _proto._deserialize = function _deserialize(serializedData, handle) {
          var data = serializedData;
          _SimpleTexture.prototype._deserialize.call(this, data.base, handle);
          this._mipmaps = new Array(data.mipmaps.length);
          for (var i = 0; i < data.mipmaps.length; ++i) {
            this._mipmaps[i] = new ImageAsset();
            if (!data.mipmaps[i]) {
              continue;
            }
            var mipmapUUID = data.mipmaps[i];
            handle.result.push(this._mipmaps, "" + i, mipmapUUID, getClassId(ImageAsset));
          }
        };
        _proto._getGfxTextureCreateInfo = function _getGfxTextureCreateInfo(presumed) {
          var texInfo = new TextureInfo(TextureType.TEX2D);
          texInfo.width = this._width;
          texInfo.height = this._height;
          Object.assign(texInfo, presumed);
          return texInfo;
        };
        _proto._getGfxTextureViewCreateInfo = function _getGfxTextureViewCreateInfo(presumed) {
          var texViewInfo = new TextureViewInfo();
          texViewInfo.type = TextureType.TEX2D;
          Object.assign(texViewInfo, presumed);
          return texViewInfo;
        };
        _proto.initDefault = function initDefault(uuid) {
          _SimpleTexture.prototype.initDefault.call(this, uuid);
          var imageAsset = new ImageAsset();
          imageAsset.initDefault();
          this.image = imageAsset;
        };
        _proto.validate = function validate() {
          return this.mipmaps && this.mipmaps.length !== 0;
        };
        _createClass(Texture2D, [{
          key: "mipmaps",
          get: function get() {
            return this._mipmaps;
          },
          set: function set(value) {
            this._mipmaps = value;
            var mipmaps = [];
            if (value.length === 1) {
              var image = value[0];
              mipmaps.push.apply(mipmaps, image.extractMipmaps());
            } else if (value.length > 1) {
              for (var i = 0; i < value.length; ++i) {
                var _image = value[i];
                mipmaps.push(_image.extractMipmap0());
              }
            }
            this._setMipmapParams(mipmaps);
          }
        }, {
          key: "image",
          get: function get() {
            return this._mipmaps.length === 0 ? null : this._mipmaps[0];
          },
          set: function set(value) {
            this.mipmaps = value ? [value] : [];
          }
        }]);
        return Texture2D;
      }(SimpleTexture), (_initializer$2l = applyDecoratedInitializer(_class2$2D.prototype, "_mipmaps", [_dec2$24], function () {
        return [];
      })), _class2$2D)) || _class$2T));
      legacyCC.Texture2D = Texture2D;

      var space$1 = 2;
      var Atlas = function () {
        function Atlas(width, height) {
          this._texture = void 0;
          this._width = void 0;
          this._height = void 0;
          this._x = void 0;
          this._y = void 0;
          this._nexty = void 0;
          this._innerTextureInfos = {};
          this._innerSpriteFrames = void 0;
          this._count = void 0;
          var texture = new DynamicAtlasTexture();
          texture.initWithSize(width, height);
          this._texture = texture;
          this._width = width;
          this._height = height;
          this._x = space$1;
          this._y = space$1;
          this._nexty = space$1;
          this._innerTextureInfos = {};
          this._innerSpriteFrames = [];
          this._count = 0;
        }
        var _proto = Atlas.prototype;
        _proto.insertSpriteFrame = function insertSpriteFrame(spriteFrame) {
          var rect = spriteFrame.rect;
          var texture = spriteFrame.texture;
          var info = this._innerTextureInfos[texture.getId()];
          var sx = rect.x;
          var sy = rect.y;
          if (info) {
            sx += info.x;
            sy += info.y;
          } else {
            var width = texture.width;
            var height = texture.height;
            if (this._x + width + space$1 > this._width) {
              this._x = space$1;
              this._y = this._nexty;
            }
            if (this._y + height + space$1 > this._nexty) {
              this._nexty = this._y + height + space$1;
            }
            if (this._nexty > this._height) {
              return null;
            }
            if (legacyCC.internal.dynamicAtlasManager.textureBleeding) {
              if (width <= 8 || height <= 8) {
                this._texture.drawTextureAt(texture.image, this._x - 1, this._y - 1);
                this._texture.drawTextureAt(texture.image, this._x - 1, this._y + 1);
                this._texture.drawTextureAt(texture.image, this._x + 1, this._y - 1);
                this._texture.drawTextureAt(texture.image, this._x + 1, this._y + 1);
              }
              this._texture.drawTextureAt(texture.image, this._x - 1, this._y);
              this._texture.drawTextureAt(texture.image, this._x + 1, this._y);
              this._texture.drawTextureAt(texture.image, this._x, this._y - 1);
              this._texture.drawTextureAt(texture.image, this._x, this._y + 1);
            }
            this._texture.drawTextureAt(texture.image, this._x, this._y);
            this._innerTextureInfos[texture.getId()] = {
              x: this._x,
              y: this._y,
              texture: texture
            };
            this._count++;
            sx += this._x;
            sy += this._y;
            this._x += width + space$1;
          }
          var frame = {
            x: sx,
            y: sy,
            texture: this._texture
          };
          this._innerSpriteFrames.push(spriteFrame);
          return frame;
        };
        _proto.deleteInnerTexture = function deleteInnerTexture(texture) {
          if (texture && this._innerTextureInfos[texture.getId()]) {
            delete this._innerTextureInfos[texture.getId()];
            this._count--;
          }
        };
        _proto.isEmpty = function isEmpty() {
          return this._count <= 0;
        };
        _proto.reset = function reset() {
          this._x = space$1;
          this._y = space$1;
          this._nexty = space$1;
          var frames = this._innerSpriteFrames;
          for (var i = 0, l = frames.length; i < l; i++) {
            var frame = frames[i];
            if (!frame.isValid) {
              continue;
            }
            frame._resetDynamicAtlasFrame();
          }
          this._innerSpriteFrames.length = 0;
          this._innerTextureInfos = {};
        };
        _proto.destroy = function destroy() {
          this.reset();
          this._texture.destroy();
        };
        return Atlas;
      }();
      var DynamicAtlasTexture = function (_Texture2D) {
        _inheritsLoose(DynamicAtlasTexture, _Texture2D);
        function DynamicAtlasTexture() {
          return _Texture2D.apply(this, arguments) || this;
        }
        var _proto2 = DynamicAtlasTexture.prototype;
        _proto2.initWithSize = function initWithSize(width, height, format) {
          if (format === void 0) {
            format = PixelFormat.RGBA8888;
          }
          this.reset({
            width: width,
            height: height,
            format: format
          });
        };
        _proto2.drawTextureAt = function drawTextureAt(image, x, y) {
          var gfxTexture = this.getGFXTexture();
          if (!image || !gfxTexture) {
            return;
          }
          var gfxDevice = this._getGFXDevice();
          if (!gfxDevice) {
            console.warn('Unable to get device');
            return;
          }
          var region = new BufferTextureCopy();
          region.texOffset.x = x;
          region.texOffset.y = y;
          region.texExtent.width = image.width;
          region.texExtent.height = image.height;
          gfxDevice.copyTexImagesToTexture([image.data], gfxTexture, [region]);
        };
        return DynamicAtlasTexture;
      }(Texture2D);

      var layerList = {
        NONE: 0,
        IGNORE_RAYCAST: 1 << 20,
        GIZMOS: 1 << 21,
        EDITOR: 1 << 22,
        UI_3D: 1 << 23,
        SCENE_GIZMO: 1 << 24,
        UI_2D: 1 << 25,
        PROFILER: 1 << 28,
        DEFAULT: 1 << 30,
        ALL: 0xffffffff
      };
      var Layers = exports('dw', function () {
        function Layers() {}
        Layers.init = function init() {
          var userLayers = settings.querySettings(Settings.Category.ENGINE, 'customLayers');
          if (!userLayers) return;
          for (var i = 0; i < userLayers.length; i++) {
            var layer = userLayers[i];
            Layers.addLayer(layer.name, layer.bit);
          }
        };
        Layers.makeMaskInclude = function makeMaskInclude(includes) {
          var mask = 0;
          for (var _iterator = _createForOfIteratorHelperLoose(includes), _step; !(_step = _iterator()).done;) {
            var inc = _step.value;
            mask |= inc;
          }
          return mask;
        };
        Layers.makeMaskExclude = function makeMaskExclude(excludes) {
          return ~Layers.makeMaskInclude(excludes);
        };
        Layers.addLayer = function addLayer(name, bitNum) {
          if (bitNum === undefined) {
            console.warn('bitNum can\'t be undefined');
            return;
          }
          if (bitNum > 19 || bitNum < 0) {
            console.warn('maximum layers reached.');
            return;
          }
          var val = 1 << bitNum;
          assertIsTrue(!Layers.Enum[name], getError(2104, name));
          Layers.Enum[name] = val;
          value(Layers.Enum, String(val), name);
          Layers.BitMask[name] = val;
          value(Layers.BitMask, String(val), name);
          BitMask.update(Layers.BitMask);
          Enum.update(Layers.Enum);
        };
        Layers.deleteLayer = function deleteLayer(bitNum) {
          if (bitNum > 19 || bitNum < 0) {
            console.warn('do not change buildin layers.');
            return;
          }
          var val = 1 << bitNum;
          delete Layers.Enum[Layers.Enum[val]];
          delete Layers.Enum[val];
          delete Layers.BitMask[Layers.BitMask[val]];
          delete Layers.BitMask[val];
          BitMask.update(Layers.BitMask);
          Enum.update(Layers.Enum);
        };
        Layers.nameToLayer = function nameToLayer(name) {
          if (name === undefined) {
            console.warn('name can\'t be undefined');
            return -1;
          }
          return log2(Layers.Enum[name]);
        };
        Layers.layerToName = function layerToName(bitNum) {
          if (bitNum > 31 || bitNum < 0) {
            console.warn('Unable to access unknown layer.');
            return '';
          }
          return Layers.Enum[1 << bitNum];
        };
        return Layers;
      }());
      Layers.Enum = Enum(layerList);
      Layers.BitMask = BitMask(_extends({}, layerList));
      legacyCC.Layers = Layers;

      var _class$2S, _class2$2C, _class3$M, _class4$w, _class5$x, _class6$8, _class7$c, _class8$b, _class10$7, _class11$7, _class12$2, _class13$6, _class14$6, _class15$1;
      var PIPELINE_FLOW_MAIN = 'MainFlow';
      var PIPELINE_FLOW_FORWARD = 'ForwardFlow';
      var PIPELINE_FLOW_SHADOW = 'ShadowFlow';
      var PIPELINE_FLOW_SMAA = 'SMAAFlow';
      var PIPELINE_FLOW_TONEMAP = 'ToneMapFlow';
      var RenderPassStage;
      (function (RenderPassStage) {
        RenderPassStage[RenderPassStage["DEFAULT"] = 100] = "DEFAULT";
        RenderPassStage[RenderPassStage["UI"] = 200] = "UI";
      })(RenderPassStage || (RenderPassStage = {}));
      legacyCC.RenderPassStage = RenderPassStage;
      var RenderPriority;
      (function (RenderPriority) {
        RenderPriority[RenderPriority["MIN"] = 0] = "MIN";
        RenderPriority[RenderPriority["MAX"] = 255] = "MAX";
        RenderPriority[RenderPriority["DEFAULT"] = 128] = "DEFAULT";
      })(RenderPriority || (RenderPriority = {}));
      var globalDescriptorSetLayout = {
        bindings: [],
        layouts: {}
      };
      var localDescriptorSetLayout = {
        bindings: [],
        layouts: {}
      };
      var PipelineGlobalBindings;
      (function (PipelineGlobalBindings) {
        PipelineGlobalBindings[PipelineGlobalBindings["UBO_GLOBAL"] = 0] = "UBO_GLOBAL";
        PipelineGlobalBindings[PipelineGlobalBindings["UBO_CAMERA"] = 1] = "UBO_CAMERA";
        PipelineGlobalBindings[PipelineGlobalBindings["UBO_SHADOW"] = 2] = "UBO_SHADOW";
        PipelineGlobalBindings[PipelineGlobalBindings["UBO_CSM"] = 3] = "UBO_CSM";
        PipelineGlobalBindings[PipelineGlobalBindings["SAMPLER_SHADOWMAP"] = 4] = "SAMPLER_SHADOWMAP";
        PipelineGlobalBindings[PipelineGlobalBindings["SAMPLER_ENVIRONMENT"] = 5] = "SAMPLER_ENVIRONMENT";
        PipelineGlobalBindings[PipelineGlobalBindings["SAMPLER_SPOT_SHADOW_MAP"] = 6] = "SAMPLER_SPOT_SHADOW_MAP";
        PipelineGlobalBindings[PipelineGlobalBindings["SAMPLER_DIFFUSEMAP"] = 7] = "SAMPLER_DIFFUSEMAP";
        PipelineGlobalBindings[PipelineGlobalBindings["COUNT"] = 8] = "COUNT";
      })(PipelineGlobalBindings || (PipelineGlobalBindings = {}));
      var GLOBAL_UBO_COUNT = PipelineGlobalBindings.SAMPLER_SHADOWMAP;
      var GLOBAL_SAMPLER_COUNT = PipelineGlobalBindings.COUNT - GLOBAL_UBO_COUNT;
      var ModelLocalBindings;
      (function (ModelLocalBindings) {
        ModelLocalBindings[ModelLocalBindings["UBO_LOCAL"] = 0] = "UBO_LOCAL";
        ModelLocalBindings[ModelLocalBindings["UBO_FORWARD_LIGHTS"] = 1] = "UBO_FORWARD_LIGHTS";
        ModelLocalBindings[ModelLocalBindings["UBO_SKINNING_ANIMATION"] = 2] = "UBO_SKINNING_ANIMATION";
        ModelLocalBindings[ModelLocalBindings["UBO_SKINNING_TEXTURE"] = 3] = "UBO_SKINNING_TEXTURE";
        ModelLocalBindings[ModelLocalBindings["UBO_MORPH"] = 4] = "UBO_MORPH";
        ModelLocalBindings[ModelLocalBindings["UBO_UI_LOCAL"] = 5] = "UBO_UI_LOCAL";
        ModelLocalBindings[ModelLocalBindings["UBO_SH"] = 6] = "UBO_SH";
        ModelLocalBindings[ModelLocalBindings["SAMPLER_JOINTS"] = 7] = "SAMPLER_JOINTS";
        ModelLocalBindings[ModelLocalBindings["SAMPLER_MORPH_POSITION"] = 8] = "SAMPLER_MORPH_POSITION";
        ModelLocalBindings[ModelLocalBindings["SAMPLER_MORPH_NORMAL"] = 9] = "SAMPLER_MORPH_NORMAL";
        ModelLocalBindings[ModelLocalBindings["SAMPLER_MORPH_TANGENT"] = 10] = "SAMPLER_MORPH_TANGENT";
        ModelLocalBindings[ModelLocalBindings["SAMPLER_LIGHTMAP"] = 11] = "SAMPLER_LIGHTMAP";
        ModelLocalBindings[ModelLocalBindings["SAMPLER_SPRITE"] = 12] = "SAMPLER_SPRITE";
        ModelLocalBindings[ModelLocalBindings["SAMPLER_REFLECTION"] = 13] = "SAMPLER_REFLECTION";
        ModelLocalBindings[ModelLocalBindings["STORAGE_REFLECTION"] = 14] = "STORAGE_REFLECTION";
        ModelLocalBindings[ModelLocalBindings["SAMPLER_REFLECTION_PROBE_CUBE"] = 15] = "SAMPLER_REFLECTION_PROBE_CUBE";
        ModelLocalBindings[ModelLocalBindings["SAMPLER_REFLECTION_PROBE_PLANAR"] = 16] = "SAMPLER_REFLECTION_PROBE_PLANAR";
        ModelLocalBindings[ModelLocalBindings["SAMPLER_REFLECTION_PROBE_DATA_MAP"] = 17] = "SAMPLER_REFLECTION_PROBE_DATA_MAP";
        ModelLocalBindings[ModelLocalBindings["SAMPLER_REFLECTION_PROBE_BLEND_CUBE"] = 18] = "SAMPLER_REFLECTION_PROBE_BLEND_CUBE";
        ModelLocalBindings[ModelLocalBindings["COUNT"] = 19] = "COUNT";
      })(ModelLocalBindings || (ModelLocalBindings = {}));
      var LOCAL_UBO_COUNT = ModelLocalBindings.SAMPLER_JOINTS;
      var LOCAL_SAMPLER_COUNT = ModelLocalBindings.STORAGE_REFLECTION - LOCAL_UBO_COUNT;
      var LOCAL_STORAGE_IMAGE_COUNT = ModelLocalBindings.COUNT - LOCAL_UBO_COUNT - LOCAL_SAMPLER_COUNT;
      var SetIndex;
      (function (SetIndex) {
        SetIndex[SetIndex["GLOBAL"] = 0] = "GLOBAL";
        SetIndex[SetIndex["MATERIAL"] = 1] = "MATERIAL";
        SetIndex[SetIndex["LOCAL"] = 2] = "LOCAL";
        SetIndex[SetIndex["COUNT"] = 3] = "COUNT";
      })(SetIndex || (SetIndex = {}));
      var bindingMappingInfo = new BindingMappingInfo([GLOBAL_UBO_COUNT, 0, LOCAL_UBO_COUNT, 0], [GLOBAL_SAMPLER_COUNT, 0, LOCAL_SAMPLER_COUNT, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, LOCAL_STORAGE_IMAGE_COUNT, 0], [0, 0, 0, 0], [0, 2, 1, 3]);
      var UBOGlobal = function UBOGlobal() {};
      _class$2S = UBOGlobal;
      UBOGlobal.TIME_OFFSET = 0;
      UBOGlobal.SCREEN_SIZE_OFFSET = _class$2S.TIME_OFFSET + 4;
      UBOGlobal.NATIVE_SIZE_OFFSET = _class$2S.SCREEN_SIZE_OFFSET + 4;
      UBOGlobal.PROBE_INFO_OFFSET = _class$2S.NATIVE_SIZE_OFFSET + 4;
      UBOGlobal.DEBUG_VIEW_MODE_OFFSET = _class$2S.PROBE_INFO_OFFSET + 4;
      UBOGlobal.COUNT = _class$2S.DEBUG_VIEW_MODE_OFFSET + 4;
      UBOGlobal.SIZE = _class$2S.COUNT * 4;
      UBOGlobal.NAME = 'CCGlobal';
      UBOGlobal.BINDING = PipelineGlobalBindings.UBO_GLOBAL;
      UBOGlobal.DESCRIPTOR = new DescriptorSetLayoutBinding(_class$2S.BINDING, DescriptorType.UNIFORM_BUFFER, 1, ShaderStageFlagBit.ALL);
      UBOGlobal.LAYOUT = new UniformBlock(SetIndex.GLOBAL, _class$2S.BINDING, _class$2S.NAME, [new Uniform('cc_time', Type$1.FLOAT4, 1), new Uniform('cc_screenSize', Type$1.FLOAT4, 1), new Uniform('cc_nativeSize', Type$1.FLOAT4, 1), new Uniform('cc_probeInfo', Type$1.FLOAT4, 1), new Uniform('cc_debug_view_mode', Type$1.FLOAT4, 1)], 1);
      globalDescriptorSetLayout.layouts[UBOGlobal.NAME] = UBOGlobal.LAYOUT;
      globalDescriptorSetLayout.bindings[UBOGlobal.BINDING] = UBOGlobal.DESCRIPTOR;
      var UBOCamera = function UBOCamera() {};
      _class2$2C = UBOCamera;
      UBOCamera.MAT_VIEW_OFFSET = 0;
      UBOCamera.MAT_VIEW_INV_OFFSET = _class2$2C.MAT_VIEW_OFFSET + 16;
      UBOCamera.MAT_PROJ_OFFSET = _class2$2C.MAT_VIEW_INV_OFFSET + 16;
      UBOCamera.MAT_PROJ_INV_OFFSET = _class2$2C.MAT_PROJ_OFFSET + 16;
      UBOCamera.MAT_VIEW_PROJ_OFFSET = _class2$2C.MAT_PROJ_INV_OFFSET + 16;
      UBOCamera.MAT_VIEW_PROJ_INV_OFFSET = _class2$2C.MAT_VIEW_PROJ_OFFSET + 16;
      UBOCamera.CAMERA_POS_OFFSET = _class2$2C.MAT_VIEW_PROJ_INV_OFFSET + 16;
      UBOCamera.SURFACE_TRANSFORM_OFFSET = _class2$2C.CAMERA_POS_OFFSET + 4;
      UBOCamera.SCREEN_SCALE_OFFSET = _class2$2C.SURFACE_TRANSFORM_OFFSET + 4;
      UBOCamera.EXPOSURE_OFFSET = _class2$2C.SCREEN_SCALE_OFFSET + 4;
      UBOCamera.MAIN_LIT_DIR_OFFSET = _class2$2C.EXPOSURE_OFFSET + 4;
      UBOCamera.MAIN_LIT_COLOR_OFFSET = _class2$2C.MAIN_LIT_DIR_OFFSET + 4;
      UBOCamera.AMBIENT_SKY_OFFSET = _class2$2C.MAIN_LIT_COLOR_OFFSET + 4;
      UBOCamera.AMBIENT_GROUND_OFFSET = _class2$2C.AMBIENT_SKY_OFFSET + 4;
      UBOCamera.GLOBAL_FOG_COLOR_OFFSET = _class2$2C.AMBIENT_GROUND_OFFSET + 4;
      UBOCamera.GLOBAL_FOG_BASE_OFFSET = _class2$2C.GLOBAL_FOG_COLOR_OFFSET + 4;
      UBOCamera.GLOBAL_FOG_ADD_OFFSET = _class2$2C.GLOBAL_FOG_BASE_OFFSET + 4;
      UBOCamera.NEAR_FAR_OFFSET = _class2$2C.GLOBAL_FOG_ADD_OFFSET + 4;
      UBOCamera.VIEW_PORT_OFFSET = _class2$2C.NEAR_FAR_OFFSET + 4;
      UBOCamera.COUNT = _class2$2C.VIEW_PORT_OFFSET + 4;
      UBOCamera.SIZE = _class2$2C.COUNT * 4;
      UBOCamera.NAME = 'CCCamera';
      UBOCamera.BINDING = PipelineGlobalBindings.UBO_CAMERA;
      UBOCamera.DESCRIPTOR = new DescriptorSetLayoutBinding(_class2$2C.BINDING, DescriptorType.UNIFORM_BUFFER, 1, ShaderStageFlagBit.ALL);
      UBOCamera.LAYOUT = new UniformBlock(SetIndex.GLOBAL, _class2$2C.BINDING, _class2$2C.NAME, [new Uniform('cc_matView', Type$1.MAT4, 1), new Uniform('cc_matViewInv', Type$1.MAT4, 1), new Uniform('cc_matProj', Type$1.MAT4, 1), new Uniform('cc_matProjInv', Type$1.MAT4, 1), new Uniform('cc_matViewProj', Type$1.MAT4, 1), new Uniform('cc_matViewProjInv', Type$1.MAT4, 1), new Uniform('cc_cameraPos', Type$1.FLOAT4, 1), new Uniform('cc_surfaceTransform', Type$1.FLOAT4, 1), new Uniform('cc_screenScale', Type$1.FLOAT4, 1), new Uniform('cc_exposure', Type$1.FLOAT4, 1), new Uniform('cc_mainLitDir', Type$1.FLOAT4, 1), new Uniform('cc_mainLitColor', Type$1.FLOAT4, 1), new Uniform('cc_ambientSky', Type$1.FLOAT4, 1), new Uniform('cc_ambientGround', Type$1.FLOAT4, 1), new Uniform('cc_fogColor', Type$1.FLOAT4, 1), new Uniform('cc_fogBase', Type$1.FLOAT4, 1), new Uniform('cc_fogAdd', Type$1.FLOAT4, 1), new Uniform('cc_nearFar', Type$1.FLOAT4, 1), new Uniform('cc_viewPort', Type$1.FLOAT4, 1)], 1);
      globalDescriptorSetLayout.layouts[UBOCamera.NAME] = UBOCamera.LAYOUT;
      globalDescriptorSetLayout.bindings[UBOCamera.BINDING] = UBOCamera.DESCRIPTOR;
      var UBOShadow = function UBOShadow() {};
      _class3$M = UBOShadow;
      UBOShadow.MAT_LIGHT_VIEW_OFFSET = 0;
      UBOShadow.MAT_LIGHT_VIEW_PROJ_OFFSET = _class3$M.MAT_LIGHT_VIEW_OFFSET + 16;
      UBOShadow.SHADOW_INV_PROJ_DEPTH_INFO_OFFSET = _class3$M.MAT_LIGHT_VIEW_PROJ_OFFSET + 16;
      UBOShadow.SHADOW_PROJ_DEPTH_INFO_OFFSET = _class3$M.SHADOW_INV_PROJ_DEPTH_INFO_OFFSET + 4;
      UBOShadow.SHADOW_PROJ_INFO_OFFSET = _class3$M.SHADOW_PROJ_DEPTH_INFO_OFFSET + 4;
      UBOShadow.SHADOW_NEAR_FAR_LINEAR_SATURATION_INFO_OFFSET = _class3$M.SHADOW_PROJ_INFO_OFFSET + 4;
      UBOShadow.SHADOW_WIDTH_HEIGHT_PCF_BIAS_INFO_OFFSET = _class3$M.SHADOW_NEAR_FAR_LINEAR_SATURATION_INFO_OFFSET + 4;
      UBOShadow.SHADOW_LIGHT_PACKING_NBIAS_NULL_INFO_OFFSET = _class3$M.SHADOW_WIDTH_HEIGHT_PCF_BIAS_INFO_OFFSET + 4;
      UBOShadow.SHADOW_COLOR_OFFSET = _class3$M.SHADOW_LIGHT_PACKING_NBIAS_NULL_INFO_OFFSET + 4;
      UBOShadow.PLANAR_NORMAL_DISTANCE_INFO_OFFSET = _class3$M.SHADOW_COLOR_OFFSET + 4;
      UBOShadow.COUNT = _class3$M.PLANAR_NORMAL_DISTANCE_INFO_OFFSET + 4;
      UBOShadow.SIZE = _class3$M.COUNT * 4;
      UBOShadow.NAME = 'CCShadow';
      UBOShadow.BINDING = PipelineGlobalBindings.UBO_SHADOW;
      UBOShadow.DESCRIPTOR = new DescriptorSetLayoutBinding(_class3$M.BINDING, DescriptorType.UNIFORM_BUFFER, 1, ShaderStageFlagBit.ALL);
      UBOShadow.LAYOUT = new UniformBlock(SetIndex.GLOBAL, _class3$M.BINDING, _class3$M.NAME, [new Uniform('cc_matLightView', Type$1.MAT4, 1), new Uniform('cc_matLightViewProj', Type$1.MAT4, 1), new Uniform('cc_shadowInvProjDepthInfo', Type$1.FLOAT4, 1), new Uniform('cc_shadowProjDepthInfo', Type$1.FLOAT4, 1), new Uniform('cc_shadowProjInfo', Type$1.FLOAT4, 1), new Uniform('cc_shadowNFLSInfo', Type$1.FLOAT4, 1), new Uniform('cc_shadowWHPBInfo', Type$1.FLOAT4, 1), new Uniform('cc_shadowLPNNInfo', Type$1.FLOAT4, 1), new Uniform('cc_shadowColor', Type$1.FLOAT4, 1), new Uniform('cc_planarNDInfo', Type$1.FLOAT4, 1)], 1);
      globalDescriptorSetLayout.layouts[UBOShadow.NAME] = UBOShadow.LAYOUT;
      globalDescriptorSetLayout.bindings[UBOShadow.BINDING] = UBOShadow.DESCRIPTOR;
      var UBOCSM = function UBOCSM() {};
      _class4$w = UBOCSM;
      UBOCSM.CSM_LEVEL_COUNT = 4;
      UBOCSM.CSM_VIEW_DIR_0_OFFSET = 0;
      UBOCSM.CSM_VIEW_DIR_1_OFFSET = _class4$w.CSM_VIEW_DIR_0_OFFSET + 4 * _class4$w.CSM_LEVEL_COUNT;
      UBOCSM.CSM_VIEW_DIR_2_OFFSET = _class4$w.CSM_VIEW_DIR_1_OFFSET + 4 * _class4$w.CSM_LEVEL_COUNT;
      UBOCSM.CSM_ATLAS_OFFSET = _class4$w.CSM_VIEW_DIR_2_OFFSET + 4 * _class4$w.CSM_LEVEL_COUNT;
      UBOCSM.MAT_CSM_VIEW_PROJ_OFFSET = _class4$w.CSM_ATLAS_OFFSET + 4 * _class4$w.CSM_LEVEL_COUNT;
      UBOCSM.CSM_PROJ_DEPTH_INFO_OFFSET = _class4$w.MAT_CSM_VIEW_PROJ_OFFSET + 16 * _class4$w.CSM_LEVEL_COUNT;
      UBOCSM.CSM_PROJ_INFO_OFFSET = _class4$w.CSM_PROJ_DEPTH_INFO_OFFSET + 4 * _class4$w.CSM_LEVEL_COUNT;
      UBOCSM.CSM_SPLITS_INFO_OFFSET = _class4$w.CSM_PROJ_INFO_OFFSET + 4 * _class4$w.CSM_LEVEL_COUNT;
      UBOCSM.COUNT = _class4$w.CSM_SPLITS_INFO_OFFSET + 4;
      UBOCSM.SIZE = _class4$w.COUNT * 4;
      UBOCSM.NAME = 'CCCSM';
      UBOCSM.BINDING = PipelineGlobalBindings.UBO_CSM;
      UBOCSM.DESCRIPTOR = new DescriptorSetLayoutBinding(_class4$w.BINDING, DescriptorType.UNIFORM_BUFFER, 1, ShaderStageFlagBit.FRAGMENT);
      UBOCSM.LAYOUT = new UniformBlock(SetIndex.GLOBAL, _class4$w.BINDING, _class4$w.NAME, [new Uniform('cc_csmViewDir0', Type$1.FLOAT4, _class4$w.CSM_LEVEL_COUNT), new Uniform('cc_csmViewDir1', Type$1.FLOAT4, _class4$w.CSM_LEVEL_COUNT), new Uniform('cc_csmViewDir2', Type$1.FLOAT4, _class4$w.CSM_LEVEL_COUNT), new Uniform('cc_csmAtlas', Type$1.FLOAT4, _class4$w.CSM_LEVEL_COUNT), new Uniform('cc_matCSMViewProj', Type$1.MAT4, _class4$w.CSM_LEVEL_COUNT), new Uniform('cc_csmProjDepthInfo', Type$1.FLOAT4, _class4$w.CSM_LEVEL_COUNT), new Uniform('cc_csmProjInfo', Type$1.FLOAT4, _class4$w.CSM_LEVEL_COUNT), new Uniform('cc_csmSplitsInfo', Type$1.FLOAT4, 1)], 1);
      globalDescriptorSetLayout.layouts[UBOCSM.NAME] = UBOCSM.LAYOUT;
      globalDescriptorSetLayout.bindings[UBOCSM.BINDING] = UBOCSM.DESCRIPTOR;
      var UNIFORM_SHADOWMAP_NAME = 'cc_shadowMap';
      var UNIFORM_SHADOWMAP_BINDING = PipelineGlobalBindings.SAMPLER_SHADOWMAP;
      var UNIFORM_SHADOWMAP_DESCRIPTOR = new DescriptorSetLayoutBinding(UNIFORM_SHADOWMAP_BINDING, DescriptorType.SAMPLER_TEXTURE, 1, ShaderStageFlagBit.FRAGMENT);
      var UNIFORM_SHADOWMAP_LAYOUT = new UniformSamplerTexture(SetIndex.GLOBAL, UNIFORM_SHADOWMAP_BINDING, UNIFORM_SHADOWMAP_NAME, Type$1.SAMPLER2D, 1);
      globalDescriptorSetLayout.layouts[UNIFORM_SHADOWMAP_NAME] = UNIFORM_SHADOWMAP_LAYOUT;
      globalDescriptorSetLayout.bindings[UNIFORM_SHADOWMAP_BINDING] = UNIFORM_SHADOWMAP_DESCRIPTOR;
      var UNIFORM_ENVIRONMENT_NAME = 'cc_environment';
      var UNIFORM_ENVIRONMENT_BINDING = PipelineGlobalBindings.SAMPLER_ENVIRONMENT;
      var UNIFORM_ENVIRONMENT_DESCRIPTOR = new DescriptorSetLayoutBinding(UNIFORM_ENVIRONMENT_BINDING, DescriptorType.SAMPLER_TEXTURE, 1, ShaderStageFlagBit.FRAGMENT);
      var UNIFORM_ENVIRONMENT_LAYOUT = new UniformSamplerTexture(SetIndex.GLOBAL, UNIFORM_ENVIRONMENT_BINDING, UNIFORM_ENVIRONMENT_NAME, Type$1.SAMPLER_CUBE, 1);
      globalDescriptorSetLayout.layouts[UNIFORM_ENVIRONMENT_NAME] = UNIFORM_ENVIRONMENT_LAYOUT;
      globalDescriptorSetLayout.bindings[UNIFORM_ENVIRONMENT_BINDING] = UNIFORM_ENVIRONMENT_DESCRIPTOR;
      var UNIFORM_DIFFUSEMAP_NAME = 'cc_diffuseMap';
      var UNIFORM_DIFFUSEMAP_BINDING = PipelineGlobalBindings.SAMPLER_DIFFUSEMAP;
      var UNIFORM_DIFFUSEMAP_DESCRIPTOR = new DescriptorSetLayoutBinding(UNIFORM_DIFFUSEMAP_BINDING, DescriptorType.SAMPLER_TEXTURE, 1, ShaderStageFlagBit.FRAGMENT);
      var UNIFORM_DIFFUSEMAP_LAYOUT = new UniformSamplerTexture(SetIndex.GLOBAL, UNIFORM_DIFFUSEMAP_BINDING, UNIFORM_DIFFUSEMAP_NAME, Type$1.SAMPLER_CUBE, 1);
      globalDescriptorSetLayout.layouts[UNIFORM_DIFFUSEMAP_NAME] = UNIFORM_DIFFUSEMAP_LAYOUT;
      globalDescriptorSetLayout.bindings[UNIFORM_DIFFUSEMAP_BINDING] = UNIFORM_DIFFUSEMAP_DESCRIPTOR;
      var UNIFORM_SPOT_SHADOW_MAP_TEXTURE_NAME = 'cc_spotShadowMap';
      var UNIFORM_SPOT_SHADOW_MAP_TEXTURE_BINDING = PipelineGlobalBindings.SAMPLER_SPOT_SHADOW_MAP;
      var UNIFORM_SPOT_SHADOW_MAP_TEXTURE_DESCRIPTOR = new DescriptorSetLayoutBinding(UNIFORM_SPOT_SHADOW_MAP_TEXTURE_BINDING, DescriptorType.SAMPLER_TEXTURE, 1, ShaderStageFlagBit.FRAGMENT);
      var UNIFORM_SPOT_SHADOW_MAP_TEXTURE_LAYOUT = new UniformSamplerTexture(SetIndex.GLOBAL, UNIFORM_SPOT_SHADOW_MAP_TEXTURE_BINDING, UNIFORM_SPOT_SHADOW_MAP_TEXTURE_NAME, Type$1.SAMPLER2D, 1);
      globalDescriptorSetLayout.layouts[UNIFORM_SPOT_SHADOW_MAP_TEXTURE_NAME] = UNIFORM_SPOT_SHADOW_MAP_TEXTURE_LAYOUT;
      globalDescriptorSetLayout.bindings[UNIFORM_SPOT_SHADOW_MAP_TEXTURE_BINDING] = UNIFORM_SPOT_SHADOW_MAP_TEXTURE_DESCRIPTOR;
      var UBOLocal = function UBOLocal() {};
      _class5$x = UBOLocal;
      UBOLocal.MAT_WORLD_OFFSET = 0;
      UBOLocal.MAT_WORLD_IT_OFFSET = _class5$x.MAT_WORLD_OFFSET + 16;
      UBOLocal.LIGHTINGMAP_UVPARAM = _class5$x.MAT_WORLD_IT_OFFSET + 16;
      UBOLocal.LOCAL_SHADOW_BIAS = _class5$x.LIGHTINGMAP_UVPARAM + 4;
      UBOLocal.REFLECTION_PROBE_DATA1 = _class5$x.LOCAL_SHADOW_BIAS + 4;
      UBOLocal.REFLECTION_PROBE_DATA2 = _class5$x.REFLECTION_PROBE_DATA1 + 4;
      UBOLocal.REFLECTION_PROBE_BLEND_DATA1 = _class5$x.REFLECTION_PROBE_DATA2 + 4;
      UBOLocal.REFLECTION_PROBE_BLEND_DATA2 = _class5$x.REFLECTION_PROBE_BLEND_DATA1 + 4;
      UBOLocal.COUNT = _class5$x.REFLECTION_PROBE_BLEND_DATA2 + 4;
      UBOLocal.SIZE = _class5$x.COUNT * 4;
      UBOLocal.NAME = 'CCLocal';
      UBOLocal.BINDING = ModelLocalBindings.UBO_LOCAL;
      UBOLocal.DESCRIPTOR = new DescriptorSetLayoutBinding(_class5$x.BINDING, DescriptorType.UNIFORM_BUFFER, 1, ShaderStageFlagBit.VERTEX | ShaderStageFlagBit.COMPUTE);
      UBOLocal.LAYOUT = new UniformBlock(SetIndex.LOCAL, _class5$x.BINDING, _class5$x.NAME, [new Uniform('cc_matWorld', Type$1.MAT4, 1), new Uniform('cc_matWorldIT', Type$1.MAT4, 1), new Uniform('cc_lightingMapUVParam', Type$1.FLOAT4, 1), new Uniform('cc_localShadowBias', Type$1.FLOAT4, 1), new Uniform('cc_reflectionProbeData1', Type$1.FLOAT4, 1), new Uniform('cc_reflectionProbeData2', Type$1.FLOAT4, 1), new Uniform('cc_reflectionProbeBlendData1', Type$1.FLOAT4, 1), new Uniform('cc_reflectionProbeBlendData2', Type$1.FLOAT4, 1)], 1);
      localDescriptorSetLayout.layouts[UBOLocal.NAME] = UBOLocal.LAYOUT;
      localDescriptorSetLayout.bindings[UBOLocal.BINDING] = UBOLocal.DESCRIPTOR;
      var UBOWorldBound = function UBOWorldBound() {};
      _class6$8 = UBOWorldBound;
      UBOWorldBound.WORLD_BOUND_CENTER = 0;
      UBOWorldBound.WORLD_BOUND_HALF_EXTENTS = _class6$8.WORLD_BOUND_CENTER + 4;
      UBOWorldBound.COUNT = _class6$8.WORLD_BOUND_HALF_EXTENTS + 4;
      UBOWorldBound.SIZE = _class6$8.COUNT * 4;
      UBOWorldBound.NAME = 'CCWorldBound';
      UBOWorldBound.BINDING = ModelLocalBindings.UBO_LOCAL;
      UBOWorldBound.DESCRIPTOR = new DescriptorSetLayoutBinding(_class6$8.BINDING, DescriptorType.UNIFORM_BUFFER, 1, ShaderStageFlagBit.VERTEX | ShaderStageFlagBit.COMPUTE);
      UBOWorldBound.LAYOUT = new UniformBlock(SetIndex.LOCAL, _class6$8.BINDING, _class6$8.NAME, [new Uniform('cc_worldBoundCenter', Type$1.FLOAT4, 1), new Uniform('cc_worldBoundHalfExtents', Type$1.FLOAT4, 1)], 1);
      localDescriptorSetLayout.layouts[UBOWorldBound.NAME] = UBOWorldBound.LAYOUT;
      localDescriptorSetLayout.bindings[UBOWorldBound.BINDING] = UBOWorldBound.DESCRIPTOR;
      var INST_MAT_WORLD = 'a_matWorld0';
      var INST_SH = 'a_sh_linear_const_r';
      var UBOLocalBatched = function UBOLocalBatched() {};
      _class7$c = UBOLocalBatched;
      UBOLocalBatched.BATCHING_COUNT = 10;
      UBOLocalBatched.MAT_WORLDS_OFFSET = 0;
      UBOLocalBatched.COUNT = 16 * _class7$c.BATCHING_COUNT;
      UBOLocalBatched.SIZE = _class7$c.COUNT * 4;
      UBOLocalBatched.NAME = 'CCLocalBatched';
      UBOLocalBatched.BINDING = ModelLocalBindings.UBO_LOCAL;
      UBOLocalBatched.DESCRIPTOR = new DescriptorSetLayoutBinding(_class7$c.BINDING, DescriptorType.UNIFORM_BUFFER, 1, ShaderStageFlagBit.VERTEX | ShaderStageFlagBit.COMPUTE);
      UBOLocalBatched.LAYOUT = new UniformBlock(SetIndex.LOCAL, _class7$c.BINDING, _class7$c.NAME, [new Uniform('cc_matWorlds', Type$1.MAT4, _class7$c.BATCHING_COUNT)], 1);
      localDescriptorSetLayout.layouts[UBOLocalBatched.NAME] = UBOLocalBatched.LAYOUT;
      localDescriptorSetLayout.bindings[UBOLocalBatched.BINDING] = UBOLocalBatched.DESCRIPTOR;
      var UBOForwardLight = function UBOForwardLight() {};
      _class8$b = UBOForwardLight;
      UBOForwardLight.LIGHTS_PER_PASS = 1;
      UBOForwardLight.LIGHT_POS_OFFSET = 0;
      UBOForwardLight.LIGHT_COLOR_OFFSET = _class8$b.LIGHT_POS_OFFSET + _class8$b.LIGHTS_PER_PASS * 4;
      UBOForwardLight.LIGHT_SIZE_RANGE_ANGLE_OFFSET = _class8$b.LIGHT_COLOR_OFFSET + _class8$b.LIGHTS_PER_PASS * 4;
      UBOForwardLight.LIGHT_DIR_OFFSET = _class8$b.LIGHT_SIZE_RANGE_ANGLE_OFFSET + _class8$b.LIGHTS_PER_PASS * 4;
      UBOForwardLight.LIGHT_BOUNDING_SIZE_VS_OFFSET = _class8$b.LIGHT_DIR_OFFSET + _class8$b.LIGHTS_PER_PASS * 4;
      UBOForwardLight.COUNT = _class8$b.LIGHT_BOUNDING_SIZE_VS_OFFSET + _class8$b.LIGHTS_PER_PASS * 4;
      UBOForwardLight.SIZE = _class8$b.COUNT * 4;
      UBOForwardLight.NAME = 'CCForwardLight';
      UBOForwardLight.BINDING = ModelLocalBindings.UBO_FORWARD_LIGHTS;
      UBOForwardLight.DESCRIPTOR = new DescriptorSetLayoutBinding(_class8$b.BINDING, DescriptorType.DYNAMIC_UNIFORM_BUFFER, 1, ShaderStageFlagBit.FRAGMENT);
      UBOForwardLight.LAYOUT = new UniformBlock(SetIndex.LOCAL, _class8$b.BINDING, _class8$b.NAME, [new Uniform('cc_lightPos', Type$1.FLOAT4, _class8$b.LIGHTS_PER_PASS), new Uniform('cc_lightColor', Type$1.FLOAT4, _class8$b.LIGHTS_PER_PASS), new Uniform('cc_lightSizeRangeAngle', Type$1.FLOAT4, _class8$b.LIGHTS_PER_PASS), new Uniform('cc_lightDir', Type$1.FLOAT4, _class8$b.LIGHTS_PER_PASS), new Uniform('cc_lightBoundingSizeVS', Type$1.FLOAT4, _class8$b.LIGHTS_PER_PASS)], 1);
      localDescriptorSetLayout.layouts[UBOForwardLight.NAME] = UBOForwardLight.LAYOUT;
      localDescriptorSetLayout.bindings[UBOForwardLight.BINDING] = UBOForwardLight.DESCRIPTOR;
      var UBODeferredLight = function UBODeferredLight() {};
      UBODeferredLight.LIGHTS_PER_PASS = 10;
      var JOINT_UNIFORM_CAPACITY = 30;
      var UBOSkinningTexture = function UBOSkinningTexture() {};
      _class10$7 = UBOSkinningTexture;
      UBOSkinningTexture.JOINTS_TEXTURE_INFO_OFFSET = 0;
      UBOSkinningTexture.COUNT = _class10$7.JOINTS_TEXTURE_INFO_OFFSET + 4;
      UBOSkinningTexture.SIZE = _class10$7.COUNT * 4;
      UBOSkinningTexture.NAME = 'CCSkinningTexture';
      UBOSkinningTexture.BINDING = ModelLocalBindings.UBO_SKINNING_TEXTURE;
      UBOSkinningTexture.DESCRIPTOR = new DescriptorSetLayoutBinding(_class10$7.BINDING, DescriptorType.UNIFORM_BUFFER, 1, ShaderStageFlagBit.VERTEX);
      UBOSkinningTexture.LAYOUT = new UniformBlock(SetIndex.LOCAL, _class10$7.BINDING, _class10$7.NAME, [new Uniform('cc_jointTextureInfo', Type$1.FLOAT4, 1)], 1);
      localDescriptorSetLayout.layouts[UBOSkinningTexture.NAME] = UBOSkinningTexture.LAYOUT;
      localDescriptorSetLayout.bindings[UBOSkinningTexture.BINDING] = UBOSkinningTexture.DESCRIPTOR;
      var UBOSkinningAnimation = function UBOSkinningAnimation() {};
      _class11$7 = UBOSkinningAnimation;
      UBOSkinningAnimation.JOINTS_ANIM_INFO_OFFSET = 0;
      UBOSkinningAnimation.COUNT = _class11$7.JOINTS_ANIM_INFO_OFFSET + 4;
      UBOSkinningAnimation.SIZE = _class11$7.COUNT * 4;
      UBOSkinningAnimation.NAME = 'CCSkinningAnimation';
      UBOSkinningAnimation.BINDING = ModelLocalBindings.UBO_SKINNING_ANIMATION;
      UBOSkinningAnimation.DESCRIPTOR = new DescriptorSetLayoutBinding(_class11$7.BINDING, DescriptorType.UNIFORM_BUFFER, 1, ShaderStageFlagBit.VERTEX);
      UBOSkinningAnimation.LAYOUT = new UniformBlock(SetIndex.LOCAL, _class11$7.BINDING, _class11$7.NAME, [new Uniform('cc_jointAnimInfo', Type$1.FLOAT4, 1)], 1);
      localDescriptorSetLayout.layouts[UBOSkinningAnimation.NAME] = UBOSkinningAnimation.LAYOUT;
      localDescriptorSetLayout.bindings[UBOSkinningAnimation.BINDING] = UBOSkinningAnimation.DESCRIPTOR;
      var INST_JOINT_ANIM_INFO = 'a_jointAnimInfo';
      var UBOSkinning = function () {
        function UBOSkinning() {}
        UBOSkinning.initLayout = function initLayout(capacity) {
          UBOSkinning._jointUniformCapacity = capacity;
          UBOSkinning._count = capacity * 12;
          UBOSkinning._size = UBOSkinning._count * 4;
          UBOSkinning.LAYOUT.members[0].count = capacity * 3;
        };
        _createClass(UBOSkinning, null, [{
          key: "JOINT_UNIFORM_CAPACITY",
          get: function get() {
            return UBOSkinning._jointUniformCapacity;
          }
        }, {
          key: "COUNT",
          get: function get() {
            return UBOSkinning._count;
          }
        }, {
          key: "SIZE",
          get: function get() {
            return UBOSkinning._size;
          }
        }]);
        return UBOSkinning;
      }();
      _class12$2 = UBOSkinning;
      UBOSkinning._jointUniformCapacity = 0;
      UBOSkinning._count = 0;
      UBOSkinning._size = 0;
      UBOSkinning.NAME = 'CCSkinning';
      UBOSkinning.BINDING = ModelLocalBindings.UBO_SKINNING_TEXTURE;
      UBOSkinning.DESCRIPTOR = new DescriptorSetLayoutBinding(_class12$2.BINDING, DescriptorType.UNIFORM_BUFFER, 1, ShaderStageFlagBit.VERTEX);
      UBOSkinning.LAYOUT = new UniformBlock(SetIndex.LOCAL, _class12$2.BINDING, _class12$2.NAME, [new Uniform('cc_joints', Type$1.FLOAT4, 1)], 1);
      function localDescriptorSetLayout_ResizeMaxJoints(maxCount) {
        UBOSkinning.initLayout(maxCount);
        localDescriptorSetLayout.layouts[UBOSkinning.NAME] = UBOSkinning.LAYOUT;
        localDescriptorSetLayout.bindings[UBOSkinning.BINDING] = UBOSkinning.DESCRIPTOR;
      }
      var UBOMorph = function UBOMorph() {};
      _class13$6 = UBOMorph;
      UBOMorph.MAX_MORPH_TARGET_COUNT = 60;
      UBOMorph.OFFSET_OF_WEIGHTS = 0;
      UBOMorph.OFFSET_OF_DISPLACEMENT_TEXTURE_WIDTH = 4 * _class13$6.MAX_MORPH_TARGET_COUNT;
      UBOMorph.OFFSET_OF_DISPLACEMENT_TEXTURE_HEIGHT = _class13$6.OFFSET_OF_DISPLACEMENT_TEXTURE_WIDTH + 4;
      UBOMorph.OFFSET_OF_VERTICES_COUNT = _class13$6.OFFSET_OF_DISPLACEMENT_TEXTURE_HEIGHT + 4;
      UBOMorph.COUNT_BASE_4_BYTES = 4 * Math.ceil(_class13$6.MAX_MORPH_TARGET_COUNT / 4) + 4;
      UBOMorph.SIZE = _class13$6.COUNT_BASE_4_BYTES * 4;
      UBOMorph.NAME = 'CCMorph';
      UBOMorph.BINDING = ModelLocalBindings.UBO_MORPH;
      UBOMorph.DESCRIPTOR = new DescriptorSetLayoutBinding(_class13$6.BINDING, DescriptorType.UNIFORM_BUFFER, 1, ShaderStageFlagBit.VERTEX);
      UBOMorph.LAYOUT = new UniformBlock(SetIndex.LOCAL, _class13$6.BINDING, _class13$6.NAME, [new Uniform('cc_displacementWeights', Type$1.FLOAT4, _class13$6.MAX_MORPH_TARGET_COUNT / 4), new Uniform('cc_displacementTextureInfo', Type$1.FLOAT4, 1)], 1);
      localDescriptorSetLayout.layouts[UBOMorph.NAME] = UBOMorph.LAYOUT;
      localDescriptorSetLayout.bindings[UBOMorph.BINDING] = UBOMorph.DESCRIPTOR;
      var UBOUILocal = function UBOUILocal() {};
      _class14$6 = UBOUILocal;
      UBOUILocal.NAME = 'CCUILocal';
      UBOUILocal.BINDING = ModelLocalBindings.UBO_UI_LOCAL;
      UBOUILocal.DESCRIPTOR = new DescriptorSetLayoutBinding(_class14$6.BINDING, DescriptorType.DYNAMIC_UNIFORM_BUFFER, 1, ShaderStageFlagBit.VERTEX);
      UBOUILocal.LAYOUT = new UniformBlock(SetIndex.LOCAL, _class14$6.BINDING, _class14$6.NAME, [new Uniform('cc_local_data', Type$1.FLOAT4, 1)], 1);
      localDescriptorSetLayout.layouts[UBOUILocal.NAME] = UBOUILocal.LAYOUT;
      localDescriptorSetLayout.bindings[UBOUILocal.BINDING] = UBOUILocal.DESCRIPTOR;
      var UBOSH = function UBOSH() {};
      _class15$1 = UBOSH;
      UBOSH.SH_LINEAR_CONST_R_OFFSET = 0;
      UBOSH.SH_LINEAR_CONST_G_OFFSET = _class15$1.SH_LINEAR_CONST_R_OFFSET + 4;
      UBOSH.SH_LINEAR_CONST_B_OFFSET = _class15$1.SH_LINEAR_CONST_G_OFFSET + 4;
      UBOSH.SH_QUADRATIC_R_OFFSET = _class15$1.SH_LINEAR_CONST_B_OFFSET + 4;
      UBOSH.SH_QUADRATIC_G_OFFSET = _class15$1.SH_QUADRATIC_R_OFFSET + 4;
      UBOSH.SH_QUADRATIC_B_OFFSET = _class15$1.SH_QUADRATIC_G_OFFSET + 4;
      UBOSH.SH_QUADRATIC_A_OFFSET = _class15$1.SH_QUADRATIC_B_OFFSET + 4;
      UBOSH.COUNT = _class15$1.SH_QUADRATIC_A_OFFSET + 4;
      UBOSH.SIZE = _class15$1.COUNT * 4;
      UBOSH.NAME = 'CCSH';
      UBOSH.BINDING = ModelLocalBindings.UBO_SH;
      UBOSH.DESCRIPTOR = new DescriptorSetLayoutBinding(_class15$1.BINDING, DescriptorType.UNIFORM_BUFFER, 1, ShaderStageFlagBit.FRAGMENT);
      UBOSH.LAYOUT = new UniformBlock(SetIndex.LOCAL, _class15$1.BINDING, _class15$1.NAME, [new Uniform('cc_sh_linear_const_r', Type$1.FLOAT4, 1), new Uniform('cc_sh_linear_const_g', Type$1.FLOAT4, 1), new Uniform('cc_sh_linear_const_b', Type$1.FLOAT4, 1), new Uniform('cc_sh_quadratic_r', Type$1.FLOAT4, 1), new Uniform('cc_sh_quadratic_g', Type$1.FLOAT4, 1), new Uniform('cc_sh_quadratic_b', Type$1.FLOAT4, 1), new Uniform('cc_sh_quadratic_a', Type$1.FLOAT4, 1)], 1);
      localDescriptorSetLayout.layouts[UBOSH.NAME] = UBOSH.LAYOUT;
      localDescriptorSetLayout.bindings[UBOSH.BINDING] = UBOSH.DESCRIPTOR;
      var UNIFORM_JOINT_TEXTURE_NAME = 'cc_jointTexture';
      var UNIFORM_JOINT_TEXTURE_BINDING = ModelLocalBindings.SAMPLER_JOINTS;
      var UNIFORM_JOINT_TEXTURE_DESCRIPTOR = new DescriptorSetLayoutBinding(UNIFORM_JOINT_TEXTURE_BINDING, DescriptorType.SAMPLER_TEXTURE, 1, ShaderStageFlagBit.VERTEX);
      var UNIFORM_JOINT_TEXTURE_LAYOUT = new UniformSamplerTexture(SetIndex.LOCAL, UNIFORM_JOINT_TEXTURE_BINDING, UNIFORM_JOINT_TEXTURE_NAME, Type$1.SAMPLER2D, 1);
      localDescriptorSetLayout.layouts[UNIFORM_JOINT_TEXTURE_NAME] = UNIFORM_JOINT_TEXTURE_LAYOUT;
      localDescriptorSetLayout.bindings[UNIFORM_JOINT_TEXTURE_BINDING] = UNIFORM_JOINT_TEXTURE_DESCRIPTOR;
      var UNIFORM_REALTIME_JOINT_TEXTURE_NAME = 'cc_realtimeJoint';
      var UNIFORM_REALTIME_JOINT_TEXTURE_BINDING = ModelLocalBindings.SAMPLER_JOINTS;
      var UNIFORM_REALTIME_JOINT_TEXTURE_DESCRIPTOR = new DescriptorSetLayoutBinding(UNIFORM_REALTIME_JOINT_TEXTURE_BINDING, DescriptorType.SAMPLER_TEXTURE, 1, ShaderStageFlagBit.VERTEX);
      var UNIFORM_REALTIME_JOINT_TEXTURE_LAYOUT = new UniformSamplerTexture(SetIndex.LOCAL, UNIFORM_REALTIME_JOINT_TEXTURE_BINDING, UNIFORM_REALTIME_JOINT_TEXTURE_NAME, Type$1.SAMPLER2D, 1);
      localDescriptorSetLayout.layouts[UNIFORM_REALTIME_JOINT_TEXTURE_NAME] = UNIFORM_REALTIME_JOINT_TEXTURE_LAYOUT;
      localDescriptorSetLayout.bindings[UNIFORM_REALTIME_JOINT_TEXTURE_BINDING] = UNIFORM_REALTIME_JOINT_TEXTURE_DESCRIPTOR;
      var UNIFORM_POSITION_MORPH_TEXTURE_NAME = 'cc_PositionDisplacements';
      var UNIFORM_POSITION_MORPH_TEXTURE_BINDING = ModelLocalBindings.SAMPLER_MORPH_POSITION;
      var UNIFORM_POSITION_MORPH_TEXTURE_DESCRIPTOR = new DescriptorSetLayoutBinding(UNIFORM_POSITION_MORPH_TEXTURE_BINDING, DescriptorType.SAMPLER_TEXTURE, 1, ShaderStageFlagBit.VERTEX);
      var UNIFORM_POSITION_MORPH_TEXTURE_LAYOUT = new UniformSamplerTexture(SetIndex.LOCAL, UNIFORM_POSITION_MORPH_TEXTURE_BINDING, UNIFORM_POSITION_MORPH_TEXTURE_NAME, Type$1.SAMPLER2D, 1);
      localDescriptorSetLayout.layouts[UNIFORM_POSITION_MORPH_TEXTURE_NAME] = UNIFORM_POSITION_MORPH_TEXTURE_LAYOUT;
      localDescriptorSetLayout.bindings[UNIFORM_POSITION_MORPH_TEXTURE_BINDING] = UNIFORM_POSITION_MORPH_TEXTURE_DESCRIPTOR;
      var UNIFORM_NORMAL_MORPH_TEXTURE_NAME = 'cc_NormalDisplacements';
      var UNIFORM_NORMAL_MORPH_TEXTURE_BINDING = ModelLocalBindings.SAMPLER_MORPH_NORMAL;
      var UNIFORM_NORMAL_MORPH_TEXTURE_DESCRIPTOR = new DescriptorSetLayoutBinding(UNIFORM_NORMAL_MORPH_TEXTURE_BINDING, DescriptorType.SAMPLER_TEXTURE, 1, ShaderStageFlagBit.VERTEX);
      var UNIFORM_NORMAL_MORPH_TEXTURE_LAYOUT = new UniformSamplerTexture(SetIndex.LOCAL, UNIFORM_NORMAL_MORPH_TEXTURE_BINDING, UNIFORM_NORMAL_MORPH_TEXTURE_NAME, Type$1.SAMPLER2D, 1);
      localDescriptorSetLayout.layouts[UNIFORM_NORMAL_MORPH_TEXTURE_NAME] = UNIFORM_NORMAL_MORPH_TEXTURE_LAYOUT;
      localDescriptorSetLayout.bindings[UNIFORM_NORMAL_MORPH_TEXTURE_BINDING] = UNIFORM_NORMAL_MORPH_TEXTURE_DESCRIPTOR;
      var UNIFORM_TANGENT_MORPH_TEXTURE_NAME = 'cc_TangentDisplacements';
      var UNIFORM_TANGENT_MORPH_TEXTURE_BINDING = ModelLocalBindings.SAMPLER_MORPH_TANGENT;
      var UNIFORM_TANGENT_MORPH_TEXTURE_DESCRIPTOR = new DescriptorSetLayoutBinding(UNIFORM_TANGENT_MORPH_TEXTURE_BINDING, DescriptorType.SAMPLER_TEXTURE, 1, ShaderStageFlagBit.VERTEX);
      var UNIFORM_TANGENT_MORPH_TEXTURE_LAYOUT = new UniformSamplerTexture(SetIndex.LOCAL, UNIFORM_TANGENT_MORPH_TEXTURE_BINDING, UNIFORM_TANGENT_MORPH_TEXTURE_NAME, Type$1.SAMPLER2D, 1);
      localDescriptorSetLayout.layouts[UNIFORM_TANGENT_MORPH_TEXTURE_NAME] = UNIFORM_TANGENT_MORPH_TEXTURE_LAYOUT;
      localDescriptorSetLayout.bindings[UNIFORM_TANGENT_MORPH_TEXTURE_BINDING] = UNIFORM_TANGENT_MORPH_TEXTURE_DESCRIPTOR;
      var UNIFORM_LIGHTMAP_TEXTURE_NAME = 'cc_lightingMap';
      var UNIFORM_LIGHTMAP_TEXTURE_BINDING = ModelLocalBindings.SAMPLER_LIGHTMAP;
      var UNIFORM_LIGHTMAP_TEXTURE_DESCRIPTOR = new DescriptorSetLayoutBinding(UNIFORM_LIGHTMAP_TEXTURE_BINDING, DescriptorType.SAMPLER_TEXTURE, 1, ShaderStageFlagBit.FRAGMENT);
      var UNIFORM_LIGHTMAP_TEXTURE_LAYOUT = new UniformSamplerTexture(SetIndex.LOCAL, UNIFORM_LIGHTMAP_TEXTURE_BINDING, UNIFORM_LIGHTMAP_TEXTURE_NAME, Type$1.SAMPLER2D, 1);
      localDescriptorSetLayout.layouts[UNIFORM_LIGHTMAP_TEXTURE_NAME] = UNIFORM_LIGHTMAP_TEXTURE_LAYOUT;
      localDescriptorSetLayout.bindings[UNIFORM_LIGHTMAP_TEXTURE_BINDING] = UNIFORM_LIGHTMAP_TEXTURE_DESCRIPTOR;
      var UNIFORM_SPRITE_TEXTURE_NAME = 'cc_spriteTexture';
      var UNIFORM_SPRITE_TEXTURE_BINDING = ModelLocalBindings.SAMPLER_SPRITE;
      var UNIFORM_SPRITE_TEXTURE_DESCRIPTOR = new DescriptorSetLayoutBinding(UNIFORM_SPRITE_TEXTURE_BINDING, DescriptorType.SAMPLER_TEXTURE, 1, ShaderStageFlagBit.FRAGMENT);
      var UNIFORM_SPRITE_TEXTURE_LAYOUT = new UniformSamplerTexture(SetIndex.LOCAL, UNIFORM_SPRITE_TEXTURE_BINDING, UNIFORM_SPRITE_TEXTURE_NAME, Type$1.SAMPLER2D, 1);
      localDescriptorSetLayout.layouts[UNIFORM_SPRITE_TEXTURE_NAME] = UNIFORM_SPRITE_TEXTURE_LAYOUT;
      localDescriptorSetLayout.bindings[UNIFORM_SPRITE_TEXTURE_BINDING] = UNIFORM_SPRITE_TEXTURE_DESCRIPTOR;
      var UNIFORM_REFLECTION_TEXTURE_NAME = 'cc_reflectionTexture';
      var UNIFORM_REFLECTION_TEXTURE_BINDING = ModelLocalBindings.SAMPLER_REFLECTION;
      var UNIFORM_REFLECTION_TEXTURE_DESCRIPTOR = new DescriptorSetLayoutBinding(UNIFORM_REFLECTION_TEXTURE_BINDING, DescriptorType.SAMPLER_TEXTURE, 1, ShaderStageFlagBit.FRAGMENT);
      var UNIFORM_REFLECTION_TEXTURE_LAYOUT = new UniformSamplerTexture(SetIndex.LOCAL, UNIFORM_REFLECTION_TEXTURE_BINDING, UNIFORM_REFLECTION_TEXTURE_NAME, Type$1.SAMPLER2D, 1);
      localDescriptorSetLayout.layouts[UNIFORM_REFLECTION_TEXTURE_NAME] = UNIFORM_REFLECTION_TEXTURE_LAYOUT;
      localDescriptorSetLayout.bindings[UNIFORM_REFLECTION_TEXTURE_BINDING] = UNIFORM_REFLECTION_TEXTURE_DESCRIPTOR;
      var UNIFORM_REFLECTION_STORAGE_NAME = 'cc_reflectionStorage';
      var UNIFORM_REFLECTION_STORAGE_BINDING = ModelLocalBindings.STORAGE_REFLECTION;
      var UNIFORM_REFLECTION_STORAGE_DESCRIPTOR = new DescriptorSetLayoutBinding(UNIFORM_REFLECTION_STORAGE_BINDING, DescriptorType.STORAGE_IMAGE, 1, ShaderStageFlagBit.COMPUTE);
      var UNIFORM_REFLECTION_STORAGE_LAYOUT = new UniformStorageImage(SetIndex.LOCAL, UNIFORM_REFLECTION_STORAGE_BINDING, UNIFORM_REFLECTION_STORAGE_NAME, Type$1.IMAGE2D, 1);
      localDescriptorSetLayout.layouts[UNIFORM_REFLECTION_STORAGE_NAME] = UNIFORM_REFLECTION_STORAGE_LAYOUT;
      localDescriptorSetLayout.bindings[UNIFORM_REFLECTION_STORAGE_BINDING] = UNIFORM_REFLECTION_STORAGE_DESCRIPTOR;
      var UNIFORM_REFLECTION_PROBE_CUBEMAP_NAME = 'cc_reflectionProbeCubemap';
      var UNIFORM_REFLECTION_PROBE_CUBEMAP_BINDING = ModelLocalBindings.SAMPLER_REFLECTION_PROBE_CUBE;
      var UNIFORM_REFLECTION_PROBE_CUBEMAP_DESCRIPTOR = new DescriptorSetLayoutBinding(UNIFORM_REFLECTION_PROBE_CUBEMAP_BINDING, DescriptorType.SAMPLER_TEXTURE, 1, ShaderStageFlagBit.FRAGMENT);
      var UNIFORM_REFLECTION_PROBE_CUBEMAP_LAYOUT = new UniformSamplerTexture(SetIndex.LOCAL, UNIFORM_REFLECTION_PROBE_CUBEMAP_BINDING, UNIFORM_REFLECTION_PROBE_CUBEMAP_NAME, Type$1.SAMPLER_CUBE, 1);
      localDescriptorSetLayout.layouts[UNIFORM_REFLECTION_PROBE_CUBEMAP_NAME] = UNIFORM_REFLECTION_PROBE_CUBEMAP_LAYOUT;
      localDescriptorSetLayout.bindings[UNIFORM_REFLECTION_PROBE_CUBEMAP_BINDING] = UNIFORM_REFLECTION_PROBE_CUBEMAP_DESCRIPTOR;
      var UNIFORM_REFLECTION_PROBE_TEXTURE_NAME = 'cc_reflectionProbePlanarMap';
      var UNIFORM_REFLECTION_PROBE_TEXTURE_BINDING = ModelLocalBindings.SAMPLER_REFLECTION_PROBE_PLANAR;
      var UNIFORM_REFLECTION_PROBE_TEXTURE_DESCRIPTOR = new DescriptorSetLayoutBinding(UNIFORM_REFLECTION_PROBE_TEXTURE_BINDING, DescriptorType.SAMPLER_TEXTURE, 1, ShaderStageFlagBit.FRAGMENT);
      var UNIFORM_REFLECTION_PROBE_TEXTURE_LAYOUT = new UniformSamplerTexture(SetIndex.LOCAL, UNIFORM_REFLECTION_PROBE_TEXTURE_BINDING, UNIFORM_REFLECTION_PROBE_TEXTURE_NAME, Type$1.SAMPLER2D, 1);
      localDescriptorSetLayout.layouts[UNIFORM_REFLECTION_PROBE_TEXTURE_NAME] = UNIFORM_REFLECTION_PROBE_TEXTURE_LAYOUT;
      localDescriptorSetLayout.bindings[UNIFORM_REFLECTION_PROBE_TEXTURE_BINDING] = UNIFORM_REFLECTION_PROBE_TEXTURE_DESCRIPTOR;
      var UNIFORM_REFLECTION_PROBE_DATA_MAP_NAME = 'cc_reflectionProbeDataMap';
      var UNIFORM_REFLECTION_PROBE_DATA_MAP_BINDING = ModelLocalBindings.SAMPLER_REFLECTION_PROBE_DATA_MAP;
      var UNIFORM_REFLECTION_PROBE_DATA_MAP_DESCRIPTOR = new DescriptorSetLayoutBinding(UNIFORM_REFLECTION_PROBE_DATA_MAP_BINDING, DescriptorType.SAMPLER_TEXTURE, 1, ShaderStageFlagBit.FRAGMENT);
      var UNIFORM_REFLECTION_PROBE_DATA_MAP_LAYOUT = new UniformSamplerTexture(SetIndex.LOCAL, UNIFORM_REFLECTION_PROBE_DATA_MAP_BINDING, UNIFORM_REFLECTION_PROBE_DATA_MAP_NAME, Type$1.SAMPLER2D, 1);
      localDescriptorSetLayout.layouts[UNIFORM_REFLECTION_PROBE_DATA_MAP_NAME] = UNIFORM_REFLECTION_PROBE_DATA_MAP_LAYOUT;
      localDescriptorSetLayout.bindings[UNIFORM_REFLECTION_PROBE_DATA_MAP_BINDING] = UNIFORM_REFLECTION_PROBE_DATA_MAP_DESCRIPTOR;
      var UNIFORM_REFLECTION_PROBE_BLEND_CUBEMAP_NAME = 'cc_reflectionProbeBlendCubemap';
      var UNIFORM_REFLECTION_PROBE_BLEND_CUBEMAP_BINDING = ModelLocalBindings.SAMPLER_REFLECTION_PROBE_BLEND_CUBE;
      var UNIFORM_REFLECTION_PROBE_BLEND_CUBEMAP_DESCRIPTOR = new DescriptorSetLayoutBinding(UNIFORM_REFLECTION_PROBE_BLEND_CUBEMAP_BINDING, DescriptorType.SAMPLER_TEXTURE, 1, ShaderStageFlagBit.FRAGMENT);
      var UNIFORM_REFLECTION_PROBE_BLEND_CUBEMAP_LAYOUT = new UniformSamplerTexture(SetIndex.LOCAL, UNIFORM_REFLECTION_PROBE_BLEND_CUBEMAP_BINDING, UNIFORM_REFLECTION_PROBE_BLEND_CUBEMAP_NAME, Type$1.SAMPLER_CUBE, 1);
      localDescriptorSetLayout.layouts[UNIFORM_REFLECTION_PROBE_BLEND_CUBEMAP_NAME] = UNIFORM_REFLECTION_PROBE_BLEND_CUBEMAP_LAYOUT;
      localDescriptorSetLayout.bindings[UNIFORM_REFLECTION_PROBE_BLEND_CUBEMAP_BINDING] = UNIFORM_REFLECTION_PROBE_BLEND_CUBEMAP_DESCRIPTOR;
      var CAMERA_DEFAULT_MASK = Layers.makeMaskExclude([Layers.BitMask.UI_2D, Layers.BitMask.GIZMOS, Layers.BitMask.EDITOR, Layers.BitMask.SCENE_GIZMO, Layers.BitMask.PROFILER]);
      var CAMERA_EDITOR_MASK = Layers.makeMaskExclude([Layers.BitMask.UI_2D, Layers.BitMask.PROFILER]);
      var MODEL_ALWAYS_MASK = Layers.Enum.ALL;
      function supportsR16HalfFloatTexture(device) {
        return (device.getFormatFeatures(Format.R16F) & (FormatFeatureBit.RENDER_TARGET | FormatFeatureBit.SAMPLED_TEXTURE)) === (FormatFeatureBit.RENDER_TARGET | FormatFeatureBit.SAMPLED_TEXTURE);
      }
      function supportsR32FloatTexture(device) {
        return (device.getFormatFeatures(Format.R32F) & (FormatFeatureBit.RENDER_TARGET | FormatFeatureBit.SAMPLED_TEXTURE)) === (FormatFeatureBit.RENDER_TARGET | FormatFeatureBit.SAMPLED_TEXTURE) && !(device.gfxAPI === API.WEBGL);
      }
      function supportsRGBA16HalfFloatTexture(device) {
        return (device.getFormatFeatures(Format.RGBA16F) & (FormatFeatureBit.RENDER_TARGET | FormatFeatureBit.SAMPLED_TEXTURE)) === (FormatFeatureBit.RENDER_TARGET | FormatFeatureBit.SAMPLED_TEXTURE) && !(device.gfxAPI === API.WEBGL);
      }
      function supportsRGBA32FloatTexture(device) {
        return (device.getFormatFeatures(Format.RGBA32F) & (FormatFeatureBit.RENDER_TARGET | FormatFeatureBit.SAMPLED_TEXTURE)) === (FormatFeatureBit.RENDER_TARGET | FormatFeatureBit.SAMPLED_TEXTURE) && !(device.gfxAPI === API.WEBGL);
      }
      function isEnableEffect() {
        return !!(legacyCC.rendering && legacyCC.rendering.enableEffectImport);
      }

      var define = /*#__PURE__*/Object.freeze({
        __proto__: null,
        PIPELINE_FLOW_MAIN: PIPELINE_FLOW_MAIN,
        PIPELINE_FLOW_FORWARD: PIPELINE_FLOW_FORWARD,
        PIPELINE_FLOW_SHADOW: PIPELINE_FLOW_SHADOW,
        PIPELINE_FLOW_SMAA: PIPELINE_FLOW_SMAA,
        PIPELINE_FLOW_TONEMAP: PIPELINE_FLOW_TONEMAP,
        get RenderPassStage () { return RenderPassStage; },
        get RenderPriority () { return RenderPriority; },
        globalDescriptorSetLayout: globalDescriptorSetLayout,
        localDescriptorSetLayout: localDescriptorSetLayout,
        get PipelineGlobalBindings () { return PipelineGlobalBindings; },
        get ModelLocalBindings () { return ModelLocalBindings; },
        get SetIndex () { return SetIndex; },
        bindingMappingInfo: bindingMappingInfo,
        UBOGlobal: UBOGlobal,
        UBOCamera: UBOCamera,
        UBOShadow: UBOShadow,
        UBOCSM: UBOCSM,
        UNIFORM_SHADOWMAP_BINDING: UNIFORM_SHADOWMAP_BINDING,
        UNIFORM_ENVIRONMENT_BINDING: UNIFORM_ENVIRONMENT_BINDING,
        UNIFORM_DIFFUSEMAP_BINDING: UNIFORM_DIFFUSEMAP_BINDING,
        UNIFORM_SPOT_SHADOW_MAP_TEXTURE_BINDING: UNIFORM_SPOT_SHADOW_MAP_TEXTURE_BINDING,
        UBOLocal: UBOLocal,
        UBOWorldBound: UBOWorldBound,
        INST_MAT_WORLD: INST_MAT_WORLD,
        INST_SH: INST_SH,
        UBOLocalBatched: UBOLocalBatched,
        UBOForwardLight: UBOForwardLight,
        UBODeferredLight: UBODeferredLight,
        JOINT_UNIFORM_CAPACITY: JOINT_UNIFORM_CAPACITY,
        UBOSkinningTexture: UBOSkinningTexture,
        UBOSkinningAnimation: UBOSkinningAnimation,
        INST_JOINT_ANIM_INFO: INST_JOINT_ANIM_INFO,
        UBOSkinning: UBOSkinning,
        localDescriptorSetLayout_ResizeMaxJoints: localDescriptorSetLayout_ResizeMaxJoints,
        UBOMorph: UBOMorph,
        UBOUILocal: UBOUILocal,
        UBOSH: UBOSH,
        UNIFORM_JOINT_TEXTURE_BINDING: UNIFORM_JOINT_TEXTURE_BINDING,
        UNIFORM_REALTIME_JOINT_TEXTURE_BINDING: UNIFORM_REALTIME_JOINT_TEXTURE_BINDING,
        UNIFORM_POSITION_MORPH_TEXTURE_BINDING: UNIFORM_POSITION_MORPH_TEXTURE_BINDING,
        UNIFORM_NORMAL_MORPH_TEXTURE_BINDING: UNIFORM_NORMAL_MORPH_TEXTURE_BINDING,
        UNIFORM_TANGENT_MORPH_TEXTURE_BINDING: UNIFORM_TANGENT_MORPH_TEXTURE_BINDING,
        UNIFORM_LIGHTMAP_TEXTURE_BINDING: UNIFORM_LIGHTMAP_TEXTURE_BINDING,
        UNIFORM_SPRITE_TEXTURE_BINDING: UNIFORM_SPRITE_TEXTURE_BINDING,
        UNIFORM_REFLECTION_TEXTURE_BINDING: UNIFORM_REFLECTION_TEXTURE_BINDING,
        UNIFORM_REFLECTION_STORAGE_BINDING: UNIFORM_REFLECTION_STORAGE_BINDING,
        UNIFORM_REFLECTION_PROBE_CUBEMAP_BINDING: UNIFORM_REFLECTION_PROBE_CUBEMAP_BINDING,
        UNIFORM_REFLECTION_PROBE_TEXTURE_BINDING: UNIFORM_REFLECTION_PROBE_TEXTURE_BINDING,
        UNIFORM_REFLECTION_PROBE_DATA_MAP_BINDING: UNIFORM_REFLECTION_PROBE_DATA_MAP_BINDING,
        UNIFORM_REFLECTION_PROBE_BLEND_CUBEMAP_BINDING: UNIFORM_REFLECTION_PROBE_BLEND_CUBEMAP_BINDING,
        CAMERA_DEFAULT_MASK: CAMERA_DEFAULT_MASK,
        CAMERA_EDITOR_MASK: CAMERA_EDITOR_MASK,
        MODEL_ALWAYS_MASK: MODEL_ALWAYS_MASK,
        supportsR16HalfFloatTexture: supportsR16HalfFloatTexture,
        supportsR32FloatTexture: supportsR32FloatTexture,
        supportsRGBA16HalfFloatTexture: supportsRGBA16HalfFloatTexture,
        supportsRGBA32FloatTexture: supportsRGBA32FloatTexture,
        isEnableEffect: isEnableEffect
      });
      exports('d2', define);

      var _type2reader, _type2writer, _type2validator;
      var typeMask = 0xfc000000;
      var bindingMask = 0x03f00000;
      var countMask = 0x000ff000;
      var offsetMask = 0x00000fff;
      var genHandle = function genHandle(binding, type, count, offset) {
        if (offset === void 0) {
          offset = 0;
        }
        return type << 26 & typeMask | binding << 20 & bindingMask | count << 12 & countMask | offset & offsetMask;
      };
      var getTypeFromHandle = function getTypeFromHandle(handle) {
        return (handle & typeMask) >>> 26;
      };
      var getBindingFromHandle = function getBindingFromHandle(handle) {
        return (handle & bindingMask) >>> 20;
      };
      var getCountFromHandle = function getCountFromHandle(handle) {
        return (handle & countMask) >>> 12;
      };
      var getOffsetFromHandle = function getOffsetFromHandle(handle) {
        return handle & offsetMask;
      };
      var customizeType = function customizeType(handle, type) {
        return handle & ~typeMask | type << 26 & typeMask;
      };
      var type2reader = (_type2reader = {}, _type2reader[Type$1.UNKNOWN] = function (a, v, idx) {
        if (idx === void 0) {
          idx = 0;
        }
        return warnID(12010, idx);
      }, _type2reader[Type$1.INT] = function (a, v, idx) {
        if (idx === void 0) {
          idx = 0;
        }
        return a[idx];
      }, _type2reader[Type$1.INT2] = function (a, v, idx) {
        if (idx === void 0) {
          idx = 0;
        }
        return Vec2.fromArray(v, a, idx);
      }, _type2reader[Type$1.INT3] = function (a, v, idx) {
        if (idx === void 0) {
          idx = 0;
        }
        return Vec3.fromArray(v, a, idx);
      }, _type2reader[Type$1.INT4] = function (a, v, idx) {
        if (idx === void 0) {
          idx = 0;
        }
        return Vec4.fromArray(v, a, idx);
      }, _type2reader[Type$1.FLOAT] = function (a, v, idx) {
        if (idx === void 0) {
          idx = 0;
        }
        return a[idx];
      }, _type2reader[Type$1.FLOAT2] = function (a, v, idx) {
        if (idx === void 0) {
          idx = 0;
        }
        return Vec2.fromArray(v, a, idx);
      }, _type2reader[Type$1.FLOAT3] = function (a, v, idx) {
        if (idx === void 0) {
          idx = 0;
        }
        return Vec3.fromArray(v, a, idx);
      }, _type2reader[Type$1.FLOAT4] = function (a, v, idx) {
        if (idx === void 0) {
          idx = 0;
        }
        return Vec4.fromArray(v, a, idx);
      }, _type2reader[Type$1.MAT3] = function (a, v, idx) {
        if (idx === void 0) {
          idx = 0;
        }
        return Mat3.fromArray(v, a, idx);
      }, _type2reader[Type$1.MAT4] = function (a, v, idx) {
        if (idx === void 0) {
          idx = 0;
        }
        return Mat4.fromArray(v, a, idx);
      }, _type2reader);
      var type2writer = (_type2writer = {}, _type2writer[Type$1.UNKNOWN] = function (a, v, idx) {
        if (idx === void 0) {
          idx = 0;
        }
        return warnID(12010, idx);
      }, _type2writer[Type$1.INT] = function (a, v, idx) {
        if (idx === void 0) {
          idx = 0;
        }
        return a[idx] = v;
      }, _type2writer[Type$1.INT2] = function (a, v, idx) {
        if (idx === void 0) {
          idx = 0;
        }
        return Vec2.toArray(a, v, idx);
      }, _type2writer[Type$1.INT3] = function (a, v, idx) {
        if (idx === void 0) {
          idx = 0;
        }
        return Vec3.toArray(a, v, idx);
      }, _type2writer[Type$1.INT4] = function (a, v, idx) {
        if (idx === void 0) {
          idx = 0;
        }
        return Vec4.toArray(a, v, idx);
      }, _type2writer[Type$1.FLOAT] = function (a, v, idx) {
        if (idx === void 0) {
          idx = 0;
        }
        return a[idx] = v;
      }, _type2writer[Type$1.FLOAT2] = function (a, v, idx) {
        if (idx === void 0) {
          idx = 0;
        }
        return Vec2.toArray(a, v, idx);
      }, _type2writer[Type$1.FLOAT3] = function (a, v, idx) {
        if (idx === void 0) {
          idx = 0;
        }
        return Vec3.toArray(a, v, idx);
      }, _type2writer[Type$1.FLOAT4] = function (a, v, idx) {
        if (idx === void 0) {
          idx = 0;
        }
        return Vec4.toArray(a, v, idx);
      }, _type2writer[Type$1.MAT3] = function (a, v, idx) {
        if (idx === void 0) {
          idx = 0;
        }
        return Mat3.toArray(a, v, idx);
      }, _type2writer[Type$1.MAT4] = function (a, v, idx) {
        if (idx === void 0) {
          idx = 0;
        }
        return Mat4.toArray(a, v, idx);
      }, _type2writer);
      var type2validator = (_type2validator = {}, _type2validator[Type$1.INT] = function (v) {
        return typeof v === 'number';
      }, _type2validator[Type$1.FLOAT] = function (v) {
        return typeof v === 'number';
      }, _type2validator[Type$1.INT2] = function (v) {
        return !!(v instanceof Vec2);
      }, _type2validator[Type$1.FLOAT2] = function (v) {
        return !!(v instanceof Vec2);
      }, _type2validator[Type$1.INT3] = function (v) {
        return !!(v instanceof Vec3);
      }, _type2validator[Type$1.FLOAT3] = function (v) {
        return !!(v instanceof Vec3);
      }, _type2validator[Type$1.INT4] = function (v) {
        return !!(v instanceof Vec4);
      }, _type2validator[Type$1.FLOAT4] = function (v) {
        return !!(v instanceof Vec4 || v instanceof Color$1 || v instanceof Quat);
      }, _type2validator[Type$1.MAT3] = function (v) {
        return !!(v instanceof Mat3);
      }, _type2validator[Type$1.MAT4] = function (v) {
        return !!(v instanceof Mat4);
      }, _type2validator);
      var defaultValues = [Object.freeze([0]), Object.freeze([0, 0]), Object.freeze([0, 0, 0, 0]), Object.freeze([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1])];
      function getDefaultFromType(type) {
        switch (type) {
          case Type$1.BOOL:
          case Type$1.INT:
          case Type$1.UINT:
          case Type$1.FLOAT:
            return defaultValues[0];
          case Type$1.BOOL2:
          case Type$1.INT2:
          case Type$1.UINT2:
          case Type$1.FLOAT2:
            return defaultValues[1];
          case Type$1.BOOL4:
          case Type$1.INT4:
          case Type$1.UINT4:
          case Type$1.FLOAT4:
            return defaultValues[2];
          case Type$1.MAT4:
            return defaultValues[3];
          case Type$1.SAMPLER2D:
            return 'default-texture';
          case Type$1.SAMPLER_CUBE:
            return 'default-cube-texture';
          case Type$1.SAMPLER2D_ARRAY:
            return 'default-array-texture';
          case Type$1.SAMPLER3D:
            return 'default-3d-texture';
        }
        return defaultValues[0];
      }
      function getStringFromType(type) {
        switch (type) {
          case Type$1.SAMPLER2D:
            return '-texture';
          case Type$1.SAMPLER_CUBE:
            return '-cube-texture';
          case Type$1.SAMPLER2D_ARRAY:
            return '-array-texture';
          case Type$1.SAMPLER3D:
            return '-3d-texture';
          default:
            return '-unknown';
        }
      }
      function overrideMacros(target, source) {
        var entries = Object.entries(source);
        var isDifferent = false;
        for (var i = 0; i < entries.length; i++) {
          if (target[entries[i][0]] !== entries[i][1]) {
            target[entries[i][0]] = entries[i][1];
            isDifferent = true;
          }
        }
        return isDifferent;
      }

      function mapDefine(info, def) {
        switch (info.type) {
          case 'boolean':
            return typeof def === 'number' ? def.toString() : def ? '1' : '0';
          case 'string':
            return def !== undefined ? def : info.options[0];
          case 'number':
            return def !== undefined ? def.toString() : info.range[0].toString();
          default:
            console.warn("unknown define type '" + info.type + "'");
            return '-1';
        }
      }
      function prepareDefines(defs, tDefs) {
        var macros = [];
        for (var i = 0; i < tDefs.length; i++) {
          var tmpl = tDefs[i];
          var name = tmpl.name;
          var v = defs[name];
          var value = mapDefine(tmpl, v);
          var isDefault = !v || v === '0';
          macros.push({
            name: name,
            value: value,
            isDefault: isDefault
          });
        }
        return macros;
      }
      function getShaderInstanceName(name, macros) {
        return name + macros.reduce(function (acc, cur) {
          return cur.isDefault ? acc : acc + "|" + cur.name + cur.value;
        }, '');
      }
      function dependencyCheck(dependencies, defines) {
        for (var i = 0; i < dependencies.length; i++) {
          var d = dependencies[i];
          if (d[0] === '!') {
            if (defines[d.slice(1)]) {
              return false;
            }
          } else if (!defines[d]) {
            return false;
          }
        }
        return true;
      }
      function getActiveAttributes(tmpl, gfxAttributes, defines) {
        var out = [];
        var attributes = tmpl.attributes;
        for (var i = 0; i < attributes.length; i++) {
          if (!dependencyCheck(attributes[i].defines, defines)) {
            continue;
          }
          out.push(gfxAttributes[i]);
        }
        return out;
      }
      function getVariantKey(programInfo, defines) {
        var tmplDefs = programInfo.defines;
        if (programInfo.uber) {
          var _key = '';
          for (var i = 0; i < tmplDefs.length; i++) {
            var tmplDef = tmplDefs[i];
            var value = defines[tmplDef.name];
            if (!value || !tmplDef._map) {
              continue;
            }
            var mapped = tmplDef._map(value);
            var offset = tmplDef._offset;
            _key += "" + offset + mapped + "|";
          }
          return "" + _key + programInfo.hash;
        }
        var key = 0;
        for (var _i = 0; _i < tmplDefs.length; _i++) {
          var _tmplDef = tmplDefs[_i];
          var _value = defines[_tmplDef.name];
          if (!_value || !_tmplDef._map) {
            continue;
          }
          var _mapped = _tmplDef._map(_value);
          var _offset = _tmplDef._offset;
          key |= _mapped << _offset;
        }
        return key.toString(16) + "|" + programInfo.hash;
      }
      var defaultUniformCounts = new Map();
      defaultUniformCounts.set('cc_joints', UBOSkinning.LAYOUT.members[0].count);
      defaultUniformCounts.set('cc_lightPos', UBOForwardLight.LIGHTS_PER_PASS);
      defaultUniformCounts.set('cc_lightColor', UBOForwardLight.LIGHTS_PER_PASS);
      defaultUniformCounts.set('cc_lightSizeRangeAngle', UBOForwardLight.LIGHTS_PER_PASS);
      defaultUniformCounts.set('cc_lightDir', UBOForwardLight.LIGHTS_PER_PASS);
      defaultUniformCounts.set('cc_lightBoundingSizeVS', UBOForwardLight.LIGHTS_PER_PASS);
      function getUniformSize(prevSize, m) {
        if (m.count) {
          return prevSize + GetTypeSize(m.type) * m.count;
        } else {
          var count = defaultUniformCounts.get(m.name);
          if (count !== undefined) {
            return prevSize + GetTypeSize(m.type) * count;
          }
          console.error("uniform '" + m.name + "' must have a count");
        }
        return prevSize;
      }
      function getSize(blockMembers) {
        return blockMembers.reduce(getUniformSize, 0);
      }
      function genHandles(tmpl) {
        var handleMap = {};
        for (var i = 0; i < tmpl.blocks.length; i++) {
          var block = tmpl.blocks[i];
          var members = block.members;
          var offset = 0;
          for (var j = 0; j < members.length; j++) {
            var uniform = members[j];
            handleMap[uniform.name] = genHandle(block.binding, uniform.type, uniform.count, offset);
            offset += (GetTypeSize(uniform.type) >> 2) * uniform.count;
          }
        }
        for (var _i2 = 0; _i2 < tmpl.samplerTextures.length; _i2++) {
          var samplerTexture = tmpl.samplerTextures[_i2];
          handleMap[samplerTexture.name] = genHandle(samplerTexture.binding, samplerTexture.type, samplerTexture.count);
        }
        return handleMap;
      }
      function getBitCount(cnt) {
        return Math.ceil(Math.log2(Math.max(cnt, 2)));
      }
      function populateMacros(tmpl) {
        var offset = 0;
        var _loop = function _loop() {
          var def = tmpl.defines[i];
          var cnt = 1;
          if (def.type === 'number') {
            var range = def.range;
            cnt = getBitCount(range[1] - range[0] + 1);
            def._map = function (value) {
              return value - range[0];
            };
          } else if (def.type === 'string') {
            cnt = getBitCount(def.options.length);
            def._map = function (value) {
              return Math.max(0, def.options.findIndex(function (s) {
                return s === value;
              }));
            };
          } else if (def.type === 'boolean') {
            def._map = function (value) {
              return value ? 1 : 0;
            };
          }
          def._offset = offset;
          offset += cnt;
        };
        for (var i = 0; i < tmpl.defines.length; i++) {
          _loop();
        }
        if (offset > 31) {
          tmpl.uber = true;
        }
        tmpl.constantMacros = '';
        for (var key in tmpl.builtins.statistics) {
          tmpl.constantMacros += "#define " + key + " " + tmpl.builtins.statistics[key] + "\n";
        }
      }
      function getCombinationDefines(combination) {
        var defines = Object.keys(combination).reduce(function (out, name) {
          return out.reduce(function (acc, cur) {
            var choices = combination[name];
            for (var i = 0; i < choices.length; ++i) {
              var _defines = _extends({}, cur);
              _defines[name] = choices[i];
              acc.push(_defines);
            }
            return acc;
          }, []);
        }, [{}]);
        return defines;
      }
      function addEffectDefaultProperties(effect) {
        for (var i = 0; i < effect.techniques.length; i++) {
          var tech = effect.techniques[i];
          for (var j = 0; j < tech.passes.length; j++) {
            var pass = tech.passes[j];
            if (pass.propertyIndex !== undefined && pass.properties === undefined) {
              pass.properties = tech.passes[pass.propertyIndex].properties;
            }
          }
        }
      }

      var _dsLayoutInfo = new DescriptorSetLayoutInfo();
      function insertBuiltinBindings(tmpl, tmplInfo, source, type, outBindings) {
        var target = tmpl.builtins[type];
        var tempBlocks = [];
        var _loop = function _loop() {
          var b = target.blocks[i];
          var info = source.layouts[b.name];
          var binding = info && source.bindings.find(function (bd) {
            return bd.binding === info.binding;
          });
          if (!info || !binding || !(binding.descriptorType & DESCRIPTOR_BUFFER_TYPE)) {
            console.warn("builtin UBO '" + b.name + "' not available!");
            return 1;
          }
          tempBlocks.push(info);
          if (outBindings && !outBindings.includes(binding)) outBindings.push(binding);
        };
        for (var i = 0; i < target.blocks.length; i++) {
          if (_loop()) continue;
        }
        Array.prototype.unshift.apply(tmplInfo.shaderInfo.blocks, tempBlocks);
        var tempSamplerTextures = [];
        var _loop2 = function _loop2() {
          var s = target.samplerTextures[_i];
          var info = source.layouts[s.name];
          var binding = info && source.bindings.find(function (bd) {
            return bd.binding === info.binding;
          });
          if (!info || !binding || !(binding.descriptorType & DESCRIPTOR_SAMPLER_TYPE)) {
            console.warn("builtin samplerTexture '" + s.name + "' not available!");
            return 1;
          }
          tempSamplerTextures.push(info);
          if (outBindings && !outBindings.includes(binding)) outBindings.push(binding);
        };
        for (var _i = 0; _i < target.samplerTextures.length; _i++) {
          if (_loop2()) continue;
        }
        Array.prototype.unshift.apply(tmplInfo.shaderInfo.samplerTextures, tempSamplerTextures);
        if (outBindings) outBindings.sort(function (a, b) {
          return a.binding - b.binding;
        });
      }
      var ProgramLib = function () {
        function ProgramLib() {
          this._templates = {};
          this._cache = {};
          this._templateInfos = {};
        }
        var _proto = ProgramLib.prototype;
        _proto.register = function register(effect) {
          for (var i = 0; i < effect.shaders.length; i++) {
            var tmpl = this.define(effect.shaders[i]);
            tmpl.effectName = effect.name;
          }
          for (var _i2 = 0; _i2 < effect.techniques.length; _i2++) {
            var tech = effect.techniques[_i2];
            for (var j = 0; j < tech.passes.length; j++) {
              var pass = tech.passes[j];
              if (pass.propertyIndex !== undefined && pass.properties === undefined) {
                pass.properties = tech.passes[pass.propertyIndex].properties;
              }
            }
          }
        };
        _proto.define = function define(shader) {
          var curTmpl = this._templates[shader.name];
          if (curTmpl && curTmpl.hash === shader.hash) {
            return curTmpl;
          }
          var tmpl = _extends({}, shader);
          populateMacros(tmpl);
          this._templates[shader.name] = tmpl;
          if (!this._templateInfos[tmpl.hash]) {
            var tmplInfo = {};
            tmplInfo.samplerStartBinding = tmpl.blocks.length;
            tmplInfo.shaderInfo = new ShaderInfo();
            tmplInfo.blockSizes = [];
            tmplInfo.bindings = [];
            for (var i = 0; i < tmpl.blocks.length; i++) {
              var block = tmpl.blocks[i];
              tmplInfo.blockSizes.push(getSize(block.members));
              tmplInfo.bindings.push(new DescriptorSetLayoutBinding(block.binding, DescriptorType.UNIFORM_BUFFER, 1, block.stageFlags));
              tmplInfo.shaderInfo.blocks.push(new UniformBlock(SetIndex.MATERIAL, block.binding, block.name, block.members.map(function (m) {
                return new Uniform(m.name, m.type, m.count);
              }), 1));
            }
            for (var _i3 = 0; _i3 < tmpl.samplerTextures.length; _i3++) {
              var samplerTexture = tmpl.samplerTextures[_i3];
              tmplInfo.bindings.push(new DescriptorSetLayoutBinding(samplerTexture.binding, DescriptorType.SAMPLER_TEXTURE, samplerTexture.count, samplerTexture.stageFlags));
              tmplInfo.shaderInfo.samplerTextures.push(new UniformSamplerTexture(SetIndex.MATERIAL, samplerTexture.binding, samplerTexture.name, samplerTexture.type, samplerTexture.count));
            }
            for (var _i4 = 0; _i4 < tmpl.samplers.length; _i4++) {
              var sampler = tmpl.samplers[_i4];
              tmplInfo.bindings.push(new DescriptorSetLayoutBinding(sampler.binding, DescriptorType.SAMPLER, sampler.count, sampler.stageFlags));
              tmplInfo.shaderInfo.samplers.push(new UniformSampler(SetIndex.MATERIAL, sampler.binding, sampler.name, sampler.count));
            }
            for (var _i5 = 0; _i5 < tmpl.textures.length; _i5++) {
              var texture = tmpl.textures[_i5];
              tmplInfo.bindings.push(new DescriptorSetLayoutBinding(texture.binding, DescriptorType.TEXTURE, texture.count, texture.stageFlags));
              tmplInfo.shaderInfo.textures.push(new UniformTexture(SetIndex.MATERIAL, texture.binding, texture.name, texture.type, texture.count));
            }
            for (var _i6 = 0; _i6 < tmpl.buffers.length; _i6++) {
              var buffer = tmpl.buffers[_i6];
              tmplInfo.bindings.push(new DescriptorSetLayoutBinding(buffer.binding, DescriptorType.STORAGE_BUFFER, 1, buffer.stageFlags));
              tmplInfo.shaderInfo.buffers.push(new UniformStorageBuffer(SetIndex.MATERIAL, buffer.binding, buffer.name, 1, buffer.memoryAccess));
            }
            for (var _i7 = 0; _i7 < tmpl.images.length; _i7++) {
              var image = tmpl.images[_i7];
              tmplInfo.bindings.push(new DescriptorSetLayoutBinding(image.binding, DescriptorType.STORAGE_IMAGE, image.count, image.stageFlags));
              tmplInfo.shaderInfo.images.push(new UniformStorageImage(SetIndex.MATERIAL, image.binding, image.name, image.type, image.count, image.memoryAccess));
            }
            for (var _i8 = 0; _i8 < tmpl.subpassInputs.length; _i8++) {
              var subpassInput = tmpl.subpassInputs[_i8];
              tmplInfo.bindings.push(new DescriptorSetLayoutBinding(subpassInput.binding, DescriptorType.INPUT_ATTACHMENT, subpassInput.count, subpassInput.stageFlags));
              tmplInfo.shaderInfo.subpassInputs.push(new UniformInputAttachment(SetIndex.MATERIAL, subpassInput.binding, subpassInput.name, subpassInput.count));
            }
            tmplInfo.gfxAttributes = [];
            for (var _i9 = 0; _i9 < tmpl.attributes.length; _i9++) {
              var attr = tmpl.attributes[_i9];
              tmplInfo.gfxAttributes.push(new Attribute(attr.name, attr.format, attr.isNormalized, 0, attr.isInstanced, attr.location));
            }
            insertBuiltinBindings(tmpl, tmplInfo, localDescriptorSetLayout, 'locals');
            tmplInfo.shaderInfo.stages.push(new ShaderStage(ShaderStageFlagBit.VERTEX, ''));
            tmplInfo.shaderInfo.stages.push(new ShaderStage(ShaderStageFlagBit.FRAGMENT, ''));
            tmplInfo.handleMap = genHandles(tmpl);
            tmplInfo.setLayouts = [];
            this._templateInfos[tmpl.hash] = tmplInfo;
          }
          return tmpl;
        };
        _proto.getTemplate = function getTemplate(name) {
          return this._templates[name];
        };
        _proto.getTemplateInfo = function getTemplateInfo(name) {
          var hash = this._templates[name].hash;
          return this._templateInfos[hash];
        };
        _proto.getDescriptorSetLayout = function getDescriptorSetLayout(device, name, isLocal) {
          if (isLocal === void 0) {
            isLocal = false;
          }
          var tmpl = this._templates[name];
          var tmplInfo = this._templateInfos[tmpl.hash];
          if (!tmplInfo.setLayouts.length) {
            _dsLayoutInfo.bindings = tmplInfo.bindings;
            tmplInfo.setLayouts[SetIndex.MATERIAL] = device.createDescriptorSetLayout(_dsLayoutInfo);
            _dsLayoutInfo.bindings = localDescriptorSetLayout.bindings;
            tmplInfo.setLayouts[SetIndex.LOCAL] = device.createDescriptorSetLayout(_dsLayoutInfo);
          }
          return tmplInfo.setLayouts[isLocal ? SetIndex.LOCAL : SetIndex.MATERIAL];
        };
        _proto.hasProgram = function hasProgram(name) {
          return this._templates[name] !== undefined;
        };
        _proto.getKey = function getKey(name, defines) {
          var tmpl = this._templates[name];
          return getVariantKey(tmpl, defines);
        };
        _proto.destroyShaderByDefines = function destroyShaderByDefines(defines) {
          var _this = this;
          var names = Object.keys(defines);
          if (!names.length) {
            return;
          }
          var regexes = names.map(function (cur) {
            var val = defines[cur];
            if (typeof val === 'boolean') {
              val = val ? '1' : '0';
            }
            return new RegExp("" + cur + val);
          });
          var keys = Object.keys(this._cache).filter(function (k) {
            return regexes.every(function (re) {
              return re.test(_this._cache[k].name);
            });
          });
          for (var i = 0; i < keys.length; i++) {
            var k = keys[i];
            var prog = this._cache[k];
            debug("destroyed shader " + prog.name);
            prog.destroy();
            delete this._cache[k];
          }
        };
        _proto.getGFXShader = function getGFXShader(device, name, defines, pipeline, key) {
          Object.assign(defines, pipeline.macros);
          if (!key) key = this.getKey(name, defines);
          var res = this._cache[key];
          if (res) {
            return res;
          }
          var tmpl = this._templates[name];
          var tmplInfo = this._templateInfos[tmpl.hash];
          if (!tmplInfo.pipelineLayout) {
            this.getDescriptorSetLayout(device, name);
            insertBuiltinBindings(tmpl, tmplInfo, globalDescriptorSetLayout, 'globals');
            tmplInfo.setLayouts[SetIndex.GLOBAL] = pipeline.descriptorSetLayout;
            tmplInfo.pipelineLayout = device.createPipelineLayout(new PipelineLayoutInfo(tmplInfo.setLayouts));
          }
          var macroArray = prepareDefines(defines, tmpl.defines);
          var prefix = pipeline.constantMacros + tmpl.constantMacros + macroArray.reduce(function (acc, cur) {
            return acc + "#define " + cur.name + " " + cur.value + "\n";
          }, '');
          var src = tmpl.glsl3;
          var deviceShaderVersion = getDeviceShaderVersion(device);
          if (deviceShaderVersion) {
            src = tmpl[deviceShaderVersion];
          } else {
            console.error('Invalid GFX API!');
          }
          tmplInfo.shaderInfo.stages[0].source = prefix + src.vert;
          tmplInfo.shaderInfo.stages[1].source = prefix + src.frag;
          tmplInfo.shaderInfo.attributes = getActiveAttributes(tmpl, tmplInfo.gfxAttributes, defines);
          tmplInfo.shaderInfo.name = getShaderInstanceName(name, macroArray);
          var shaderInfo = tmplInfo.shaderInfo;
          return this._cache[key] = device.createShader(shaderInfo);
        };
        return ProgramLib;
      }();
      function getDeviceShaderVersion(device) {
        switch (device.gfxAPI) {
          case API.GLES2:
          case API.WEBGL:
            return 'glsl1';
          case API.GLES3:
          case API.WEBGL2:
            return 'glsl3';
          default:
            return 'glsl4';
        }
      }
      var programLib = new ProgramLib();
      legacyCC.programLib = programLib;

      var _dec$2V, _class$2R, _class2$2B, _initializer$2k, _initializer2$1O, _initializer3$1d, _initializer4$Y, _class3$L;
      var legacyBuiltinEffectNames = ['planar-shadow', 'skybox', 'deferred-lighting', 'bloom', 'hbao', 'copy-pass', 'post-process', 'profiler', 'splash-screen', 'unlit', 'sprite', 'particle', 'particle-gpu', 'particle-trail', 'billboard', 'terrain', 'graphics', 'clear-stencil', 'spine', 'occlusion-query', 'geometry-renderer', 'debug-renderer', 'ssss-blur', 'float-output-process'];
      var EffectAsset = exports('eb', (_dec$2V = ccclass$n('cc.EffectAsset'), _dec$2V(_class$2R = (_class2$2B = (_class3$L = function (_Asset) {
        _inheritsLoose(EffectAsset, _Asset);
        function EffectAsset() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Asset.call.apply(_Asset, [this].concat(args)) || this;
          _this.techniques = _initializer$2k && _initializer$2k();
          _this.shaders = _initializer2$1O && _initializer2$1O();
          _this.combinations = _initializer3$1d && _initializer3$1d();
          _this.hideInEditor = _initializer4$Y && _initializer4$Y();
          return _this;
        }
        EffectAsset.register = function register(asset) {
          EffectAsset._effects[asset.name] = asset;
          EffectAsset._layoutValid = false;
        };
        EffectAsset.remove = function remove(asset) {
          if (typeof asset !== 'string') {
            if (EffectAsset._effects[asset.name] && EffectAsset._effects[asset.name] === asset) {
              delete EffectAsset._effects[asset.name];
            }
          } else {
            if (EffectAsset._effects[asset]) {
              delete EffectAsset._effects[asset];
              return;
            }
            for (var n in EffectAsset._effects) {
              if (EffectAsset._effects[n]._uuid === asset) {
                delete EffectAsset._effects[n];
                return;
              }
            }
          }
        };
        EffectAsset.get = function get(name) {
          if (EffectAsset._effects[name]) {
            return EffectAsset._effects[name];
          }
          for (var n in EffectAsset._effects) {
            if (EffectAsset._effects[n]._uuid === name) {
              return EffectAsset._effects[n];
            }
          }
          if (legacyBuiltinEffectNames.includes(name)) {
            warnID(16101, name);
          }
          return null;
        };
        EffectAsset.getAll = function getAll() {
          return EffectAsset._effects;
        };
        EffectAsset.isLayoutValid = function isLayoutValid() {
          return EffectAsset._layoutValid;
        };
        EffectAsset.setLayoutValid = function setLayoutValid() {
          EffectAsset._layoutValid = true;
        };
        var _proto = EffectAsset.prototype;
        _proto.onLoaded = function onLoaded() {
          if (legacyCC.rendering && legacyCC.rendering.enableEffectImport) {
            addEffectDefaultProperties(this);
            legacyCC.rendering.programLib.addEffect(this);
          } else {
            programLib.register(this);
          }
          EffectAsset.register(this);
          {
            legacyCC.game.once(legacyCC.Game.EVENT_RENDERER_INITED, this._precompile, this);
          }
        };
        _proto._precompile = function _precompile() {
          var _this2 = this;
          if (legacyCC.rendering && legacyCC.rendering.enableEffectImport) {
            legacyCC.rendering.programLib.precompileEffect(deviceManager.gfxDevice, this);
            return;
          }
          var root = legacyCC.director.root;
          var _loop = function _loop() {
            var shader = _this2.shaders[i];
            var combination = _this2.combinations[i];
            if (!combination) {
              return 1;
            }
            var defines = getCombinationDefines(combination);
            defines.forEach(function (defines) {
              return programLib.getGFXShader(deviceManager.gfxDevice, shader.name, defines, root.pipeline);
            });
          };
          for (var i = 0; i < this.shaders.length; i++) {
            if (_loop()) continue;
          }
        };
        _proto.destroy = function destroy() {
          EffectAsset.remove(this);
          return _Asset.prototype.destroy.call(this);
        };
        _proto.initDefault = function initDefault(uuid) {
          _Asset.prototype.initDefault.call(this, uuid);
          var effect = EffectAsset.get('builtin-unlit');
          this.name = 'builtin-unlit';
          this.shaders = effect.shaders;
          this.combinations = effect.combinations;
          this.techniques = effect.techniques;
        };
        _proto.validate = function validate() {
          return this.techniques.length > 0 && this.shaders.length > 0;
        };
        return EffectAsset;
      }(Asset), _class3$L._effects = {}, _class3$L._layoutValid = true, _class3$L), (_initializer$2k = applyDecoratedInitializer(_class2$2B.prototype, "techniques", [serializable$j], function () {
        return [];
      }), _initializer2$1O = applyDecoratedInitializer(_class2$2B.prototype, "shaders", [serializable$j], function () {
        return [];
      }), _initializer3$1d = applyDecoratedInitializer(_class2$2B.prototype, "combinations", [serializable$j], function () {
        return [];
      }), _initializer4$Y = applyDecoratedInitializer(_class2$2B.prototype, "hideInEditor", [serializable$j, editorOnly], function () {
        return false;
      })), _class2$2B)) || _class$2R));
      legacyCC.EffectAsset = EffectAsset;

      var _dec$2U, _class$2Q, _class2$2A, _initializer$2j, _initializer2$1N, _initializer3$1c, _initializer4$X, _class3$K;
      var FaceIndex;
      (function (FaceIndex) {
        FaceIndex[FaceIndex["right"] = 0] = "right";
        FaceIndex[FaceIndex["left"] = 1] = "left";
        FaceIndex[FaceIndex["top"] = 2] = "top";
        FaceIndex[FaceIndex["bottom"] = 3] = "bottom";
        FaceIndex[FaceIndex["front"] = 4] = "front";
        FaceIndex[FaceIndex["back"] = 5] = "back";
      })(FaceIndex || (FaceIndex = {}));
      var MipmapMode;
      (function (MipmapMode) {
        MipmapMode[MipmapMode["NONE"] = 0] = "NONE";
        MipmapMode[MipmapMode["AUTO"] = 1] = "AUTO";
        MipmapMode[MipmapMode["BAKED_CONVOLUTION_MAP"] = 2] = "BAKED_CONVOLUTION_MAP";
      })(MipmapMode || (MipmapMode = {}));
      var TextureCube = exports('ea', (_dec$2U = ccclass$n('cc.TextureCube'), _dec$2U(_class$2Q = (_class2$2A = (_class3$K = function (_SimpleTexture) {
        _inheritsLoose(TextureCube, _SimpleTexture);
        function TextureCube() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _SimpleTexture.call.apply(_SimpleTexture, [this].concat(args)) || this;
          _this.isRGBE = _initializer$2j && _initializer$2j();
          _this._mipmapAtlas = _initializer2$1N && _initializer2$1N();
          _this._mipmapMode = _initializer3$1c && _initializer3$1c();
          _this._mipmaps = _initializer4$X && _initializer4$X();
          _this._generatedMipmaps = [];
          return _this;
        }
        var _proto = TextureCube.prototype;
        _proto._setMipmapParams = function _setMipmapParams(value) {
          var _this2 = this;
          this._generatedMipmaps = value;
          this._setMipmapLevel(this._generatedMipmaps.length);
          if (this._generatedMipmaps.length > 0) {
            var imageAsset = this._generatedMipmaps[0].front;
            this.reset({
              width: imageAsset.width,
              height: imageAsset.height,
              format: imageAsset.format,
              mipmapLevel: this._generatedMipmaps.length,
              baseLevel: this._baseLevel,
              maxLevel: this._maxLevel
            });
            this._generatedMipmaps.forEach(function (mipmap, level) {
              _forEachFace(mipmap, function (face, faceIndex) {
                _this2._assignImage(face, level, faceIndex);
              });
            });
          } else {
            this.reset({
              width: 0,
              height: 0,
              mipmapLevel: this._generatedMipmaps.length,
              baseLevel: this._baseLevel,
              maxLevel: this._maxLevel
            });
          }
        };
        _proto.isUsingOfflineMipmaps = function isUsingOfflineMipmaps() {
          return this._mipmapMode === MipmapMode.BAKED_CONVOLUTION_MAP;
        };
        TextureCube.fromTexture2DArray = function fromTexture2DArray(textures, out) {
          var mipmaps = [];
          var nMipmaps = textures.length / 6;
          for (var i = 0; i < nMipmaps; i++) {
            var x = i * 6;
            mipmaps.push({
              front: textures[x + FaceIndex.front].image,
              back: textures[x + FaceIndex.back].image,
              left: textures[x + FaceIndex.left].image,
              right: textures[x + FaceIndex.right].image,
              top: textures[x + FaceIndex.top].image,
              bottom: textures[x + FaceIndex.bottom].image
            });
          }
          out = out || new TextureCube();
          out.mipmaps = mipmaps;
          return out;
        };
        _proto.onLoaded = function onLoaded() {
          if (this._mipmapMode === MipmapMode.BAKED_CONVOLUTION_MAP) {
            this.mipmapAtlas = this._mipmapAtlas;
          } else {
            this.mipmaps = this._mipmaps;
          }
        };
        _proto.reset = function reset(info) {
          this._width = info.width;
          this._height = info.height;
          this._setGFXFormat(info.format);
          var mipLevels = info.mipmapLevel === undefined ? 1 : info.mipmapLevel;
          this._setMipmapLevel(mipLevels);
          var minLod = info.baseLevel === undefined ? 0 : info.baseLevel;
          var maxLod = info.maxLevel === undefined ? 1000 : info.maxLevel;
          this._setMipRange(minLod, maxLod);
          this._tryReset();
        };
        _proto.updateMipmaps = function updateMipmaps(firstLevel, count) {
          var _this3 = this;
          if (firstLevel === void 0) {
            firstLevel = 0;
          }
          if (firstLevel >= this._generatedMipmaps.length) {
            return;
          }
          var nUpdate = Math.min(count === undefined ? this._generatedMipmaps.length : count, this._generatedMipmaps.length - firstLevel);
          var _loop = function _loop() {
            var level = firstLevel + i;
            _forEachFace(_this3._generatedMipmaps[level], function (face, faceIndex) {
              _this3._assignImage(face, level, faceIndex);
            });
          };
          for (var i = 0; i < nUpdate; ++i) {
            _loop();
          }
        };
        _proto.destroy = function destroy() {
          this._mipmaps = [];
          this._generatedMipmaps = [];
          this._mipmapAtlas = null;
          return _SimpleTexture.prototype.destroy.call(this);
        };
        _proto.releaseTexture = function releaseTexture() {
          this.destroy();
        };
        _proto._serialize = function _serialize(ctxForExporting) {
          return null;
        };
        _proto._deserialize = function _deserialize(serializedData, handle) {
          var data = serializedData;
          _SimpleTexture.prototype._deserialize.call(this, data.base, handle);
          this.isRGBE = data.rgbe;
          this._mipmapMode = data.mipmapMode;
          if (this._mipmapMode === MipmapMode.BAKED_CONVOLUTION_MAP) {
            var mipmapAtlas = data.mipmapAtlas;
            var mipmapLayout = data.mipmapLayout;
            this._mipmapAtlas = {
              atlas: {},
              layout: mipmapLayout
            };
            this._mipmapAtlas.atlas = {
              front: new ImageAsset(),
              back: new ImageAsset(),
              left: new ImageAsset(),
              right: new ImageAsset(),
              top: new ImageAsset(),
              bottom: new ImageAsset()
            };
            var imageAssetClassId = getClassId(ImageAsset);
            handle.result.push(this._mipmapAtlas.atlas, "front", mipmapAtlas.front, imageAssetClassId);
            handle.result.push(this._mipmapAtlas.atlas, "back", mipmapAtlas.back, imageAssetClassId);
            handle.result.push(this._mipmapAtlas.atlas, "left", mipmapAtlas.left, imageAssetClassId);
            handle.result.push(this._mipmapAtlas.atlas, "right", mipmapAtlas.right, imageAssetClassId);
            handle.result.push(this._mipmapAtlas.atlas, "top", mipmapAtlas.top, imageAssetClassId);
            handle.result.push(this._mipmapAtlas.atlas, "bottom", mipmapAtlas.bottom, imageAssetClassId);
          } else {
            this._mipmaps = new Array(data.mipmaps.length);
            for (var i = 0; i < data.mipmaps.length; ++i) {
              this._mipmaps[i] = {
                front: new ImageAsset(),
                back: new ImageAsset(),
                left: new ImageAsset(),
                right: new ImageAsset(),
                top: new ImageAsset(),
                bottom: new ImageAsset()
              };
              var mipmap = data.mipmaps[i];
              var _imageAssetClassId = getClassId(ImageAsset);
              handle.result.push(this._mipmaps[i], "front", mipmap.front, _imageAssetClassId);
              handle.result.push(this._mipmaps[i], "back", mipmap.back, _imageAssetClassId);
              handle.result.push(this._mipmaps[i], "left", mipmap.left, _imageAssetClassId);
              handle.result.push(this._mipmaps[i], "right", mipmap.right, _imageAssetClassId);
              handle.result.push(this._mipmaps[i], "top", mipmap.top, _imageAssetClassId);
              handle.result.push(this._mipmaps[i], "bottom", mipmap.bottom, _imageAssetClassId);
            }
          }
        };
        _proto._getGfxTextureCreateInfo = function _getGfxTextureCreateInfo(presumed) {
          var texInfo = new TextureInfo(TextureType.CUBE);
          texInfo.width = this._width;
          texInfo.height = this._height;
          texInfo.layerCount = 6;
          Object.assign(texInfo, presumed);
          return texInfo;
        };
        _proto._getGfxTextureViewCreateInfo = function _getGfxTextureViewCreateInfo(presumed) {
          var texViewInfo = new TextureViewInfo();
          texViewInfo.type = TextureType.CUBE;
          texViewInfo.baseLayer = 0;
          texViewInfo.layerCount = 6;
          Object.assign(texViewInfo, presumed);
          return texViewInfo;
        };
        _proto._uploadAtlas = function _uploadAtlas() {
          var _this4 = this;
          var layout = this._mipmapAtlas.layout;
          var mip0Layout = layout[0];
          this.reset({
            width: mip0Layout.width,
            height: mip0Layout.height,
            format: this._mipmapAtlas.atlas.front.format,
            mipmapLevel: layout.length
          });
          _forEachFace(this._mipmapAtlas.atlas, function (face, faceIndex) {
            var tex = new Texture2D();
            tex.image = face;
            tex.reset({
              width: face.width,
              height: face.height,
              format: face.format
            });
            tex.uploadData(face.data);
            for (var i = 0; i < layout.length; i++) {
              var layoutInfo = layout[i];
              var size = tex.getGFXTexture().size;
              var buffer = new Uint8Array(size);
              var region = new BufferTextureCopy();
              region.texOffset.x = layoutInfo.left;
              region.texOffset.y = layoutInfo.top;
              region.texExtent.width = layoutInfo.width;
              region.texExtent.height = layoutInfo.height;
              _this4._getGFXDevice().copyTextureToBuffers(tex.getGFXTexture(), [buffer], [region]);
              var bufferAsset = new ImageAsset({
                _data: buffer,
                _compressed: face.isCompressed,
                width: layoutInfo.width,
                height: layoutInfo.height,
                format: face.format
              });
              _this4._assignImage(bufferAsset, layoutInfo.level, faceIndex);
            }
          });
        };
        _proto.initDefault = function initDefault(uuid) {
          _SimpleTexture.prototype.initDefault.call(this, uuid);
          var imageAsset = new ImageAsset();
          imageAsset.initDefault();
          this.mipmaps = [{
            front: imageAsset,
            back: imageAsset,
            top: imageAsset,
            bottom: imageAsset,
            left: imageAsset,
            right: imageAsset
          }];
        };
        _proto.validate = function validate() {
          if (this._mipmapMode === MipmapMode.BAKED_CONVOLUTION_MAP) {
            if (this.mipmapAtlas === null || this.mipmapAtlas.layout.length === 0) {
              return false;
            }
            var atlas = this.mipmapAtlas.atlas;
            return !!(atlas.top && atlas.bottom && atlas.front && atlas.back && atlas.left && atlas.right);
          } else {
            return this._mipmaps.length !== 0 && !this._mipmaps.find(function (x) {
              return !(x.top && x.bottom && x.front && x.back && x.left && x.right);
            });
          }
        };
        _createClass(TextureCube, [{
          key: "mipmaps",
          get: function get() {
            return this._mipmaps;
          },
          set: function set(value) {
            this._mipmaps = value;
            var cubeMaps = [];
            if (value.length === 1) {
              var cubeMipmap = value[0];
              var front = cubeMipmap.front.extractMipmaps();
              var back = cubeMipmap.back.extractMipmaps();
              var left = cubeMipmap.left.extractMipmaps();
              var right = cubeMipmap.right.extractMipmaps();
              var top = cubeMipmap.top.extractMipmaps();
              var bottom = cubeMipmap.bottom.extractMipmaps();
              if (front.length !== back.length || front.length !== left.length || front.length !== right.length || front.length !== top.length || front.length !== bottom.length) {
                console.error('The number of mipmaps of each face is different.');
                this._setMipmapParams([]);
                return;
              }
              var level = front.length;
              for (var i = 0; i < level; ++i) {
                var cubeMap = {
                  front: front[i],
                  back: back[i],
                  left: left[i],
                  right: right[i],
                  top: top[i],
                  bottom: bottom[i]
                };
                cubeMaps.push(cubeMap);
              }
            } else if (value.length > 1) {
              value.forEach(function (mipmap) {
                var cubeMap = {
                  front: mipmap.front.extractMipmap0(),
                  back: mipmap.back.extractMipmap0(),
                  left: mipmap.left.extractMipmap0(),
                  right: mipmap.right.extractMipmap0(),
                  top: mipmap.top.extractMipmap0(),
                  bottom: mipmap.bottom.extractMipmap0()
                };
                cubeMaps.push(cubeMap);
              });
            }
            this._setMipmapParams(cubeMaps);
          }
        }, {
          key: "mipmapAtlas",
          get: function get() {
            return this._mipmapAtlas;
          },
          set: function set(value) {
            var _this5 = this;
            this._mipmapAtlas = value;
            if (!this._mipmapAtlas) {
              this.reset({
                width: 0,
                height: 0,
                mipmapLevel: 0
              });
              return;
            }
            var imageAtlasAsset = this._mipmapAtlas.atlas.front;
            if (!imageAtlasAsset.data) {
              return;
            }
            var faceAtlas = this._mipmapAtlas.atlas;
            var layout = this._mipmapAtlas.layout;
            var mip0Layout = layout[0];
            var ctx = Object.assign(ccwindow.document.createElement('canvas'), {
              width: imageAtlasAsset.width,
              height: imageAtlasAsset.height
            }).getContext('2d');
            this.reset({
              width: mip0Layout.width,
              height: mip0Layout.height,
              format: imageAtlasAsset.format,
              mipmapLevel: layout.length
            });
            var _loop2 = function _loop2() {
              var layoutInfo = layout[j];
              _forEachFace(faceAtlas, function (face, faceIndex) {
                ctx.clearRect(0, 0, imageAtlasAsset.width, imageAtlasAsset.height);
                var drawImg = face.data;
                ctx.drawImage(drawImg, 0, 0);
                var rawData = ctx.getImageData(layoutInfo.left, layoutInfo.top, layoutInfo.width, layoutInfo.height);
                var bufferAsset = new ImageAsset({
                  _data: rawData.data,
                  _compressed: face.isCompressed,
                  width: rawData.width,
                  height: rawData.height,
                  format: face.format
                });
                _this5._assignImage(bufferAsset, layoutInfo.level, faceIndex);
              });
            };
            for (var j = 0; j < layout.length; j++) {
              _loop2();
            }
          }
        }, {
          key: "image",
          get: function get() {
            return this._mipmaps.length === 0 ? null : this._mipmaps[0];
          },
          set: function set(value) {
            this.mipmaps = value ? [value] : [];
          }
        }]);
        return TextureCube;
      }(SimpleTexture), _class3$K.FaceIndex = FaceIndex, _class3$K), (_initializer$2j = applyDecoratedInitializer(_class2$2A.prototype, "isRGBE", [serializable$j], function () {
        return false;
      }), _initializer2$1N = applyDecoratedInitializer(_class2$2A.prototype, "_mipmapAtlas", [serializable$j], function () {
        return null;
      }), _initializer3$1c = applyDecoratedInitializer(_class2$2A.prototype, "_mipmapMode", [serializable$j], function () {
        return MipmapMode.NONE;
      }), _initializer4$X = applyDecoratedInitializer(_class2$2A.prototype, "_mipmaps", [serializable$j], function () {
        return [];
      })), _class2$2A)) || _class$2Q));
      legacyCC.TextureCube = TextureCube;
      function _forEachFace(mipmap, callback) {
        callback(mipmap.front, FaceIndex.front);
        callback(mipmap.back, FaceIndex.back);
        callback(mipmap.left, FaceIndex.left);
        callback(mipmap.right, FaceIndex.right);
        callback(mipmap.top, FaceIndex.top);
        callback(mipmap.bottom, FaceIndex.bottom);
      }

      var isMatchByWord = function isMatchByWord(path, test) {
        if (path.length > test.length) {
          var nextAscii = path.charCodeAt(test.length);
          return nextAscii === 47;
        }
        return true;
      };
      var processOptions = function processOptions(options) {
        var uuids = options.uuids;
        var paths = options.paths;
        var types = options.types;
        var bundles = options.deps;
        var realEntries = options.paths = Object.create(null);
        if (options.debug === false) {
          for (var i = 0, l = uuids.length; i < l; i++) {
            uuids[i] = decodeUuid(uuids[i]);
          }
          for (var id in paths) {
            var entry = paths[id];
            var type = entry[1];
            entry[1] = types[type];
          }
        } else {
          var out = Object.create(null);
          for (var _i = 0, _l = uuids.length; _i < _l; _i++) {
            var uuid = uuids[_i];
            uuids[_i] = out[uuid] = decodeUuid(uuid);
          }
          uuids = out;
        }
        for (var _id in paths) {
          var _entry = paths[_id];
          realEntries[uuids[_id]] = _entry;
        }
        var scenes = options.scenes;
        for (var name in scenes) {
          var _uuid = scenes[name];
          scenes[name] = uuids[_uuid];
        }
        var packs = options.packs;
        for (var packId in packs) {
          var packedIds = packs[packId];
          for (var j = 0; j < packedIds.length; ++j) {
            packedIds[j] = uuids[packedIds[j]];
          }
        }
        var versions = options.versions;
        if (versions) {
          for (var folder in versions) {
            var entries = versions[folder];
            for (var _i2 = 0; _i2 < entries.length; _i2 += 2) {
              var _uuid2 = entries[_i2];
              entries[_i2] = uuids[_uuid2] || _uuid2;
            }
          }
        }
        var redirect = options.redirect;
        if (redirect) {
          for (var _i3 = 0; _i3 < redirect.length; _i3 += 2) {
            redirect[_i3] = uuids[redirect[_i3]];
            redirect[_i3 + 1] = bundles[redirect[_i3 + 1]];
          }
        }
        var extensionMap = options.extensionMap;
        if (extensionMap) {
          var _loop = function _loop(ext) {
            if (!Object.prototype.hasOwnProperty.call(options.extensionMap, ext)) {
              return 1;
            }
            options.extensionMap[ext].forEach(function (uuid, index) {
              options.extensionMap[ext][index] = uuids[uuid] || uuid;
            });
          };
          for (var ext in options.extensionMap) {
            if (_loop(ext)) continue;
          }
        }
      };
      var Config = function () {
        function Config() {
          this.name = '';
          this.base = '';
          this.importBase = '';
          this.nativeBase = '';
          this.deps = null;
          this.assetInfos = new Cache();
          this.scenes = new Cache();
          this.paths = new Cache();
        }
        var _proto = Config.prototype;
        _proto.init = function init(options) {
          var _this = this;
          processOptions(options);
          this.importBase = options.importBase || '';
          this.nativeBase = options.nativeBase || '';
          this.base = options.base || '';
          this.name = options.name || '';
          this.deps = options.deps || [];
          this._initUuid(options.uuids);
          this._initPath(options.paths);
          this._initScene(options.scenes);
          this._initPackage(options.packs);
          this._initVersion(options.versions);
          this._initRedirect(options.redirect);
          var _loop2 = function _loop2(ext) {
            if (!Object.prototype.hasOwnProperty.call(options.extensionMap, ext)) {
              return 1;
            }
            options.extensionMap[ext].forEach(function (uuid) {
              var assetInfo = _this.assetInfos.get(uuid);
              if (assetInfo) {
                assetInfo.extension = ext;
              }
            });
          };
          for (var ext in options.extensionMap) {
            if (_loop2(ext)) continue;
          }
        };
        _proto.getInfoWithPath = function getInfoWithPath(path, type) {
          if (!path) {
            return null;
          }
          path = normalize(path);
          var items = this.paths.get(path);
          if (items) {
            if (type) {
              for (var i = 0, l = items.length; i < l; i++) {
                var assetInfo = items[i];
                if (isChildClassOf(assetInfo.ctor, type)) {
                  return assetInfo;
                }
              }
            } else {
              return items[0];
            }
          }
          return null;
        };
        _proto.getDirWithPath = function getDirWithPath(path, type, out) {
          path = normalize(path);
          if (path[path.length - 1] === '/') {
            path = path.slice(0, -1);
          }
          var infos = out || [];
          this.paths.forEach(function (items, p) {
            if (p.startsWith(path) && isMatchByWord(p, path) || !path) {
              for (var i = 0, l = items.length; i < l; i++) {
                var entry = items[i];
                if (!type || isChildClassOf(entry.ctor, type)) {
                  infos.push(entry);
                }
              }
            }
          });
          return infos;
        };
        _proto.getAssetInfo = function getAssetInfo(uuid) {
          return this.assetInfos.get(uuid) || null;
        };
        _proto.getSceneInfo = function getSceneInfo(name) {
          if (!name.endsWith('.scene')) {
            name += '.scene';
          }
          if (name[0] !== '/' && !name.startsWith('db://')) {
            name = "/" + name;
          }
          var info = this.scenes.find(function (val, key) {
            return key.endsWith(name);
          });
          return info;
        };
        _proto.destroy = function destroy() {
          this.paths.destroy();
          this.scenes.destroy();
          this.assetInfos.destroy();
        };
        _proto._initUuid = function _initUuid(uuidList) {
          if (!uuidList) {
            return;
          }
          this.assetInfos.clear();
          for (var i = 0, l = uuidList.length; i < l; i++) {
            var uuid = uuidList[i];
            this.assetInfos.add(uuid, {
              uuid: uuid
            });
          }
        };
        _proto._initPath = function _initPath(pathList) {
          if (!pathList) {
            return;
          }
          var paths = this.paths;
          paths.clear();
          for (var uuid in pathList) {
            var info = pathList[uuid];
            var path = info[0];
            var type = info[1];
            var isSubAsset = info.length === 3;
            var assetInfo = this.assetInfos.get(uuid);
            assetInfo.path = path;
            assetInfo.ctor = getClassById(type);
            if (paths.has(path)) {
              if (isSubAsset) {
                paths.get(path).push(assetInfo);
              } else {
                paths.get(path).unshift(assetInfo);
              }
            } else {
              paths.add(path, [assetInfo]);
            }
          }
        };
        _proto._initScene = function _initScene(sceneList) {
          if (!sceneList) {
            return;
          }
          var scenes = this.scenes;
          scenes.clear();
          var assetInfos = this.assetInfos;
          for (var sceneName in sceneList) {
            var uuid = sceneList[sceneName];
            var assetInfo = assetInfos.get(uuid);
            assetInfo.url = sceneName;
            scenes.add(sceneName, assetInfo);
          }
        };
        _proto._initPackage = function _initPackage(packageList) {
          if (!packageList) {
            return;
          }
          var assetInfos = this.assetInfos;
          for (var packUuid in packageList) {
            var uuids = packageList[packUuid];
            var pack = {
              uuid: packUuid,
              packedUuids: uuids,
              ext: '.json'
            };
            assetInfos.add(packUuid, pack);
            for (var i = 0, l = uuids.length; i < l; i++) {
              var uuid = uuids[i];
              var assetInfo = assetInfos.get(uuid);
              var assetPacks = assetInfo.packs;
              if (assetPacks) {
                if (l === 1) {
                  assetPacks.unshift(pack);
                } else {
                  assetPacks.push(pack);
                }
              } else {
                assetInfo.packs = [pack];
              }
            }
          }
        };
        _proto._initVersion = function _initVersion(versions) {
          if (!versions) {
            return;
          }
          var assetInfos = this.assetInfos;
          var entries = versions["import"];
          if (entries) {
            for (var i = 0, l = entries.length; i < l; i += 2) {
              var uuid = entries[i];
              var assetInfo = assetInfos.get(uuid);
              assetInfo.ver = entries[i + 1];
            }
          }
          entries = versions["native"];
          if (entries) {
            for (var _i4 = 0, _l2 = entries.length; _i4 < _l2; _i4 += 2) {
              var _uuid3 = entries[_i4];
              var _assetInfo = assetInfos.get(_uuid3);
              _assetInfo.nativeVer = entries[_i4 + 1];
            }
          }
        };
        _proto._initRedirect = function _initRedirect(redirect) {
          if (!redirect) {
            return;
          }
          var assetInfos = this.assetInfos;
          for (var i = 0, l = redirect.length; i < l; i += 2) {
            var uuid = redirect[i];
            var assetInfo = assetInfos.get(uuid);
            assetInfo.redirect = redirect[i + 1];
          }
        };
        return Config;
      }();

      function visitAsset(asset, deps) {
        if (!asset._uuid) {
          return;
        }
        deps.push(asset._uuid);
      }
      function visitComponent(comp, deps) {
        var props = Object.getOwnPropertyNames(comp);
        for (var i = 0; i < props.length; i++) {
          var propName = props[i];
          if (propName === 'node' || propName === '__eventTargets') {
            continue;
          }
          var value = comp[propName];
          if (typeof value === 'object' && value) {
            if (Array.isArray(value)) {
              for (var j = 0; j < value.length; j++) {
                var val = value[j];
                if (val instanceof Asset) {
                  visitAsset(val, deps);
                }
              }
            } else if (!value.constructor || value.constructor === Object) {
              var keys = Object.getOwnPropertyNames(value);
              for (var _j = 0; _j < keys.length; _j++) {
                var _val = value[keys[_j]];
                if (_val instanceof Asset) {
                  visitAsset(_val, deps);
                }
              }
            } else if (value instanceof Asset) {
              visitAsset(value, deps);
            }
          }
        }
      }
      function visitNode$1(node, deps) {
        for (var i = 0; i < node._components.length; i++) {
          visitComponent(node._components[i], deps);
        }
        for (var _i = 0; _i < node._children.length; _i++) {
          visitNode$1(node._children[_i], deps);
        }
      }
      function descendOpRef(asset, refs, exclude, op) {
        exclude.push(asset._uuid);
        var depends = dependUtil.getDeps(asset._uuid);
        for (var i = 0, l = depends.length; i < l; i++) {
          var dependAsset = assets.get(depends[i]);
          if (!dependAsset) {
            continue;
          }
          var uuid = dependAsset._uuid;
          if (!(uuid in refs)) {
            refs[uuid] = dependAsset.refCount + op;
          } else {
            refs[uuid] += op;
          }
          if (exclude.includes(uuid)) {
            continue;
          }
          descendOpRef(dependAsset, refs, exclude, op);
        }
      }
      var _temp = [];
      function checkCircularReference(asset) {
        var refs = Object.create(null);
        refs[asset._uuid] = asset.refCount;
        descendOpRef(asset, refs, _temp, -1);
        _temp.length = 0;
        if (refs[asset._uuid] !== 0) {
          return refs[asset._uuid];
        }
        for (var uuid in refs) {
          if (refs[uuid] !== 0) {
            descendOpRef(assets.get(uuid), refs, _temp, 1);
          }
        }
        _temp.length = 0;
        return refs[asset._uuid];
      }
      var ReleaseManager = function () {
        function ReleaseManager() {
          this._persistNodeDeps = new Cache();
          this._toDelete = new Cache();
          this._eventListener = false;
          this._dontDestroyAssets = [];
        }
        var _proto = ReleaseManager.prototype;
        _proto.addIgnoredAsset = function addIgnoredAsset(asset) {
          this._dontDestroyAssets.push(asset._uuid);
        };
        _proto.init = function init() {
          this._persistNodeDeps.clear();
          this._toDelete.clear();
        };
        _proto._addPersistNodeRef = function _addPersistNodeRef(node) {
          var deps = [];
          visitNode$1(node, deps);
          for (var i = 0, l = deps.length; i < l; i++) {
            var dependAsset = assets.get(deps[i]);
            if (dependAsset) {
              dependAsset.addRef();
            }
          }
          this._persistNodeDeps.add(node.uuid, deps);
        };
        _proto._removePersistNodeRef = function _removePersistNodeRef(node) {
          if (!this._persistNodeDeps.has(node.uuid)) {
            return;
          }
          var deps = this._persistNodeDeps.get(node.uuid);
          for (var i = 0, l = deps.length; i < l; i++) {
            var dependAsset = assets.get(deps[i]);
            if (dependAsset) {
              dependAsset.decRef();
            }
          }
          this._persistNodeDeps.remove(node.uuid);
        };
        _proto._autoRelease = function _autoRelease(oldScene, newScene, persistNodes) {
          if (oldScene) {
            var childs = dependUtil.getDeps(oldScene.uuid);
            for (var i = 0, l = childs.length; i < l; i++) {
              var asset = assets.get(childs[i]);
              if (asset) {
                asset.decRef(oldScene.autoReleaseAssets);
              }
            }
            var dependencies = dependUtil._depends.get(oldScene.uuid);
            if (dependencies && dependencies.persistDeps) {
              var persistDeps = dependencies.persistDeps;
              for (var _i2 = 0, _l = persistDeps.length; _i2 < _l; _i2++) {
                var _asset = assets.get(persistDeps[_i2]);
                if (_asset) {
                  _asset.decRef(oldScene.autoReleaseAssets);
                }
              }
            }
            if (oldScene.uuid !== newScene.uuid) {
              dependUtil.remove(oldScene.uuid);
            }
          }
          var sceneDeps = dependUtil._depends.get(newScene.uuid);
          if (sceneDeps) {
            sceneDeps.persistDeps = [];
          }
          for (var key in persistNodes) {
            var _ref;
            var node = persistNodes[key];
            var deps = this._persistNodeDeps.get(node.uuid);
            for (var _iterator = _createForOfIteratorHelperLoose(deps), _step; !(_step = _iterator()).done;) {
              var dep = _step.value;
              var dependAsset = assets.get(dep);
              if (dependAsset) {
                dependAsset.addRef();
              }
            }
            if (!sceneDeps) {
              continue;
            }
            (_ref = sceneDeps.persistDeps).push.apply(_ref, deps);
          }
        };
        _proto.tryRelease = function tryRelease(asset, force) {
          if (force === void 0) {
            force = false;
          }
          if (!(asset instanceof Asset)) {
            return;
          }
          if (force) {
            this._free(asset, force);
            return;
          }
          this._toDelete.add(asset._uuid, asset);
          if (!this._eventListener) {
            this._eventListener = true;
            callInNextTick(this._freeAssets.bind(this));
          }
        };
        _proto._freeAssets = function _freeAssets() {
          var _this = this;
          this._eventListener = false;
          this._toDelete.forEach(function (asset) {
            _this._free(asset);
          });
          this._toDelete.clear();
        };
        _proto._free = function _free(asset, force) {
          if (force === void 0) {
            force = false;
          }
          var uuid = asset._uuid;
          this._toDelete.remove(uuid);
          if (!isValid(asset, true) || this._dontDestroyAssets.indexOf(uuid) !== -1) {
            return;
          }
          if (!force) {
            if (asset.refCount > 0) {
              if (checkCircularReference(asset) > 0) {
                return;
              }
            }
          }
          assets.remove(uuid);
          var depends = dependUtil.getDeps(uuid);
          for (var i = 0, l = depends.length; i < l; i++) {
            var dependAsset = assets.get(depends[i]);
            if (dependAsset) {
              dependAsset.decRef(false);
              {
                this._free(dependAsset, false);
              }
            }
          }
          {
            asset.destroy();
          }
          dependUtil.remove(uuid);
        };
        return ReleaseManager;
      }();
      var releaseManager = new ReleaseManager();

      var defaultProgressCallback = null;
      function clear(task, clearRef) {
        for (var i = 0, l = task.input.length; i < l; i++) {
          var _item = task.input[i];
          if (clearRef) {
            if (!_item.isNative && _item.content instanceof Asset) {
              _item.content.decRef(false);
            }
          }
          _item.recycle();
        }
        task.input = null;
      }
      function urlAppendTimestamp(url, append) {
        if (append) {
          if (/\?/.test(url)) {
            return url + "&_t=" + Date.now();
          }
          return url + "?_t=" + Date.now();
        }
        return url;
      }
      function retry(process, times, wait, onComplete, index) {
        if (index === void 0) {
          index = 0;
        }
        process(index, function (err, result) {
          index++;
          if (!err || index > times) {
            if (onComplete) {
              onComplete(err, result);
            }
          } else {
            setTimeout(function () {
              retry(process, times, wait, onComplete, index);
            }, wait);
          }
        });
      }
      function getDepends(uuid, data, exclude, depends, config) {
        try {
          var info = dependUtil.parse(uuid, data);
          for (var i = 0, l = info.deps.length; i < l; i++) {
            var dep = info.deps[i];
            if (!(dep in exclude)) {
              exclude[dep] = true;
              depends.push({
                uuid: dep,
                bundle: config && config.name
              });
            }
          }
          if (info.nativeDep) {
            if (config) {
              info.nativeDep.bundle = config.name;
            }
            depends.push(_extends({}, info.nativeDep));
          }
        } catch (e) {
          error(e.message, e.stack);
        }
      }
      function cache(id, asset, cacheAsset) {
        if (!asset) {
          return;
        }
        cacheAsset = cacheAsset !== undefined ? cacheAsset : legacyCC.assetManager.cacheAsset;
        if (!isScene(asset) && cacheAsset && !asset.isDefault) {
          assets.add(id, asset);
        }
      }
      function setProperties(uuid, asset, assetsMap) {
        var missingAsset = false;
        var depends = dependMap.get(asset);
        if (depends) {
          var missingAssetReporter = null;
          for (var i = 0, l = depends.length; i < l; i++) {
            var depend = depends[i];
            var dependAsset = assetsMap[depend.uuid + "@import"];
            if (!dependAsset) {
              {
                error("The asset " + depend.uuid + " is missing!");
              }
              legacyCC.assetManager.dispatchAssetMissing(asset, depend.owner, depend.prop, depend.uuid);
              if (depend.type && depend.type !== Asset) {
                var placeHolder = new depend.type();
                placeHolder.initDefault(depend.uuid);
                depend.owner[depend.prop] = placeHolder;
              }
              missingAsset = true;
            } else {
              depend.owner[depend.prop] = dependAsset.addRef();
            }
          }
          if (missingAssetReporter) {
            missingAssetReporter.reportByOwner();
          }
          dependMap["delete"](asset);
        }
        if (nativeDependMap.has(asset)) {
          if (assetsMap[uuid + "@native"]) {
            asset._nativeAsset = assetsMap[uuid + "@native"];
          } else {
            missingAsset = true;
            console.error("the native asset of " + uuid + " is missing!");
          }
          nativeDependMap["delete"](asset);
        }
        return missingAsset;
      }
      function gatherAsset(task) {
        var source = task.source;
        if (!task.options.__outputAsArray__ && source.length === 1) {
          task.output = source[0].content;
        } else {
          var output = task.output = [];
          for (var i = 0, l = source.length; i < l; i++) {
            output.push(source[i].content);
          }
        }
      }
      function forEach(array, process, onComplete) {
        var count = 0;
        var errs = [];
        var length = array.length;
        if (length === 0 && onComplete) {
          onComplete(errs);
        }
        var cb = function cb(err) {
          if (err) {
            errs.push(err);
          }
          count++;
          if (count === length) {
            if (onComplete) {
              onComplete(errs);
            }
          }
        };
        for (var i = 0; i < length; i++) {
          process(array[i], cb);
        }
      }
      function parseParameters(options, onProgress, onComplete) {
        var optionsOut = options;
        var onProgressOut = onProgress;
        var onCompleteOut = onComplete;
        if (onComplete === undefined) {
          var isCallback = typeof options === 'function';
          if (onProgress) {
            onCompleteOut = onProgress;
            if (!isCallback) {
              onProgressOut = null;
            }
          } else if (onProgress === undefined && isCallback) {
            onCompleteOut = options;
            optionsOut = null;
            onProgressOut = null;
          }
          if (onProgress !== undefined && isCallback) {
            onProgressOut = options;
            optionsOut = null;
          }
        }
        return {
          options: optionsOut || Object.create(null),
          onProgress: onProgressOut,
          onComplete: onCompleteOut
        };
      }
      function parseLoadResArgs(type, onProgress, onComplete) {
        var typeOut = type;
        var onProgressOut = onProgress;
        var onCompleteOut = onComplete;
        if (onComplete === undefined) {
          var isValidType = isChildClassOf(type, Asset);
          if (onProgress) {
            onCompleteOut = onProgress;
            if (isValidType) {
              onProgressOut = null;
            }
          } else if (onProgress === undefined && !isValidType) {
            onCompleteOut = type;
            onProgressOut = null;
            typeOut = null;
          }
          if (onProgress !== undefined && !isValidType) {
            onProgressOut = type;
            typeOut = null;
          }
        }
        return {
          type: typeOut,
          onProgress: onProgressOut || defaultProgressCallback,
          onComplete: onCompleteOut
        };
      }
      function checkCircleReference(owner, uuid, map, checked) {
        if (checked === void 0) {
          checked = {};
        }
        var item = map[uuid];
        if (!item || checked[uuid]) {
          return false;
        }
        checked[uuid] = true;
        var result = false;
        var deps = dependUtil.getDeps(uuid);
        if (deps) {
          for (var i = 0, l = deps.length; i < l; i++) {
            var dep = deps[i];
            if (dep === owner || checkCircleReference(owner, dep, map, checked)) {
              result = true;
              break;
            }
          }
        }
        return result;
      }
      function asyncify(cb) {
        return function (p1, p2) {
          if (!cb) {
            return;
          }
          var refs = [];
          if (Array.isArray(p2)) {
            p2.forEach(function (x) {
              return x instanceof Asset && refs.push(x.addRef());
            });
          } else if (p2 instanceof Asset) {
            refs.push(p2.addRef());
          }
          callInNextTick(function () {
            refs.forEach(function (x) {
              return x.decRef(false);
            });
            cb(p1, p2);
          });
        };
      }

      var Bundle = function () {
        function Bundle() {
          this._config = new Config();
        }
        var _proto = Bundle.prototype;
        _proto.getInfoWithPath = function getInfoWithPath(path, type) {
          return this._config.getInfoWithPath(path, type);
        };
        _proto.getDirWithPath = function getDirWithPath(path, type, out) {
          return this._config.getDirWithPath(path, type, out);
        };
        _proto.getAssetInfo = function getAssetInfo(uuid) {
          return this._config.getAssetInfo(uuid);
        };
        _proto.getSceneInfo = function getSceneInfo(name) {
          return this._config.getSceneInfo(name);
        };
        _proto.init = function init(options) {
          this._config.init(options);
          bundles.add(options.name, this);
        };
        _proto.load = function load(paths, type, onProgress, onComplete) {
          var _parseLoadResArgs = parseLoadResArgs(type, onProgress, onComplete),
            _type = _parseLoadResArgs.type,
            onProg = _parseLoadResArgs.onProgress,
            onComp = _parseLoadResArgs.onComplete;
          var options = {
            __requestType__: RequestType.PATH,
            type: _type,
            bundle: this.name,
            __outputAsArray__: Array.isArray(paths)
          };
          legacyCC.assetManager.loadAny(paths, options, onProg, onComp);
        };
        _proto.preload = function preload(paths, type, onProgress, onComplete) {
          var _parseLoadResArgs2 = parseLoadResArgs(type, onProgress, onComplete),
            _type = _parseLoadResArgs2.type,
            onProg = _parseLoadResArgs2.onProgress,
            onComp = _parseLoadResArgs2.onComplete;
          legacyCC.assetManager.preloadAny(paths, {
            __requestType__: RequestType.PATH,
            type: _type,
            bundle: this.name
          }, onProg, onComp);
        };
        _proto.loadDir = function loadDir(dir, type, onProgress, onComplete) {
          var _parseLoadResArgs3 = parseLoadResArgs(type, onProgress, onComplete),
            _type = _parseLoadResArgs3.type,
            onProg = _parseLoadResArgs3.onProgress,
            onComp = _parseLoadResArgs3.onComplete;
          legacyCC.assetManager.loadAny(dir, {
            __requestType__: RequestType.DIR,
            type: _type,
            bundle: this.name,
            __outputAsArray__: true
          }, onProg, onComp);
        };
        _proto.preloadDir = function preloadDir(dir, type, onProgress, onComplete) {
          var _parseLoadResArgs4 = parseLoadResArgs(type, onProgress, onComplete),
            _type = _parseLoadResArgs4.type,
            onProg = _parseLoadResArgs4.onProgress,
            onComp = _parseLoadResArgs4.onComplete;
          legacyCC.assetManager.preloadAny(dir, {
            __requestType__: RequestType.DIR,
            type: _type,
            bundle: this.name
          }, onProg, onComp);
        };
        _proto.loadScene = function loadScene(sceneName, options, onProgress, onComplete) {
          var _parseParameters = parseParameters(options, onProgress, onComplete),
            opts = _parseParameters.options,
            onProg = _parseParameters.onProgress,
            onComp = _parseParameters.onComplete;
          opts.preset = opts.preset || 'scene';
          opts.bundle = this.name;
          legacyCC.assetManager.loadAny({
            scene: sceneName
          }, opts, onProg, function (err, sceneAsset) {
            if (err) {
              error(err.message, err.stack);
            } else if (sceneAsset.scene) {
              var scene = sceneAsset.scene;
              scene._id = sceneAsset._uuid;
              scene.name = sceneAsset.name;
            } else {
              err = new Error("The asset " + sceneAsset._uuid + " is not a scene");
            }
            if (onComp) {
              onComp(err, sceneAsset);
            }
          });
        };
        _proto.preloadScene = function preloadScene(sceneName, options, onProgress, onComplete) {
          var _parseParameters2 = parseParameters(options, onProgress, onComplete),
            opts = _parseParameters2.options,
            onProg = _parseParameters2.onProgress,
            onComp = _parseParameters2.onComplete;
          opts.bundle = this.name;
          legacyCC.assetManager.preloadAny({
            scene: sceneName
          }, opts, onProg, function (err) {
            if (err) {
              errorID(1210, sceneName, err.message);
            }
            if (onComp) {
              onComp(err);
            }
          });
        };
        _proto.get = function get(path, type) {
          var info = this.getInfoWithPath(path, type);
          if (info) {
            return assets.get(info.uuid) || null;
          }
          return null;
        };
        _proto.release = function release(path, type) {
          var asset = this.get(path, type);
          if (asset) {
            releaseManager.tryRelease(asset, true);
          }
        };
        _proto.releaseUnusedAssets = function releaseUnusedAssets() {
          var _this = this;
          assets.forEach(function (asset) {
            var info = _this.getAssetInfo(asset._uuid);
            if (info && !info.redirect) {
              releaseManager.tryRelease(asset);
            }
          });
        };
        _proto.releaseAll = function releaseAll() {
          var _this2 = this;
          assets.forEach(function (asset) {
            var info = _this2.getAssetInfo(asset._uuid);
            if (info && !info.redirect) {
              releaseManager.tryRelease(asset, true);
            }
          });
        };
        _proto._destroy = function _destroy() {
          this._config.destroy();
        };
        _createClass(Bundle, [{
          key: "config",
          get: function get() {
            return this._config;
          }
        }, {
          key: "name",
          get: function get() {
            return this._config.name;
          }
        }, {
          key: "deps",
          get: function get() {
            return this._config.deps;
          }
        }, {
          key: "base",
          get: function get() {
            return this._config.base;
          }
        }]);
        return Bundle;
      }();
      var resources = exports('ej', new Bundle());
      legacyCC.resources = resources;

      var CacheManager = function CacheManager() {
        this.cacheDir = void 0;
        this.cacheEnabled = void 0;
        this.autoClear = void 0;
        this.cacheInterval = void 0;
        this.deleteInterval = void 0;
        this.cachedFiles = void 0;
      };

      function downloadDomImage(url, options, onComplete) {
        var img = new ccwindow.Image();
        if (ccwindow.location.protocol !== 'file:' || XIAOMI) {
          img.crossOrigin = 'anonymous';
        }
        function loadCallback() {
          img.removeEventListener('load', loadCallback);
          img.removeEventListener('error', errorCallback);
          if (onComplete) {
            onComplete(null, img);
          }
        }
        function errorCallback() {
          img.removeEventListener('load', loadCallback);
          img.removeEventListener('error', errorCallback);
          if (onComplete) {
            onComplete(new Error(getError(4930, url)));
          }
        }
        img.addEventListener('load', loadCallback);
        img.addEventListener('error', errorCallback);
        img.src = url;
        return img;
      }

      function downloadFile(url, options, onProgress, onComplete) {
        var xhr = new XMLHttpRequest();
        var errInfo = "download failed: " + url + ", status: ";
        xhr.open('GET', url, true);
        if (options.xhrResponseType !== undefined) {
          xhr.responseType = options.xhrResponseType;
        }
        if (options.xhrWithCredentials !== undefined) {
          xhr.withCredentials = options.xhrWithCredentials;
        }
        if (options.xhrMimeType !== undefined && xhr.overrideMimeType) {
          xhr.overrideMimeType(options.xhrMimeType);
        }
        if (options.xhrTimeout !== undefined) {
          xhr.timeout = options.xhrTimeout;
        }
        if (options.xhrHeader) {
          for (var header in options.xhrHeader) {
            xhr.setRequestHeader(header, options.xhrHeader[header]);
          }
        }
        xhr.onload = function () {
          if (xhr.status === 200 || xhr.status === 0) {
            if (onComplete) {
              onComplete(null, xhr.response);
            }
          } else if (onComplete) {
            onComplete(new Error("" + errInfo + xhr.status + "(no response)"));
          }
        };
        if (onProgress) {
          xhr.onprogress = function (e) {
            if (e.lengthComputable) {
              onProgress(e.loaded, e.total);
            }
          };
        }
        xhr.onerror = function () {
          if (onComplete) {
            onComplete(new Error("" + errInfo + xhr.status + "(error)"));
          }
        };
        xhr.ontimeout = function () {
          if (onComplete) {
            onComplete(new Error("" + errInfo + xhr.status + "(time out)"));
          }
        };
        xhr.onabort = function () {
          if (onComplete) {
            onComplete(new Error("" + errInfo + xhr.status + "(abort)"));
          }
        };
        xhr.send(null);
        return xhr;
      }

      var ccdocument$2 = ccwindow.document;
      var downloaded = {};
      function downloadScript(url, options, onComplete) {
        if (downloaded[url]) {
          if (onComplete) {
            onComplete(null);
          }
          return null;
        }
        var script = ccdocument$2.createElement('script');
        if (ccwindow.location.protocol !== 'file:') {
          script.crossOrigin = 'anonymous';
        }
        script.async = options.scriptAsyncLoading || false;
        script.src = url;
        function loadHandler() {
          script.parentNode.removeChild(script);
          script.removeEventListener('load', loadHandler, false);
          script.removeEventListener('error', errorHandler, false);
          downloaded[url] = true;
          if (onComplete) {
            onComplete(null);
          }
        }
        function errorHandler() {
          script.parentNode.removeChild(script);
          script.removeEventListener('load', loadHandler, false);
          script.removeEventListener('error', errorHandler, false);
          if (onComplete) {
            onComplete(new Error(getError(4928, url)));
          }
        }
        script.addEventListener('load', loadHandler, false);
        script.addEventListener('error', errorHandler, false);
        ccdocument$2.body.appendChild(script);
        return script;
      }

      var REGEX = /^(?:\w+:\/\/|\.+\/).+/;
      var downloadImage = function downloadImage(url, options, onComplete) {
        var func = sys.hasFeature(sys.Feature.IMAGE_BITMAP) && legacyCC.assetManager.allowImageBitmap ? downloadBlob : downloadDomImage;
        func(url, options, onComplete);
      };
      var downloadBlob = function downloadBlob(url, options, onComplete) {
        options.xhrResponseType = 'blob';
        downloadFile(url, options, options.onFileProgress, onComplete);
      };
      var downloadJson = function downloadJson(url, options, onComplete) {
        options.xhrResponseType = 'json';
        downloadFile(url, options, options.onFileProgress, onComplete);
      };
      var downloadArrayBuffer = function downloadArrayBuffer(url, options, onComplete) {
        options.xhrResponseType = 'arraybuffer';
        downloadFile(url, options, options.onFileProgress, onComplete);
      };
      var downloadCCON = function downloadCCON(url, options, onComplete) {
        downloader._downloadJson(url, options, function (err, json) {
          if (err) {
            onComplete(err);
            return;
          }
          var cconPreface = parseCCONJson(json);
          var chunkPromises = Promise.all(cconPreface.chunks.map(function (chunk) {
            return new Promise(function (resolve, reject) {
              downloader._downloadArrayBuffer("" + mainFileName(url) + chunk, {}, function (errChunk, chunkBuffer) {
                if (err) {
                  reject(err);
                } else {
                  resolve(new Uint8Array(chunkBuffer));
                }
              });
            });
          }));
          chunkPromises.then(function (chunks) {
            var ccon = new CCON(cconPreface.document, chunks);
            onComplete(null, ccon);
          })["catch"](function (err) {
            onComplete(err);
          });
        });
      };
      var downloadCCONB = function downloadCCONB(url, options, onComplete) {
        downloader._downloadArrayBuffer(url, options, function (err, arrayBuffer) {
          if (err) {
            onComplete(err);
            return;
          }
          try {
            var ccon = decodeCCONBinary(new Uint8Array(arrayBuffer));
            onComplete(null, ccon);
          } catch (err) {
            onComplete(err);
          }
        });
      };
      var downloadText = function downloadText(url, options, onComplete) {
        options.xhrResponseType = 'text';
        downloadFile(url, options, options.onFileProgress, onComplete);
      };
      var downloadBundle = function downloadBundle(nameOrUrl, options, onComplete) {
        var bundleName = basename(nameOrUrl);
        var url = nameOrUrl;
        if (!REGEX.test(url)) {
          if (downloader.remoteBundles.indexOf(bundleName) !== -1) {
            url = downloader.remoteServerAddress + "remote/" + bundleName;
          } else {
            url = "assets/" + bundleName;
          }
        }
        var version = options.version || downloader.bundleVers[bundleName];
        var count = 0;
        var config = url + "/config." + (version ? version + "." : '') + "json";
        var out = null;
        var error = null;
        downloadJson(config, options, function (err, response) {
          error = err || error;
          out = response;
          if (out) {
            out.base = url + "/";
          }
          if (++count === 2) {
            onComplete(error, out);
          }
        });
        var jspath = url + "/index." + (version ? version + "." : '') + "js";
        downloadScript(jspath, options, function (err) {
          error = err || error;
          if (++count === 2) {
            onComplete(error, out);
          }
        });
      };
      var Downloader = function () {
        var _proto = Downloader.prototype;
        _proto.init = function init(remoteServerAddress, bundleVers, remoteBundles) {
          if (remoteServerAddress === void 0) {
            remoteServerAddress = '';
          }
          if (bundleVers === void 0) {
            bundleVers = {};
          }
          if (remoteBundles === void 0) {
            remoteBundles = [];
          }
          this._downloading.clear();
          this._queue.length = 0;
          this._remoteServerAddress = remoteServerAddress;
          this.bundleVers = bundleVers;
          this.remoteBundles = remoteBundles;
        };
        _proto.register = function register(type, handler) {
          if (typeof type === 'object') {
            mixin(this._downloaders, type);
          } else {
            this._downloaders[type] = handler;
          }
        };
        _proto.download = function download(id, url, type, options, onComplete) {
          var _this = this;
          var file = files.get(id);
          if (file) {
            onComplete(null, file);
            return;
          }
          var downloadCallbacks = this._downloading.get(id);
          if (downloadCallbacks) {
            downloadCallbacks.push(onComplete);
            var request = this._queue.find(function (x) {
              return x.id === id;
            });
            if (!request) {
              return;
            }
            var priority = options.priority || 0;
            if (request.priority < priority) {
              request.priority = priority;
              this._queueDirty = true;
            }
            return;
          }
          var maxRetryCount = typeof options.maxRetryCount !== 'undefined' ? options.maxRetryCount : this.maxRetryCount;
          var maxConcurrency = typeof options.maxConcurrency !== 'undefined' ? options.maxConcurrency : this.maxConcurrency;
          var maxRequestsPerFrame = typeof options.maxRequestsPerFrame !== 'undefined' ? options.maxRequestsPerFrame : this.maxRequestsPerFrame;
          var handler = this._downloaders[type] || this._downloaders["default"];
          var process = function process(index, callback) {
            if (index === 0) {
              _this._downloading.add(id, [onComplete]);
            }
            if (!_this.limited) {
              handler(urlAppendTimestamp(url, _this.appendTimeStamp), options, callback);
              return;
            }
            _this._updateTime();
            var done = function done(err, data) {
              _this._totalNum--;
              _this._handleQueueInNextFrame(maxConcurrency, maxRequestsPerFrame);
              callback(err, data);
            };
            if (_this._totalNum < maxConcurrency && _this._totalNumThisPeriod < maxRequestsPerFrame) {
              handler(urlAppendTimestamp(url, _this.appendTimeStamp), options, done);
              _this._totalNum++;
              _this._totalNumThisPeriod++;
            } else {
              _this._queue.push({
                id: id,
                priority: options.priority || 0,
                url: url,
                options: options,
                done: done,
                handler: handler
              });
              _this._queueDirty = true;
              if (_this._totalNum < maxConcurrency) {
                _this._handleQueueInNextFrame(maxConcurrency, maxRequestsPerFrame);
              }
            }
          };
          var finale = function finale(err, result) {
            if (!err) {
              files.add(id, result);
            }
            var callbacks = _this._downloading.remove(id);
            for (var i = 0, l = callbacks.length; i < l; i++) {
              callbacks[i](err, result);
            }
          };
          retry(process, maxRetryCount, this.retryInterval, finale);
        };
        _proto.loadSubpackage = function loadSubpackage(name, completeCallback) {
          legacyCC.assetManager.loadBundle(name, null, completeCallback);
        };
        function Downloader() {
          this.maxConcurrency = 15;
          this.maxRequestsPerFrame = 15;
          this.maxRetryCount = 3 ;
          this.appendTimeStamp = !!EDITOR_NOT_IN_PREVIEW;
          this.limited = !EDITOR;
          this.retryInterval = 2000;
          this.bundleVers = {};
          this.remoteBundles = [];
          this.downloadDomImage = downloadDomImage;
          this.downloadDomAudio = null;
          this.downloadFile = downloadFile;
          this.downloadScript = downloadScript;
          this._downloadArrayBuffer = downloadArrayBuffer;
          this._downloadJson = downloadJson;
          this._downloaders = {
            '.png': downloadImage,
            '.jpg': downloadImage,
            '.bmp': downloadImage,
            '.jpeg': downloadImage,
            '.gif': downloadImage,
            '.ico': downloadImage,
            '.tiff': downloadImage,
            '.webp': downloadImage,
            '.image': downloadImage,
            '.pvr': downloadArrayBuffer,
            '.pkm': downloadArrayBuffer,
            '.astc': downloadArrayBuffer,
            '.txt': downloadText,
            '.xml': downloadText,
            '.vsh': downloadText,
            '.fsh': downloadText,
            '.atlas': downloadText,
            '.tmx': downloadText,
            '.tsx': downloadText,
            '.json': downloadJson,
            '.ExportJson': downloadJson,
            '.plist': downloadText,
            '.ccon': downloadCCON,
            '.cconb': downloadCCONB,
            '.fnt': downloadText,
            '.binary': downloadArrayBuffer,
            '.bin': downloadArrayBuffer,
            '.dbbin': downloadArrayBuffer,
            '.skel': downloadArrayBuffer,
            '.js': downloadScript,
            bundle: downloadBundle,
            "default": downloadText
          };
          this._downloading = new Cache();
          this._queue = [];
          this._queueDirty = false;
          this._totalNum = 0;
          this._totalNumThisPeriod = 0;
          this._lastDate = -1;
          this._checkNextPeriod = false;
          this._remoteServerAddress = '';
          this._maxInterval = 1 / 30;
        }
        _proto._updateTime = function _updateTime() {
          var now = performance.now();
          var deltaTime = legacyCC.game.deltaTime;
          var interval = deltaTime > this._maxInterval ? this._maxInterval : deltaTime;
          if (now - this._lastDate > interval * 1000) {
            this._totalNumThisPeriod = 0;
            this._lastDate = now;
          }
        };
        _proto._handleQueue = function _handleQueue(maxConcurrency, maxRequestsPerFrame) {
          this._checkNextPeriod = false;
          this._updateTime();
          while (this._queue.length > 0 && this._totalNum < maxConcurrency && this._totalNumThisPeriod < maxRequestsPerFrame) {
            if (this._queueDirty) {
              this._queue.sort(function (a, b) {
                return a.priority - b.priority;
              });
              this._queueDirty = false;
            }
            var request = this._queue.pop();
            if (!request) {
              break;
            }
            this._totalNum++;
            this._totalNumThisPeriod++;
            request.handler(urlAppendTimestamp(request.url, this.appendTimeStamp), request.options, request.done);
          }
          this._handleQueueInNextFrame(maxConcurrency, maxRequestsPerFrame);
        };
        _proto._handleQueueInNextFrame = function _handleQueueInNextFrame(maxConcurrency, maxRequestsPerFrame) {
          if (!this._checkNextPeriod && this._queue.length > 0) {
            callInNextTick(this._handleQueue.bind(this), maxConcurrency, maxRequestsPerFrame);
            this._checkNextPeriod = true;
          }
        };
        _createClass(Downloader, [{
          key: "remoteServerAddress",
          get: function get() {
            return this._remoteServerAddress;
          }
        }], [{
          key: "instance",
          get: function get() {
            if (!Downloader._instance) {
              Downloader._instance = new Downloader();
            }
            return Downloader._instance;
          }
        }]);
        return Downloader;
      }();
      Downloader._instance = void 0;
      var downloader = Downloader.instance;
      var downloader$1 = Downloader.instance;

      var _dec$2T, _class$2P, _class2$2z, _initializer$2i;
      var JsonAsset = exports('e7', (_dec$2T = ccclass$n('cc.JsonAsset'), _dec$2T(_class$2P = (_class2$2z = function (_Asset) {
        _inheritsLoose(JsonAsset, _Asset);
        function JsonAsset() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Asset.call.apply(_Asset, [this].concat(args)) || this;
          _this.json = _initializer$2i && _initializer$2i();
          return _this;
        }
        return JsonAsset;
      }(Asset), (_initializer$2i = applyDecoratedInitializer(_class2$2z.prototype, "json", [serializable$j], function () {
        return null;
      })), _class2$2z)) || _class$2P));
      legacyCC.JsonAsset = JsonAsset;

      var _dec$2S, _class$2O, _class2$2y, _initializer$2h;
      var TextAsset = exports('e6', (_dec$2S = ccclass$n('cc.TextAsset'), _dec$2S(_class$2O = (_class2$2y = function (_Asset) {
        _inheritsLoose(TextAsset, _Asset);
        function TextAsset() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Asset.call.apply(_Asset, [this].concat(args)) || this;
          _this.text = _initializer$2h && _initializer$2h();
          return _this;
        }
        var _proto = TextAsset.prototype;
        _proto.toString = function toString() {
          return this.text;
        };
        return TextAsset;
      }(Asset), (_initializer$2h = applyDecoratedInitializer(_class2$2y.prototype, "text", [serializable$j], function () {
        return '';
      })), _class2$2y)) || _class$2O));
      legacyCC.TextAsset = TextAsset;

      var _dec$2R, _class$2N, _class2$2x;
      var BufferAsset = exports('e3', (_dec$2R = ccclass$n('cc.BufferAsset'), _dec$2R(_class$2N = (_class2$2x = function (_Asset) {
        _inheritsLoose(BufferAsset, _Asset);
        function BufferAsset() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Asset.call.apply(_Asset, [this].concat(args)) || this;
          _this._buffer = null;
          return _this;
        }
        var _proto = BufferAsset.prototype;
        _proto.buffer = function buffer() {
          assertIsNonNullable(this._buffer);
          return this._buffer;
        };
        _proto.validate = function validate() {
          return !!this._buffer;
        };
        _createClass(BufferAsset, [{
          key: "_nativeAsset",
          get: function get() {
            return this._buffer;
          },
          set: function set(bin) {
            if (bin instanceof ArrayBuffer) {
              this._buffer = bin;
            } else {
              this._buffer = bin.buffer;
            }
          }
        }]);
        return BufferAsset;
      }(Asset), (_applyDecoratedDescriptor(_class2$2x.prototype, "_nativeAsset", [override], Object.getOwnPropertyDescriptor(_class2$2x.prototype, "_nativeAsset"), _class2$2x.prototype)), _class2$2x)) || _class$2N));
      legacyCC.BufferAsset = BufferAsset;

      function createImageAsset(id, data, options, onComplete) {
        var out = null;
        var err = null;
        try {
          out = new ImageAsset();
          out._nativeUrl = id;
          out._nativeAsset = data;
        } catch (e) {
          err = e;
        }
        onComplete(err, out);
      }
      function createJsonAsset(id, data, options, onComplete) {
        var out = new JsonAsset();
        out.json = data;
        onComplete(null, out);
      }
      function createTextAsset(id, data, options, onComplete) {
        var out = new TextAsset();
        out.text = data;
        onComplete(null, out);
      }
      function createBufferAsset(id, data, options, onComplete) {
        var out = new BufferAsset();
        out._nativeUrl = id;
        out._nativeAsset = data;
        onComplete(null, out);
      }
      function createAsset(id, data, options, onComplete) {
        var out = new Asset();
        out._nativeUrl = id;
        out._nativeAsset = data;
        onComplete(null, out);
      }
      function createBundle(id, data, options, onComplete) {
        var bundle = bundles.get(data.name);
        if (!bundle) {
          bundle = data.name === BuiltinBundleName.RESOURCES ? resources : new Bundle();
          data.base = data.base || id + "/";
          bundle.init(data);
        }
        {
          module.import("virtual:///prerequisite-imports/" + bundle.name).then(function () {
            onComplete(null, bundle);
          })["catch"](onComplete);
        }
      }
      var Factory = function () {
        function Factory() {
          this._creating = new Cache();
          this._producers = {
            '.png': createImageAsset,
            '.jpg': createImageAsset,
            '.bmp': createImageAsset,
            '.jpeg': createImageAsset,
            '.gif': createImageAsset,
            '.ico': createImageAsset,
            '.tiff': createImageAsset,
            '.webp': createImageAsset,
            '.image': createImageAsset,
            '.pvr': createImageAsset,
            '.pkm': createImageAsset,
            '.txt': createTextAsset,
            '.xml': createTextAsset,
            '.vsh': createTextAsset,
            '.fsh': createTextAsset,
            '.atlas': createTextAsset,
            '.tmx': createTextAsset,
            '.tsx': createTextAsset,
            '.fnt': createTextAsset,
            '.json': createJsonAsset,
            '.ExportJson': createJsonAsset,
            '.binary': createBufferAsset,
            '.bin': createBufferAsset,
            '.dbbin': createBufferAsset,
            '.skel': createBufferAsset,
            bundle: createBundle,
            "default": createAsset
          };
        }
        var _proto = Factory.prototype;
        _proto.register = function register(type, handler) {
          if (typeof type === 'object') {
            mixin(this._producers, type);
          } else {
            this._producers[type] = handler;
          }
        };
        _proto.create = function create(id, data, type, options, onComplete) {
          var _this = this;
          var handler = this._producers[type] || this._producers["default"];
          var asset = assets.get(id);
          if (!options.reloadAsset && asset) {
            onComplete(null, asset);
            return;
          }
          var creating = this._creating.get(id);
          if (creating) {
            creating.push(onComplete);
            return;
          }
          this._creating.add(id, [onComplete]);
          handler(id, data, options, function (err, result) {
            if (!err && result instanceof Asset) {
              result._uuid = id;
              cache(id, result, options.cacheAsset);
            }
            var callbacks = _this._creating.remove(id);
            for (var i = 0, l = callbacks.length; i < l; i++) {
              callbacks[i](err, result);
            }
          });
        };
        return Factory;
      }();
      var factory = new Factory();

      var PackManager = function () {
        function PackManager() {
          this._loading = new Cache();
          this._unpackers = {
            '.json': this.unpackJson
          };
        }
        var _proto = PackManager.prototype;
        _proto.unpackJson = function unpackJson(pack, json, options, onComplete) {
          var out = createMap(true);
          var err = null;
          if (Array.isArray(json)) {
            json = unpackJSONs(json);
            if (json.length !== pack.length) {
              errorID(4915);
            }
            for (var i = 0; i < pack.length; i++) {
              out[pack[i] + "@import"] = json[i];
            }
          } else {
            var textureType = getClassId(Texture2D);
            var imageAssetType = getClassId(ImageAsset);
            if (json.type === textureType && json.data) {
              var datas = json.data;
              if (datas.length !== pack.length) {
                errorID(4915);
              }
              for (var _i = 0; _i < pack.length; _i++) {
                out[pack[_i] + "@import"] = packCustomObjData(textureType, {
                  base: datas[_i][0],
                  mipmaps: datas[_i][1]
                });
              }
            } else if (json.type === imageAssetType && json.data) {
              var _datas = json.data;
              if (_datas.length !== pack.length) {
                errorID(4915);
              }
              for (var _i2 = 0; _i2 < pack.length; _i2++) {
                out[pack[_i2] + "@import"] = _datas[_i2];
              }
            } else {
              err = new Error('unmatched type pack!');
              onComplete(err, null);
              return;
            }
          }
          onComplete(err, out);
        };
        _proto.init = function init() {
          this._loading.clear();
        };
        _proto.register = function register(type, handler) {
          if (typeof type === 'object') {
            mixin(this._unpackers, type);
          } else {
            this._unpackers[type] = handler;
          }
        };
        _proto.unpack = function unpack(pack, data, type, options, onComplete) {
          if (!data) {
            onComplete(new Error('package data is wrong!'));
            return;
          }
          var unpacker = this._unpackers[type];
          unpacker(pack, data, options, onComplete);
        };
        _proto.load = function load(item, options, onComplete) {
          var _this = this;
          if (item.isNative || !item.info || !item.info.packs) {
            downloader$1.download(item.id, item.url, item.ext, item.options, onComplete);
            return;
          }
          if (files.has(item.id)) {
            onComplete(null, files.get(item.id));
            return;
          }
          var packs = item.info.packs;
          var loadingPack = packs.find(function (val) {
            return _this._loading.has(val.uuid);
          });
          if (loadingPack) {
            var req = this._loading.get(loadingPack.uuid);
            assertIsTrue(req);
            req.push({
              onComplete: onComplete,
              id: item.id
            });
            return;
          }
          var pack = packs[0];
          this._loading.add(pack.uuid, [{
            onComplete: onComplete,
            id: item.id
          }]);
          assertIsTrue(item.config);
          var url = transform(pack.uuid, {
            ext: pack.ext,
            bundle: item.config.name
          });
          downloader$1.download(pack.uuid, url, pack.ext, item.options, function (err, data) {
            files.remove(pack.uuid);
            if (err) {
              error(err.message, err.stack);
            }
            _this.unpack(pack.packedUuids, data, pack.ext, item.options, function (err2, result) {
              if (!err2) {
                for (var id in result) {
                  files.add(id, result[id]);
                }
              }
              var callbacks = _this._loading.remove(pack.uuid);
              assertIsTrue(callbacks);
              for (var i = 0, l = callbacks.length; i < l; i++) {
                var cb = callbacks[i];
                if (err || err2) {
                  cb.onComplete(err || err2);
                  continue;
                }
                var unpackedData = result[cb.id];
                if (!unpackedData) {
                  cb.onComplete(new Error('can not retrieve data from package'));
                } else {
                  cb.onComplete(null, unpackedData);
                }
              }
            });
          });
        };
        return PackManager;
      }();
      var packManager = new PackManager();

      function fetch$1(task, done) {
        var firstTask = false;
        if (!task.progress) {
          task.progress = {
            finish: 0,
            total: task.input.length,
            canInvoke: true
          };
          firstTask = true;
        }
        var options = task.options,
          progress = task.progress;
        var depends = [];
        var total = progress.total;
        var exclude = options.__exclude__ = options.__exclude__ || Object.create(null);
        task.output = [];
        forEach(task.input, function (item, cb) {
          if (!item.isNative && assets.has(item.uuid)) {
            var asset = assets.get(item.uuid);
            item.content = asset.addRef();
            task.output.push(item);
            if (progress.canInvoke) {
              task.dispatch('progress', ++progress.finish, progress.total, item);
            }
            cb();
            return;
          }
          packManager.load(item, task.options, function (err, data) {
            if (err) {
              if (!task.isFinished) {
                if (!legacyCC.assetManager.force || firstTask) {
                  error(err.message, err.stack);
                  progress.canInvoke = false;
                  done(err);
                } else {
                  task.output.push(item);
                  if (progress.canInvoke) {
                    task.dispatch('progress', ++progress.finish, progress.total, item);
                  }
                }
              }
            } else if (!task.isFinished) {
              item.file = data;
              task.output.push(item);
              if (!item.isNative) {
                exclude[item.uuid] = true;
                getDepends(item.uuid, data, exclude, depends, item.config);
                progress.total = total + depends.length;
              }
              if (progress.canInvoke) {
                task.dispatch('progress', ++progress.finish, progress.total, item);
              }
            }
            cb();
          });
        }, function () {
          if (task.isFinished) {
            clear(task, true);
            task.dispatch('error');
            return;
          }
          if (depends.length > 0) {
            var subTask = Task.create({
              input: depends,
              progress: progress,
              options: options,
              onProgress: task.onProgress,
              onError: Task.prototype.recycle,
              onComplete: function onComplete(err) {
                if (!err) {
                  var _task$output;
                  (_task$output = task.output).push.apply(_task$output, subTask.output);
                  subTask.recycle();
                }
                if (firstTask) {
                  decreaseRef(task);
                }
                done(err);
              }
            });
            fetchPipeline.async(subTask);
            return;
          }
          if (firstTask) {
            decreaseRef(task);
          }
          done();
        });
      }
      function decreaseRef(task) {
        var output = task.output;
        for (var i = 0, l = output.length; i < l; i++) {
          if (output[i].content) {
            output[i].content.decRef(false);
          }
        }
      }

      var SAXParser = function () {
        function SAXParser() {
          this._parser = null;
          if (globalThis.DOMParser) {
            this._parser = new DOMParser();
          }
        }
        var _proto = SAXParser.prototype;
        _proto.parse = function parse(xmlTxt) {
          return this._parseXML(xmlTxt);
        };
        _proto._parseXML = function _parseXML(textxml) {
          if (this._parser) {
            return this._parser.parseFromString(textxml, 'text/xml');
          }
          throw new Error('Dom parser is not supported in this platform!');
        };
        return SAXParser;
      }();
      var PlistParser = function (_SAXParser) {
        _inheritsLoose(PlistParser, _SAXParser);
        function PlistParser() {
          return _SAXParser.apply(this, arguments) || this;
        }
        var _proto2 = PlistParser.prototype;
        _proto2.parse = function parse(xmlTxt) {
          var xmlDoc = this._parseXML(xmlTxt);
          var plist = xmlDoc.documentElement;
          if (plist.tagName !== 'plist') {
            warnID(5100);
            return {};
          }
          var node = null;
          for (var i = 0, len = plist.childNodes.length; i < len; i++) {
            node = plist.childNodes[i];
            if (node.nodeType === 1) {
              break;
            }
          }
          return this._parseNode(node);
        };
        _proto2._parseNode = function _parseNode(node) {
          var data = null;
          var tagName = node.tagName;
          if (tagName === 'dict') {
            data = this._parseDict(node);
          } else if (tagName === 'array') {
            data = this._parseArray(node);
          } else if (tagName === 'string') {
            if (node.childNodes.length === 1) {
              data = node.firstChild.nodeValue;
            } else {
              data = '';
              for (var i = 0; i < node.childNodes.length; i++) {
                data += node.childNodes[i].nodeValue;
              }
            }
          } else if (tagName === 'false') {
            data = false;
          } else if (tagName === 'true') {
            data = true;
          } else if (tagName === 'real') {
            data = parseFloat(node.firstChild.nodeValue);
          } else if (tagName === 'integer') {
            data = parseInt(node.firstChild.nodeValue, 10);
          }
          return data;
        };
        _proto2._parseArray = function _parseArray(node) {
          var data = [];
          for (var i = 0, len = node.childNodes.length; i < len; i++) {
            var child = node.childNodes[i];
            if (child.nodeType !== 1) {
              continue;
            }
            data.push(this._parseNode(child));
          }
          return data;
        };
        _proto2._parseDict = function _parseDict(node) {
          var data = {};
          var key = '';
          for (var i = 0, len = node.childNodes.length; i < len; i++) {
            var child = node.childNodes[i];
            if (child.nodeType !== 1) {
              continue;
            }
            if (child.tagName === 'key') {
              key = child.firstChild.nodeValue;
            } else {
              data[key] = this._parseNode(child);
            }
          }
          return data;
        };
        return PlistParser;
      }(SAXParser);
      var plistParser = new PlistParser();

      var Parser$1 = function () {
        function Parser() {
          this._parsing = new Cache();
          this._parsers = {
            '.png': this.parseImage,
            '.jpg': this.parseImage,
            '.bmp': this.parseImage,
            '.jpeg': this.parseImage,
            '.gif': this.parseImage,
            '.ico': this.parseImage,
            '.tiff': this.parseImage,
            '.webp': this.parseImage,
            '.image': this.parseImage,
            '.pvr': this.parsePVRTex,
            '.pkm': this.parsePKMTex,
            '.astc': this.parseASTCTex,
            '.plist': this.parsePlist,
            "import": this.parseImport,
            '.ccon': this.parseImport,
            '.cconb': this.parseImport
          };
        }
        var _proto = Parser.prototype;
        _proto.parseImage = function parseImage(file, options, onComplete) {
          if (file instanceof HTMLImageElement) {
            onComplete(null, file);
            return;
          }
          createImageBitmap(file, {
            premultiplyAlpha: 'none'
          }).then(function (result) {
            onComplete(null, result);
          }, function (err) {
            onComplete(err, null);
          });
        };
        _proto.parsePVRTex = function parsePVRTex(file, options, onComplete) {
          var err = null;
          var out = null;
          try {
            out = ImageAsset.parseCompressedTextures(file, 0);
          } catch (e) {
            err = e;
            console.warn(err);
          }
          onComplete(err, out);
        };
        _proto.parsePKMTex = function parsePKMTex(file, options, onComplete) {
          var err = null;
          var out = null;
          try {
            out = ImageAsset.parseCompressedTextures(file, 1);
          } catch (e) {
            err = e;
            console.warn(err);
          }
          onComplete(err, out);
        };
        _proto.parseASTCTex = function parseASTCTex(file, options, onComplete) {
          var err = null;
          var out = null;
          try {
            out = ImageAsset.parseCompressedTextures(file, 2);
          } catch (e) {
            err = e;
            console.warn(err);
          }
          onComplete(err, out);
        };
        _proto.parsePlist = function parsePlist(file, options, onComplete) {
          var err = null;
          var result = plistParser.parse(file);
          if (!result) {
            err = new Error('parse failed');
          }
          onComplete(err, result);
        };
        _proto.parseImport = function parseImport(file, options, onComplete) {
          if (!file) {
            onComplete(new Error("The json file of asset " + options.__uuid__ + " is empty or missing"));
            return;
          }
          var result = null;
          var err = null;
          try {
            result = deserializeAsset(file, options);
          } catch (e) {
            err = e;
          }
          onComplete(err, result);
        };
        _proto.init = function init() {
          this._parsing.clear();
        };
        _proto.register = function register(type, handler) {
          if (typeof type === 'object') {
            mixin(this._parsers, type);
          } else {
            this._parsers[type] = handler;
          }
        };
        _proto.parse = function parse(id, file, type, options, onComplete) {
          var _this = this;
          var parsedAsset = parsed.get(id);
          if (parsedAsset) {
            onComplete(null, parsedAsset);
            return;
          }
          var parsing = this._parsing.get(id);
          if (parsing) {
            parsing.push(onComplete);
            return;
          }
          var parseHandler = this._parsers[type];
          if (!parseHandler) {
            onComplete(null, file);
            return;
          }
          this._parsing.add(id, [onComplete]);
          parseHandler(file, options, function (err, data) {
            if (err) {
              files.remove(id);
            } else if (!isScene(data)) {
              parsed.add(id, data);
            }
            var callbacks = _this._parsing.remove(id);
            for (var i = 0, l = callbacks.length; i < l; i++) {
              callbacks[i](err, data);
            }
          });
        };
        _createClass(Parser, null, [{
          key: "instance",
          get: function get() {
            if (!this._instance) {
              this._instance = new Parser();
            }
            return this._instance;
          }
        }]);
        return Parser;
      }();
      Parser$1._instance = void 0;
      var parser = Parser$1.instance;

      function load(task, done) {
        var firstTask = false;
        if (!task.progress) {
          task.progress = {
            finish: 0,
            total: task.input.length,
            canInvoke: true
          };
          firstTask = true;
        }
        var options = task.options,
          progress = task.progress;
        options.__exclude__ = options.__exclude__ || Object.create(null);
        task.output = [];
        forEach(task.input, function (item, cb) {
          var subTask = Task.create({
            input: item,
            onProgress: task.onProgress,
            options: options,
            progress: progress,
            onComplete: function onComplete(err, result) {
              if (err && !task.isFinished) {
                if (!legacyCC.assetManager.force || firstTask) {
                  {
                    error(err.message, err.stack);
                  }
                  progress.canInvoke = false;
                  done(err);
                } else if (progress.canInvoke) {
                  task.dispatch('progress', ++progress.finish, progress.total, item);
                }
              }
              task.output.push(result);
              subTask.recycle();
              cb(null);
            }
          });
          loadOneAssetPipeline.async(subTask);
        }, function () {
          options.__exclude__ = null;
          if (task.isFinished) {
            clear(task, true);
            task.dispatch('error');
            return;
          }
          gatherAsset(task);
          clear(task, true);
          done();
        });
      }
      var loadOneAssetPipeline = new Pipeline('loadOneAsset', [function fetch(task, done) {
        var item = task.output = task.input;
        var options = item.options,
          isNative = item.isNative,
          uuid = item.uuid,
          file = item.file;
        var reloadAsset = options.reloadAsset;
        if (file || !reloadAsset && !isNative && assets.has(uuid)) {
          done();
          return;
        }
        packManager.load(item, task.options, function (err, data) {
          item.file = data;
          done(err);
        });
      }, function parse(task, done) {
        var item = task.output = task.input;
        var progress = task.progress;
        var exclude = task.options.__exclude__;
        var id = item.id,
          file = item.file,
          options = item.options;
        if (item.isNative) {
          parser.parse(id, file, item.ext, options, function (err, asset) {
            if (err) {
              done(err);
              return;
            }
            item.content = asset;
            if (progress.canInvoke) {
              task.dispatch('progress', ++progress.finish, progress.total, item);
            }
            files.remove(id);
            parsed.remove(id);
            done();
          });
        } else {
          var uuid = item.uuid;
          if (uuid in exclude) {
            var _exclude$uuid = exclude[uuid],
              finish = _exclude$uuid.finish,
              content = _exclude$uuid.content,
              _err = _exclude$uuid.err,
              callbacks = _exclude$uuid.callbacks;
            if (progress.canInvoke) {
              task.dispatch('progress', ++progress.finish, progress.total, item);
            }
            if (finish || checkCircleReference(uuid, uuid, exclude)) {
              if (content) {
                content.addRef();
              }
              item.content = content;
              done(_err);
            } else {
              callbacks.push({
                done: done,
                item: item
              });
            }
          } else if (!options.reloadAsset && assets.has(uuid)) {
            var asset = assets.get(uuid);
            item.content = asset.addRef();
            if (progress.canInvoke) {
              task.dispatch('progress', ++progress.finish, progress.total, item);
            }
            done();
          } else {
            options.__uuid__ = uuid;
            parser.parse(id, file, 'import', options, function (err, asset) {
              if (err) {
                done(err);
                return;
              }
              loadDepends(task, asset, done);
            });
          }
        }
      }]);
      function loadDepends(task, asset, done) {
        var item = task.input,
          progress = task.progress;
        var _ref = item,
          uuid = _ref.uuid,
          id = _ref.id,
          options = _ref.options,
          config = _ref.config;
        var cacheAsset = options.cacheAsset;
        var depends = [];
        if (asset.addRef) {
          asset.addRef();
        }
        getDepends(uuid, asset, Object.create(null), depends, config);
        if (progress.canInvoke) {
          task.dispatch('progress', ++progress.finish, progress.total += depends.length, item);
        }
        var repeatItem = task.options.__exclude__[uuid] = {
          content: asset,
          finish: false,
          callbacks: [{
            done: done,
            item: item
          }]
        };
        var subTask = Task.create({
          input: depends,
          options: task.options,
          onProgress: task.onProgress,
          onError: Task.prototype.recycle,
          progress: progress,
          onComplete: function onComplete(err) {
            if (asset.decRef) {
              asset.decRef(false);
            }
            repeatItem.finish = true;
            repeatItem.err = err;
            if (!err) {
              var output = Array.isArray(subTask.output) ? subTask.output : [subTask.output];
              var map = Object.create(null);
              for (var _iterator = _createForOfIteratorHelperLoose(output), _step; !(_step = _iterator()).done;) {
                var dependAsset = _step.value;
                if (!dependAsset) {
                  continue;
                }
                map[dependAsset instanceof Asset ? dependAsset._uuid + "@import" : uuid + "@native"] = dependAsset;
              }
              setProperties(uuid, asset, map);
              try {
                if (typeof asset.onLoaded === 'function' && !onLoadedInvokedMap.has(asset) && !nativeDependMap.has(asset)) {
                  asset.onLoaded();
                  onLoadedInvokedMap.add(asset);
                }
              } catch (e) {
                error("The asset " + uuid + " is invalid for some reason, detail message: " + e.message + ", stack: " + e.stack);
              }
              files.remove(id);
              parsed.remove(id);
              cache(uuid, asset, cacheAsset);
              subTask.recycle();
            }
            var callbacks = repeatItem.callbacks;
            for (var i = 0, l = callbacks.length; i < l; i++) {
              var cb = callbacks[i];
              if (asset.addRef) {
                asset.addRef();
              }
              cb.item.content = asset;
              cb.done(err);
            }
            callbacks.length = 0;
          }
        });
        pipeline.async(subTask);
      }

      function preprocess(task, done) {
        var options = task.options;
        var subOptions = Object.create(null);
        var leftOptions = Object.create(null);
        for (var op in options) {
          switch (op) {
            case RequestType.PATH:
            case RequestType.UUID:
            case RequestType.DIR:
            case RequestType.SCENE:
            case RequestType.URL:
              break;
            case '__requestType__':
            case '__isNative__':
            case 'ext':
            case 'type':
            case '__nativeName__':
            case 'audioLoadMode':
            case 'bundle':
              subOptions[op] = options[op];
              break;
            case '__exclude__':
            case '__outputAsArray__':
              leftOptions[op] = options[op];
              break;
            default:
              subOptions[op] = options[op];
              leftOptions[op] = options[op];
              break;
          }
        }
        task.options = leftOptions;
        var subTask = Task.create({
          input: task.input,
          options: subOptions
        });
        var err = null;
        try {
          task.output = task.source = transformPipeline.sync(subTask);
        } catch (e) {
          err = e;
          for (var i = 0, l = subTask.output.length; i < l; i++) {
            subTask.output[i].recycle();
          }
        }
        subTask.recycle();
        done(err);
      }

      var RequestItem = function () {
        function RequestItem() {
          this.uuid = '';
          this.overrideUuid = '';
          this.url = '';
          this.ext = '.json';
          this.content = null;
          this.file = null;
          this.info = null;
          this.config = null;
          this.isNative = false;
          this.options = Object.create(null);
          this._id = '';
        }
        RequestItem.create = function create() {
          var out;
          if (RequestItem._deadPool.length !== 0) {
            out = RequestItem._deadPool.pop();
          } else {
            out = new RequestItem();
          }
          return out;
        };
        var _proto = RequestItem.prototype;
        _proto.recycle = function recycle() {
          if (RequestItem._deadPool.length === RequestItem.MAX_DEAD_NUM) {
            return;
          }
          this._id = '';
          this.uuid = '';
          this.overrideUuid = '';
          this.url = '';
          this.ext = '.json';
          this.content = null;
          this.file = null;
          this.info = null;
          this.config = null;
          this.isNative = false;
          this.options = Object.create(null);
          RequestItem._deadPool.push(this);
        };
        _createClass(RequestItem, [{
          key: "id",
          get: function get() {
            if (!this._id) {
              this._id = (this.overrideUuid || this.uuid) + "@" + (this.isNative ? 'native' : 'import');
            }
            return this._id;
          }
        }]);
        return RequestItem;
      }();
      RequestItem.MAX_DEAD_NUM = 500;
      RequestItem._deadPool = [];

      var infos = [];
      function parse(task) {
        var options = task.options;
        var input = Array.isArray(task.input) ? task.input : [task.input];
        task.output = [];
        var _loop = function _loop() {
          var item = input[i];
          var out = RequestItem.create();
          var config = null;
          var info = null;
          if (typeof item === 'string') {
            item = Object.create(null);
            item[options.__requestType__ || RequestType.UUID] = input[i];
          }
          if (typeof item === 'object') {
            addon(item, options);
            if (item.preset) {
              addon(item, presets[item.preset]);
            }
            var _loop2 = function _loop2() {
              var _info2;
              switch (key) {
                case RequestType.UUID:
                  {
                    var _info;
                    var uuid = out.uuid = decodeUuid(item.uuid);
                    if (!item.bundle) {
                      var bundle = bundles.find(function (bundle) {
                        return !!bundle.getAssetInfo(uuid);
                      });
                      item.bundle = bundle && bundle.name;
                    }
                    if (bundles.has(item.bundle)) {
                      config = bundles.get(item.bundle).config;
                      info = config.getAssetInfo(uuid);
                      if (info && info.redirect) {
                        if (!bundles.has(info.redirect)) {
                          throw new Error("Please load bundle " + info.redirect + " first");
                        }
                        config = bundles.get(info.redirect).config;
                        info = config.getAssetInfo(uuid);
                      }
                      out.config = config;
                      out.info = info;
                    }
                    out.ext = item.ext || ((_info = info) === null || _info === void 0 ? void 0 : _info.extension) || '.json';
                    break;
                  }
                case '__requestType__':
                case 'ext':
                case 'bundle':
                case 'preset':
                case 'type':
                  break;
                case RequestType.DIR:
                  if (bundles.has(item.bundle)) {
                    bundles.get(item.bundle).config.getDirWithPath(item.dir, item.type, infos);
                    for (var _iterator = _createForOfIteratorHelperLoose(infos), _step; !(_step = _iterator()).done;) {
                      var assetInfo = _step.value;
                      input.push({
                        uuid: assetInfo.uuid,
                        __isNative__: false,
                        ext: assetInfo.extension || '.json',
                        bundle: item.bundle
                      });
                    }
                    infos.length = 0;
                  }
                  out.recycle();
                  out = null;
                  break;
                case RequestType.PATH:
                  if (bundles.has(item.bundle)) {
                    config = bundles.get(item.bundle).config;
                    info = config.getInfoWithPath(item.path, item.type);
                    if (info && info.redirect) {
                      if (!bundles.has(info.redirect)) {
                        throw new Error("you need to load bundle " + info.redirect + " first");
                      }
                      config = bundles.get(info.redirect).config;
                      info = config.getAssetInfo(info.uuid);
                    }
                    if (!info) {
                      out.recycle();
                      throw new Error("Bundle " + item.bundle + " doesn't contain " + item.path);
                    }
                    out.config = config;
                    out.uuid = info.uuid;
                    out.info = info;
                  }
                  out.ext = item.ext || ((_info2 = info) === null || _info2 === void 0 ? void 0 : _info2.extension) || '.json';
                  break;
                case RequestType.SCENE:
                  if (!item.bundle) {
                    var _bundle = bundles.find(function (bundle) {
                      return !!bundle.getSceneInfo(item.scene);
                    });
                    item.bundle = _bundle && _bundle.name;
                  }
                  if (bundles.has(item.bundle)) {
                    config = bundles.get(item.bundle).config;
                    info = config.getSceneInfo(item.scene);
                    if (info && info.redirect) {
                      if (!bundles.has(info.redirect)) {
                        throw new Error("you need to load bundle " + info.redirect + " first");
                      }
                      config = bundles.get(info.redirect).config;
                      info = config.getAssetInfo(info.uuid);
                    }
                    if (!info) {
                      out.recycle();
                      throw new Error("Bundle " + config.name + " doesn't contain scene " + item.scene);
                    }
                    out.config = config;
                    out.uuid = info.uuid;
                    out.info = info;
                  }
                  break;
                case '__isNative__':
                  out.isNative = item.__isNative__;
                  break;
                case RequestType.URL:
                  out.url = item.url;
                  out.uuid = item.uuid || item.url;
                  out.ext = item.ext || extname(item.url);
                  out.isNative = item.__isNative__ !== undefined ? item.__isNative__ : true;
                  break;
                default:
                  out.options[key] = item[key];
              }
              if (!out) {
                return 1;
              }
            };
            for (var key in item) {
              if (_loop2()) break;
            }
          }
          if (!out) {
            return 1;
          }
          task.output.push(out);
          if (!out.uuid && !out.url) {
            throw new Error("Can not parse this input:" + JSON.stringify(item));
          }
        };
        for (var i = 0; i < input.length; i++) {
          if (_loop()) continue;
        }
        return null;
      }
      function replaceOverrideAsset(task) {
        var input = task.output = task.input;
        var _loop3 = function _loop3() {
          var item = input[i];
          if (assetsOverrideMap.has(item.uuid)) {
            var uuid = assetsOverrideMap.get(item.uuid);
            var bundle = bundles.find(function (bundle) {
              return !!bundle.getAssetInfo(uuid);
            });
            if (bundle) {
              var _info3;
              item.overrideUuid = uuid;
              var config = bundle.config;
              var info = config.getAssetInfo(uuid);
              if (info && info.redirect) {
                if (!bundles.has(info.redirect)) {
                  throw new Error("Please load bundle " + info.redirect + " first");
                }
                config = bundles.get(info.redirect).config;
                info = config.getAssetInfo(uuid);
              }
              item.config = config;
              item.info = info;
              item.ext = item.isNative ? item.ext : ((_info3 = info) === null || _info3 === void 0 ? void 0 : _info3.extension) || '.json';
            } else {
              warnID(16201, uuid, item.uuid);
            }
          }
        };
        for (var i = 0; i < input.length; i++) {
          if (_loop3()) continue;
        }
      }
      function combine(task) {
        var input = task.output = task.input;
        for (var i = 0; i < input.length; i++) {
          var item = input[i];
          if (item.url) {
            continue;
          }
          var url = '';
          var base = '';
          var config = item.config;
          if (item.isNative) {
            base = config && config.nativeBase ? config.base + config.nativeBase : legacyCC.assetManager.generalNativeBase;
          } else {
            base = config && config.importBase ? config.base + config.importBase : legacyCC.assetManager.generalImportBase;
          }
          var uuid = item.overrideUuid || item.uuid;
          var ver = '';
          if (item.info) {
            if (item.isNative) {
              ver = item.info.nativeVer ? "." + item.info.nativeVer : '';
            } else {
              ver = item.info.ver ? "." + item.info.ver : '';
            }
          }
          if (item.ext === '.ttf') {
            url = base + "/" + uuid.slice(0, 2) + "/" + uuid + ver + "/" + item.options.__nativeName__;
          } else {
            url = base + "/" + uuid.slice(0, 2) + "/" + uuid + ver + item.ext;
          }
          item.url = url;
        }
        return null;
      }

      var EVENT_ASSET_MISSING = 'asset-missing';
      var AssetManager = exports('ei', function () {
        function AssetManager() {
          this.pipeline = pipeline.append(preprocess).append(load);
          this.fetchPipeline = fetchPipeline.append(preprocess).append(fetch$1);
          this.transformPipeline = transformPipeline.append(parse).append(replaceOverrideAsset).append(combine);
          this.bundles = bundles;
          this.assets = assets;
          this.assetsOverrideMap = assetsOverrideMap;
          this.generalImportBase = '';
          this.generalNativeBase = '';
          this.dependUtil = dependUtil;
          this.force = PREVIEW;
          this.allowImageBitmap = false;
          this.utils = helper;
          this.downloader = downloader$1;
          this.parser = parser;
          this.packManager = packManager;
          this.cacheAsset = true;
          this.cacheManager = null;
          this.presets = presets;
          this.factory = factory;
          this.preprocessPipe = preprocess;
          this.fetchPipe = fetch$1;
          this.loadPipe = load;
          this.references = references;
          this._releaseManager = releaseManager;
          this._files = files;
          this._parsed = parsed;
          this._parsePipeline = null ;
          this._projectBundles = [];
          this._eventTarget = new EventTarget();
        }
        var _proto = AssetManager.prototype;
        _proto.onAssetMissing = function onAssetMissing(func, target) {
          this._eventTarget.on(EVENT_ASSET_MISSING, func, target);
        };
        _proto.offAssetMissing = function offAssetMissing(func, target) {
          this._eventTarget.off(EVENT_ASSET_MISSING, func, target);
        };
        _proto.dispatchAssetMissing = function dispatchAssetMissing(parentAsset, owner, propName, uuid) {
          this._eventTarget.emit(EVENT_ASSET_MISSING, parentAsset, owner, propName, uuid);
        };
        _proto.init = function init(options) {
          if (options === void 0) {
            options = {};
          }
          var server = options.server || settings.querySettings(Settings.Category.ASSETS, 'server') || '';
          var bundleVers = options.bundleVers || settings.querySettings(Settings.Category.ASSETS, 'bundleVers') || {};
          var remoteBundles = options.remoteBundles || settings.querySettings(Settings.Category.ASSETS, 'remoteBundles') || [];
          this._files.clear();
          this._parsed.clear();
          this._releaseManager.init();
          this.assets.clear();
          this.bundles.clear();
          this.packManager.init();
          this.downloader.init(server, bundleVers, remoteBundles);
          this.parser.init();
          this.dependUtil.init();
          var importBase = options.importBase || settings.querySettings(Settings.Category.ASSETS, 'importBase') || '';
          if (importBase && importBase.endsWith('/')) {
            importBase = importBase.substr(0, importBase.length - 1);
          }
          var nativeBase = options.nativeBase || settings.querySettings(Settings.Category.ASSETS, 'nativeBase') || '';
          if (nativeBase && nativeBase.endsWith('/')) {
            nativeBase = nativeBase.substr(0, nativeBase.length - 1);
          }
          this.generalImportBase = importBase;
          this.generalNativeBase = nativeBase;
          this._projectBundles = settings.querySettings(Settings.Category.ASSETS, 'projectBundles') || [];
          var assetsOverride = settings.querySettings(Settings.Category.ASSETS, 'assetsOverrides') || {};
          for (var _key in assetsOverride) {
            this.assetsOverrideMap.set(_key, assetsOverride[_key]);
          }
        };
        _proto.getBundle = function getBundle(name) {
          return bundles.get(name) || null;
        };
        _proto.removeBundle = function removeBundle(bundle) {
          bundle._destroy();
          bundles.remove(bundle.name);
        };
        _proto.loadAny = function loadAny(requests, options, onProgress, onComplete) {
          var _parseParameters = parseParameters(options, onProgress, onComplete),
            opts = _parseParameters.options,
            onProg = _parseParameters.onProgress,
            onComp = _parseParameters.onComplete;
          opts.preset = opts.preset || 'default';
          requests = Array.isArray(requests) ? requests.slice() : requests;
          var task = Task.create({
            input: requests,
            onProgress: onProg,
            onComplete: asyncify(onComp),
            options: opts
          });
          pipeline.async(task);
        };
        _proto.preloadAny = function preloadAny(requests, options, onProgress, onComplete) {
          var _parseParameters2 = parseParameters(options, onProgress, onComplete),
            opts = _parseParameters2.options,
            onProg = _parseParameters2.onProgress,
            onComp = _parseParameters2.onComplete;
          opts.preset = opts.preset || 'preload';
          requests = Array.isArray(requests) ? requests.slice() : requests;
          var task = Task.create({
            input: requests,
            onProgress: onProg,
            onComplete: asyncify(onComp),
            options: opts
          });
          fetchPipeline.async(task);
        };
        _proto.loadRemote = function loadRemote(url, options, onComplete) {
          var _parseParameters3 = parseParameters(options, undefined, onComplete),
            opts = _parseParameters3.options,
            onComp = _parseParameters3.onComplete;
          if (!opts.reloadAsset && this.assets.has(url)) {
            asyncify(onComp)(null, this.assets.get(url));
            return;
          }
          opts.__isNative__ = true;
          opts.preset = opts.preset || 'remote';
          this.loadAny({
            url: url
          }, opts, null, function (err, data) {
            if (err) {
              error(err.message, err.stack);
              if (onComp) {
                onComp(err, data);
              }
            } else {
              factory.create(url, data, opts.ext || extname(url), opts, function (p1, p2) {
                if (onComp) {
                  onComp(p1, p2);
                }
              });
            }
          });
        };
        _proto.loadBundle = function loadBundle(nameOrUrl, options, onComplete) {
          var _parseParameters4 = parseParameters(options, undefined, onComplete),
            opts = _parseParameters4.options,
            onComp = _parseParameters4.onComplete;
          var bundleName = basename(nameOrUrl);
          if (this.bundles.has(bundleName)) {
            asyncify(onComp)(null, this.getBundle(bundleName));
            return;
          }
          opts.preset = opts.preset || 'bundle';
          opts.ext = 'bundle';
          opts.__isNative__ = true;
          this.loadAny({
            url: nameOrUrl
          }, opts, null, function (err, data) {
            if (err) {
              error(err.message, err.stack);
              if (onComp) {
                onComp(err, data);
              }
            } else {
              factory.create(nameOrUrl, data, 'bundle', opts, function (p1, p2) {
                if (onComp) {
                  onComp(p1, p2);
                }
              });
            }
          });
        };
        _proto.releaseAsset = function releaseAsset(asset) {
          releaseManager.tryRelease(asset, true);
        };
        _proto.releaseUnusedAssets = function releaseUnusedAssets() {
          assets.forEach(function (asset) {
            releaseManager.tryRelease(asset);
          });
        };
        _proto.releaseAll = function releaseAll() {
          assets.forEach(function (asset) {
            releaseManager.tryRelease(asset, true);
          });
        };
        _proto.loadWithJson = function loadWithJson(json, options, onProgress, onComplete) {
          {
            throw new Error('Only valid in Editor');
          }
        };
        _createClass(AssetManager, [{
          key: "main",
          get: function get() {
            return bundles.get(BuiltinBundleName.MAIN) || null;
          }
        }, {
          key: "resources",
          get: function get() {
            return bundles.get(BuiltinBundleName.RESOURCES) || null;
          }
        }], [{
          key: "instance",
          get: function get() {
            if (!this._instance) {
              this._instance = new AssetManager();
            }
            return this._instance;
          }
        }]);
        return AssetManager;
      }());
      AssetManager._instance = void 0;
      AssetManager.Pipeline = Pipeline;
      AssetManager.Task = Task;
      AssetManager.Cache = Cache;
      AssetManager.RequestItem = RequestItem;
      AssetManager.Bundle = Bundle;
      AssetManager.BuiltinBundleName = BuiltinBundleName;
      AssetManager.CacheManager = CacheManager;
      AssetManager.Downloader = Downloader;
      AssetManager.Parser = Parser$1;
      AssetManager.DependUtil = DependUtil;
      var assetManager = exports('eh', legacyCC.assetManager = AssetManager.instance);
      legacyCC.AssetManager = AssetManager;

      var BuiltinResMgr = exports('ek', function () {
        function BuiltinResMgr() {
          this._resources = {};
          this._materialsToBeCompiled = [];
        }
        var _proto = BuiltinResMgr.prototype;
        _proto.init = function init() {
          var resources = this._resources;
          var len = 2;
          var numChannels = 4;
          var blackValueView = new Uint8Array(len * len * numChannels);
          var emptyValueView = new Uint8Array(len * len * numChannels);
          var greyValueView = new Uint8Array(len * len * numChannels);
          var whiteValueView = new Uint8Array(len * len * numChannels);
          var normalValueView = new Uint8Array(len * len * numChannels);
          var offset = 0;
          for (var i = 0; i < len * len; i++) {
            blackValueView[offset] = 0;
            blackValueView[offset + 1] = 0;
            blackValueView[offset + 2] = 0;
            blackValueView[offset + 3] = 255;
            emptyValueView[offset] = 0;
            emptyValueView[offset + 1] = 0;
            emptyValueView[offset + 2] = 0;
            emptyValueView[offset + 3] = 0;
            greyValueView[offset] = 119;
            greyValueView[offset + 1] = 119;
            greyValueView[offset + 2] = 119;
            greyValueView[offset + 3] = 255;
            whiteValueView[offset] = 255;
            whiteValueView[offset + 1] = 255;
            whiteValueView[offset + 2] = 255;
            whiteValueView[offset + 3] = 255;
            normalValueView[offset] = 127;
            normalValueView[offset + 1] = 127;
            normalValueView[offset + 2] = 255;
            normalValueView[offset + 3] = 255;
            offset += numChannels;
          }
          var defaultSize = 16;
          var halfDefaultSize = defaultSize / 2;
          var defaultValueView = new Uint8Array(defaultSize * defaultSize * numChannels);
          offset = 0;
          for (var _i = 0; _i < defaultSize * defaultSize; _i++) {
            defaultValueView[offset] = 221;
            defaultValueView[offset + 1] = 221;
            defaultValueView[offset + 2] = 221;
            defaultValueView[offset + 3] = 255;
            offset += numChannels;
          }
          offset = 0;
          for (var _i2 = 0; _i2 < halfDefaultSize; _i2++) {
            for (var j = 0; j < halfDefaultSize; j++) {
              defaultValueView[offset] = 85;
              defaultValueView[offset + 1] = 85;
              defaultValueView[offset + 2] = 85;
              defaultValueView[offset + 3] = 255;
              offset += numChannels;
            }
            offset += halfDefaultSize * numChannels;
          }
          offset += halfDefaultSize * numChannels;
          for (var _i3 = 0; _i3 < halfDefaultSize; _i3++) {
            for (var _j = 0; _j < halfDefaultSize; _j++) {
              defaultValueView[offset] = 85;
              defaultValueView[offset + 1] = 85;
              defaultValueView[offset + 2] = 85;
              defaultValueView[offset + 3] = 255;
              offset += numChannels;
            }
            offset += halfDefaultSize * numChannels;
          }
          var blackMemImageSource = {
            width: len,
            height: len,
            _data: blackValueView,
            _compressed: false,
            format: Texture2D.PixelFormat.RGBA8888
          };
          var emptyMemImageSource = {
            width: len,
            height: len,
            _data: emptyValueView,
            _compressed: false,
            format: Texture2D.PixelFormat.RGBA8888
          };
          var greyMemImageSource = {
            width: len,
            height: len,
            _data: greyValueView,
            _compressed: false,
            format: Texture2D.PixelFormat.RGBA8888
          };
          var whiteMemImageSource = {
            width: len,
            height: len,
            _data: whiteValueView,
            _compressed: false,
            format: Texture2D.PixelFormat.RGBA8888
          };
          var normalMemImageSource = {
            width: len,
            height: len,
            _data: normalValueView,
            _compressed: false,
            format: Texture2D.PixelFormat.RGBA8888
          };
          var defaultMemImageSource = {
            width: defaultSize,
            height: defaultSize,
            _data: defaultValueView,
            _compressed: false,
            format: Texture2D.PixelFormat.RGBA8888
          };
          var imgAsset = new ImageAsset(blackMemImageSource);
          var blackTexture = new Texture2D();
          blackTexture._uuid = 'black-texture';
          blackTexture.image = imgAsset;
          resources[blackTexture._uuid] = blackTexture;
          var emptyImgAsset = new ImageAsset(emptyMemImageSource);
          var emptyTexture = new Texture2D();
          emptyTexture._uuid = 'empty-texture';
          emptyTexture.image = emptyImgAsset;
          resources[emptyTexture._uuid] = emptyTexture;
          var blackCubeTexture = new TextureCube();
          blackCubeTexture._uuid = 'black-cube-texture';
          blackCubeTexture.setMipFilter(TextureCube.Filter.NEAREST);
          blackCubeTexture.image = {
            front: new ImageAsset(blackMemImageSource),
            back: new ImageAsset(blackMemImageSource),
            left: new ImageAsset(blackMemImageSource),
            right: new ImageAsset(blackMemImageSource),
            top: new ImageAsset(blackMemImageSource),
            bottom: new ImageAsset(blackMemImageSource)
          };
          resources[blackCubeTexture._uuid] = blackCubeTexture;
          var greyImgAsset = new ImageAsset(greyMemImageSource);
          var greyTexture = new Texture2D();
          greyTexture._uuid = 'grey-texture';
          greyTexture.image = greyImgAsset;
          resources[greyTexture._uuid] = greyTexture;
          var greyCubeTexture = new TextureCube();
          greyCubeTexture._uuid = 'grey-cube-texture';
          greyCubeTexture.setMipFilter(TextureCube.Filter.NEAREST);
          greyCubeTexture.image = {
            front: new ImageAsset(greyMemImageSource),
            back: new ImageAsset(greyMemImageSource),
            left: new ImageAsset(greyMemImageSource),
            right: new ImageAsset(greyMemImageSource),
            top: new ImageAsset(greyMemImageSource),
            bottom: new ImageAsset(greyMemImageSource)
          };
          resources[greyCubeTexture._uuid] = greyCubeTexture;
          var whiteImgAsset = new ImageAsset(whiteMemImageSource);
          var whiteTexture = new Texture2D();
          whiteTexture._uuid = 'white-texture';
          whiteTexture.image = whiteImgAsset;
          resources[whiteTexture._uuid] = whiteTexture;
          var whiteCubeTexture = new TextureCube();
          whiteCubeTexture._uuid = 'white-cube-texture';
          whiteCubeTexture.setMipFilter(TextureCube.Filter.NEAREST);
          whiteCubeTexture.image = {
            front: new ImageAsset(whiteMemImageSource),
            back: new ImageAsset(whiteMemImageSource),
            left: new ImageAsset(whiteMemImageSource),
            right: new ImageAsset(whiteMemImageSource),
            top: new ImageAsset(whiteMemImageSource),
            bottom: new ImageAsset(whiteMemImageSource)
          };
          resources[whiteCubeTexture._uuid] = whiteCubeTexture;
          var normalImgAsset = new ImageAsset(normalMemImageSource);
          var normalTexture = new Texture2D();
          normalTexture._uuid = 'normal-texture';
          normalTexture.image = normalImgAsset;
          resources[normalTexture._uuid] = normalTexture;
          var defaultImgAsset = new ImageAsset(defaultMemImageSource);
          var defaultTexture = new Texture2D();
          defaultTexture._uuid = 'default-texture';
          defaultTexture.image = defaultImgAsset;
          resources[defaultTexture._uuid] = defaultTexture;
          var defaultCubeTexture = new TextureCube();
          defaultCubeTexture.setMipFilter(TextureCube.Filter.NEAREST);
          defaultCubeTexture._uuid = 'default-cube-texture';
          defaultCubeTexture.image = {
            front: new ImageAsset(defaultMemImageSource),
            back: new ImageAsset(defaultMemImageSource),
            left: new ImageAsset(defaultMemImageSource),
            right: new ImageAsset(defaultMemImageSource),
            top: new ImageAsset(defaultMemImageSource),
            bottom: new ImageAsset(defaultMemImageSource)
          };
          resources[defaultCubeTexture._uuid] = defaultCubeTexture;
          if (legacyCC.SpriteFrame) {
            var spriteFrame = new legacyCC.SpriteFrame();
            var image = imgAsset;
            var texture = new Texture2D();
            texture.image = image;
            spriteFrame.texture = texture;
            spriteFrame._uuid = 'default-spriteframe';
            resources[spriteFrame._uuid] = spriteFrame;
          }
        };
        _proto.addAsset = function addAsset(key, asset) {
          this._resources[key] = asset;
        };
        _proto.get = function get(uuid) {
          return this._resources[uuid];
        };
        _proto.loadBuiltinAssets = function loadBuiltinAssets() {
          var _this = this;
          var builtinAssets = settings.querySettings(Settings.Category.ENGINE, 'builtinAssets');
          if (!builtinAssets) return Promise.resolve();
          var resources = this._resources;
          return new Promise(function (resolve, reject) {
            assetManager.loadBundle(BuiltinBundleName.INTERNAL, function (err, bundle) {
              if (err) {
                reject(err);
                return;
              }
              assetManager.loadAny(builtinAssets, function (err, assets) {
                if (err) {
                  reject(err);
                } else {
                  assets.forEach(function (asset) {
                    resources[asset.name] = asset;
                    {
                      releaseManager.addIgnoredAsset(asset);
                    }
                    if (asset instanceof legacyCC.Material) {
                      _this._materialsToBeCompiled.push(asset);
                    }
                  });
                  resolve();
                }
              });
            });
          });
        };
        _proto.compileBuiltinMaterial = function compileBuiltinMaterial() {
          for (var i = 0; i < this._materialsToBeCompiled.length; ++i) {
            var mat = this._materialsToBeCompiled[i];
            for (var j = 0; j < mat.passes.length; ++j) {
              mat.passes[j].tryCompile();
            }
          }
          this._materialsToBeCompiled.length = 0;
        };
        return BuiltinResMgr;
      }());
      var builtinResMgr = exports('el', legacyCC.builtinResMgr = new BuiltinResMgr());

      var getPhaseID = exports('dr', function () {
        var phases = new Map();
        var phaseNum = 0;
        return function (phaseName) {
          if (typeof phaseName === 'number') {
            return phaseName;
          }
          if (!phases.has(phaseName)) {
            phases.set(phaseName, 1 << phaseNum);
            phaseNum++;
          }
          return phases.get(phaseName);
        };
      }());

      var INITIAL_CAPACITY = 32;
      var MAX_CAPACITY = 1024;
      var InstancedBuffer = exports('dj', function () {
        function InstancedBuffer(pass) {
          this.instances = [];
          this.pass = void 0;
          this.hasPendingModels = false;
          this.dynamicOffsets = [];
          this._device = void 0;
          this._device = pass.device;
          this.pass = pass;
        }
        var _proto = InstancedBuffer.prototype;
        _proto.destroy = function destroy() {
          for (var i = 0; i < this.instances.length; ++i) {
            var instance = this.instances[i];
            instance.vb.destroy();
            instance.ia.destroy();
          }
          this.instances.length = 0;
        };
        _proto.merge = function merge(subModel, passIdx, shaderImplant) {
          if (shaderImplant === void 0) {
            shaderImplant = null;
          }
          var attrs = subModel.instancedAttributeBlock;
          var stride = attrs.buffer.length;
          if (!stride) {
            return;
          }
          var sourceIA = subModel.inputAssembler;
          var lightingMap = subModel.descriptorSet.getTexture(UNIFORM_LIGHTMAP_TEXTURE_BINDING);
          var reflectionProbeCubemap = subModel.descriptorSet.getTexture(UNIFORM_REFLECTION_PROBE_CUBEMAP_BINDING);
          var reflectionProbePlanarMap = subModel.descriptorSet.getTexture(UNIFORM_REFLECTION_PROBE_TEXTURE_BINDING);
          var reflectionProbeBlendCubemap = subModel.descriptorSet.getTexture(UNIFORM_REFLECTION_PROBE_BLEND_CUBEMAP_BINDING);
          var useReflectionProbeType = subModel.useReflectionProbeType;
          var shader = shaderImplant;
          if (!shader) {
            shader = subModel.shaders[passIdx];
          }
          var descriptorSet = subModel.descriptorSet;
          for (var i = 0; i < this.instances.length; ++i) {
            var _instance$ia$indexBuf, _sourceIA$indexBuffer;
            var instance = this.instances[i];
            if (((_instance$ia$indexBuf = instance.ia.indexBuffer) === null || _instance$ia$indexBuf === void 0 ? void 0 : _instance$ia$indexBuf.objectID) !== ((_sourceIA$indexBuffer = sourceIA.indexBuffer) === null || _sourceIA$indexBuffer === void 0 ? void 0 : _sourceIA$indexBuffer.objectID) || instance.count >= MAX_CAPACITY) {
              continue;
            }
            if (instance.lightingMap.objectID !== lightingMap.objectID) {
              continue;
            }
            if (instance.useReflectionProbeType !== useReflectionProbeType) {
              continue;
            }
            if (instance.reflectionProbeCubemap.objectID !== reflectionProbeCubemap.objectID) {
              continue;
            }
            if (instance.reflectionProbePlanarMap.objectID !== reflectionProbePlanarMap.objectID) {
              continue;
            }
            if (instance.reflectionProbeBlendCubemap.objectID !== reflectionProbeBlendCubemap.objectID) {
              continue;
            }
            if (instance.stride !== stride) {
              continue;
            }
            if (instance.count >= instance.capacity) {
              instance.capacity <<= 1;
              var newSize = instance.stride * instance.capacity;
              var oldData = instance.data;
              instance.data = new Uint8Array(newSize);
              instance.data.set(oldData);
              instance.vb.resize(newSize);
            }
            instance.shader = shader;
            instance.descriptorSet = descriptorSet;
            instance.data.set(attrs.buffer, instance.stride * instance.count++);
            this.hasPendingModels = true;
            return;
          }
          var vb = this._device.createBuffer(new BufferInfo(BufferUsageBit.VERTEX | BufferUsageBit.TRANSFER_DST, MemoryUsageBit.HOST | MemoryUsageBit.DEVICE, stride * INITIAL_CAPACITY, stride));
          var data = new Uint8Array(stride * INITIAL_CAPACITY);
          var vertexBuffers = sourceIA.vertexBuffers.slice();
          var attributes = sourceIA.attributes.slice();
          var indexBuffer = sourceIA.indexBuffer;
          for (var _i = 0; _i < attrs.attributes.length; _i++) {
            var attr = attrs.attributes[_i];
            var newAttr = new Attribute(attr.name, attr.format, attr.isNormalized, vertexBuffers.length, true);
            attributes.push(newAttr);
          }
          data.set(attrs.buffer);
          vertexBuffers.push(vb);
          var iaInfo = new InputAssemblerInfo(attributes, vertexBuffers, indexBuffer);
          var ia = this._device.createInputAssembler(iaInfo);
          this.instances.push({
            count: 1,
            capacity: INITIAL_CAPACITY,
            vb: vb,
            data: data,
            ia: ia,
            stride: stride,
            shader: shader,
            descriptorSet: descriptorSet,
            lightingMap: lightingMap,
            reflectionProbeCubemap: reflectionProbeCubemap,
            reflectionProbePlanarMap: reflectionProbePlanarMap,
            useReflectionProbeType: useReflectionProbeType,
            reflectionProbeBlendCubemap: reflectionProbeBlendCubemap
          });
          this.hasPendingModels = true;
        };
        _proto.uploadBuffers = function uploadBuffers(cmdBuff) {
          for (var i = 0; i < this.instances.length; ++i) {
            var instance = this.instances[i];
            if (!instance.count) {
              continue;
            }
            instance.ia.instanceCount = instance.count;
            cmdBuff.updateBuffer(instance.vb, instance.data);
          }
        };
        _proto.clear = function clear() {
          for (var i = 0; i < this.instances.length; ++i) {
            var instance = this.instances[i];
            instance.count = 0;
          }
          this.hasPendingModels = false;
        };
        return InstancedBuffer;
      }());

      var _bufferInfo = new BufferInfo(BufferUsageBit.UNIFORM | BufferUsageBit.TRANSFER_DST, MemoryUsageBit.DEVICE);
      var _bufferViewInfo = new BufferViewInfo(null);
      var _dsInfo$2 = new DescriptorSetInfo(null);
      var _materialSet = 1;
      var BatchingSchemes;
      (function (BatchingSchemes) {
        BatchingSchemes[BatchingSchemes["NONE"] = 0] = "NONE";
        BatchingSchemes[BatchingSchemes["INSTANCING"] = 1] = "INSTANCING";
      })(BatchingSchemes || (BatchingSchemes = {}));
      var Pass = function () {
        Pass.fillPipelineInfo = function fillPipelineInfo(pass, info) {
          if (info.priority !== undefined) {
            pass._priority = info.priority;
          }
          if (info.primitive !== undefined) {
            pass._primitive = info.primitive;
          }
          if (info.stage !== undefined) {
            pass._stage = info.stage;
          }
          if (info.dynamicStates !== undefined) {
            pass._dynamicStates = info.dynamicStates;
          }
          if (info.phase !== undefined) {
            pass._phase = getPhaseID(info.phase);
          }
          var bs = pass._bs;
          if (info.blendState) {
            var bsInfo = info.blendState;
            var targets = bsInfo.targets;
            if (targets) {
              targets.forEach(function (t, i) {
                bs.setTarget(i, t);
              });
            }
            if (bsInfo.isA2C !== undefined) {
              bs.isA2C = bsInfo.isA2C;
            }
            if (bsInfo.isIndepend !== undefined) {
              bs.isIndepend = bsInfo.isIndepend;
            }
            if (bsInfo.blendColor !== undefined) {
              bs.blendColor = bsInfo.blendColor;
            }
          }
          pass._rs.assign(info.rasterizerState);
          pass._dss.assign(info.depthStencilState);
        };
        Pass.getPassHash = function getPassHash(pass) {
          var shaderKey = '';
          if (legacyCC.rendering && legacyCC.rendering.enableEffectImport) {
            var key = legacyCC.rendering.programLib.getKey(pass._phaseID, pass.program, pass.defines);
            shaderKey = pass._phaseID.toString() + "," + key;
          } else {
            shaderKey = programLib.getKey(pass.program, pass.defines);
          }
          var res = shaderKey + "," + pass._primitive + "," + pass._dynamicStates;
          res += serializeBlendState(pass._bs);
          res += serializeDepthStencilState(pass._dss);
          res += serializeRasterizerState(pass._rs);
          return murmurhash2_32_gc(res, 666);
        };
        function Pass(root) {
          this._rootBuffer = null;
          this._buffers = [];
          this._descriptorSet = null;
          this._pipelineLayout = null;
          this._passIndex = 0;
          this._propertyIndex = 0;
          this._programName = '';
          this._dynamics = {};
          this._propertyHandleMap = {};
          this._rootBlock = null;
          this._blocksInt = [];
          this._blocks = [];
          this._shaderInfo = null;
          this._defines = {};
          this._properties = {};
          this._shader = null;
          this._bs = new BlendState();
          this._dss = new DepthStencilState();
          this._rs = new RasterizerState();
          this._priority = RenderPriority.DEFAULT;
          this._stage = RenderPassStage.DEFAULT;
          this._phase = getPhaseID('default');
          this._passID = 0xFFFFFFFF;
          this._subpassID = 0xFFFFFFFF;
          this._phaseID = 0xFFFFFFFF;
          this._primitive = PrimitiveMode.TRIANGLE_LIST;
          this._batchingScheme = BatchingSchemes.NONE;
          this._dynamicStates = DynamicStateFlagBit.NONE;
          this._instancedBuffers = {};
          this._hash = 0;
          this._root = void 0;
          this._device = void 0;
          this._rootBufferDirty = false;
          this._root = root;
          this._device = deviceManager.gfxDevice;
        }
        var _proto = Pass.prototype;
        _proto.initialize = function initialize(info) {
          this._doInit(info);
          this.resetUBOs();
          this.resetTextures();
          this.tryCompile();
        };
        _proto.getHandle = function getHandle(name, offset, targetType) {
          if (offset === void 0) {
            offset = 0;
          }
          if (targetType === void 0) {
            targetType = Type$1.UNKNOWN;
          }
          var handle = this._propertyHandleMap[name];
          if (!handle) {
            return 0;
          }
          if (targetType) {
            handle = customizeType(handle, targetType);
          } else if (offset) {
            handle = customizeType(handle, getTypeFromHandle(handle) - offset);
          }
          return handle + offset;
        };
        _proto.getBinding = function getBinding(name) {
          var handle = this.getHandle(name);
          if (!handle) {
            return -1;
          }
          return Pass.getBindingFromHandle(handle);
        };
        _proto.setUniform = function setUniform(handle, value) {
          var binding = Pass.getBindingFromHandle(handle);
          var type = Pass.getTypeFromHandle(handle);
          var ofs = Pass.getOffsetFromHandle(handle);
          var block = this._getBlockView(type, binding);
          {
            var validator = type2validator[type];
            assertID(Boolean(validator && validator(value)), 12011, binding, Type$1[type]);
          }
          type2writer[type](block, value, ofs);
          this._rootBufferDirty = true;
        };
        _proto.getUniform = function getUniform(handle, out) {
          var binding = Pass.getBindingFromHandle(handle);
          var type = Pass.getTypeFromHandle(handle);
          var ofs = Pass.getOffsetFromHandle(handle);
          var block = this._getBlockView(type, binding);
          return type2reader[type](block, out, ofs);
        };
        _proto.setUniformArray = function setUniformArray(handle, value) {
          var binding = Pass.getBindingFromHandle(handle);
          var type = Pass.getTypeFromHandle(handle);
          var stride = GetTypeSize(type) >> 2;
          var block = this._getBlockView(type, binding);
          var ofs = Pass.getOffsetFromHandle(handle);
          for (var i = 0; i < value.length; i++, ofs += stride) {
            if (value[i] === null) {
              continue;
            }
            type2writer[type](block, value[i], ofs);
          }
          this._rootBufferDirty = true;
        };
        _proto.bindTexture = function bindTexture(binding, value, index) {
          this._descriptorSet.bindTexture(binding, value, index || 0);
        };
        _proto.bindSampler = function bindSampler(binding, value, index) {
          this._descriptorSet.bindSampler(binding, value, index || 0);
        };
        _proto.setDynamicState = function setDynamicState(state, value) {
          var ds = this._dynamics[state];
          if (ds && ds.value === value) {
            return;
          }
          ds.value = value;
          ds.dirty = true;
        };
        _proto.overridePipelineStates = function overridePipelineStates(original, overrides) {
          warnID(12102);
        };
        _proto.update = function update() {
          if (!this._descriptorSet) {
            errorID(12006);
            return;
          }
          if (this._rootBuffer && this._rootBufferDirty) {
            this._rootBuffer.update(this._rootBlock);
            this._rootBufferDirty = false;
          }
          this._descriptorSet.update();
        };
        _proto.getInstancedBuffer = function getInstancedBuffer(extraKey) {
          if (extraKey === void 0) {
            extraKey = 0;
          }
          return this._instancedBuffers[extraKey] || (this._instancedBuffers[extraKey] = new InstancedBuffer(this));
        };
        _proto.destroy = function destroy() {
          for (var i = 0; i < this._shaderInfo.blocks.length; i++) {
            var u = this._shaderInfo.blocks[i];
            this._buffers[u.binding].destroy();
          }
          this._buffers = [];
          if (this._rootBuffer) {
            this._rootBuffer.destroy();
            this._rootBuffer = null;
          }
          for (var ib in this._instancedBuffers) {
            this._instancedBuffers[ib].destroy();
          }
          this._descriptorSet.destroy();
          this._rs.destroy();
          this._dss.destroy();
          this._bs.destroy();
        };
        _proto.resetUniform = function resetUniform(name) {
          var handle = this.getHandle(name);
          if (!handle) {
            return;
          }
          var type = Pass.getTypeFromHandle(handle);
          var binding = Pass.getBindingFromHandle(handle);
          var ofs = Pass.getOffsetFromHandle(handle);
          var count = Pass.getCountFromHandle(handle);
          var block = this._getBlockView(type, binding);
          var info = this._properties[name];
          var givenDefault = info && info.value;
          var value = givenDefault || getDefaultFromType(type);
          var size = (GetTypeSize(type) >> 2) * count;
          for (var k = 0; k + value.length <= size; k += value.length) {
            block.set(value, ofs + k);
          }
          this._rootBufferDirty = true;
        };
        _proto.resetTexture = function resetTexture(name, index) {
          var handle = this.getHandle(name);
          if (!handle) {
            return;
          }
          var type = Pass.getTypeFromHandle(handle);
          var binding = Pass.getBindingFromHandle(handle);
          var info = this._properties[name];
          var value = info && info.value;
          var texName = value ? "" + value + getStringFromType(type) : getDefaultFromType(type);
          var textureBase = builtinResMgr.get(texName);
          var texture = textureBase && textureBase.getGFXTexture();
          var samplerInfo = info && info.samplerHash !== undefined ? Sampler.unpackFromHash(info.samplerHash) : textureBase && textureBase.getSamplerInfo();
          var sampler = this._device.getSampler(samplerInfo);
          this._descriptorSet.bindSampler(binding, sampler, index || 0);
          this._descriptorSet.bindTexture(binding, texture, index || 0);
        };
        _proto.resetUBOs = function resetUBOs() {
          for (var i = 0; i < this._shaderInfo.blocks.length; i++) {
            var u = this._shaderInfo.blocks[i];
            var ofs = 0;
            for (var j = 0; j < u.members.length; j++) {
              var cur = u.members[j];
              var block = this._getBlockView(cur.type, u.binding);
              var info = this._properties[cur.name];
              var givenDefault = info && info.value;
              var value = givenDefault || getDefaultFromType(cur.type);
              var size = (GetTypeSize(cur.type) >> 2) * cur.count;
              for (var k = 0; k + value.length <= size; k += value.length) {
                block.set(value, ofs + k);
              }
              ofs += size;
            }
          }
          this._rootBufferDirty = true;
        };
        _proto.resetTextures = function resetTextures() {
          for (var i = 0; i < this._shaderInfo.samplerTextures.length; i++) {
            var u = this._shaderInfo.samplerTextures[i];
            for (var j = 0; j < u.count; j++) {
              this.resetTexture(u.name, j);
            }
          }
        };
        _proto.tryCompile = function tryCompile() {
          var pipeline = this._root.pipeline;
          if (!pipeline) {
            return false;
          }
          this._syncBatchingScheme();
          if (legacyCC.rendering && legacyCC.rendering.enableEffectImport) {
            var _programLib = legacyCC.rendering.programLib;
            var program = _programLib.getProgramVariant(this._device, this._phaseID, this._programName, this._defines);
            if (!program) {
              warnID(12103, this._programName);
              return false;
            }
            this._shader = program.shader;
            this._pipelineLayout = _programLib.getPipelineLayout(this.device, this._phaseID, this._programName);
          } else {
            var shader = programLib.getGFXShader(this._device, this._programName, this._defines, pipeline);
            if (!shader) {
              warnID(12104, this._programName);
              return false;
            }
            this._shader = shader;
            this._pipelineLayout = programLib.getTemplateInfo(this._programName).pipelineLayout;
          }
          this._hash = Pass.getPassHash(this);
          return true;
        };
        _proto.getShaderVariant = function getShaderVariant(patches) {
          if (patches === void 0) {
            patches = null;
          }
          if (!this._shader && !this.tryCompile()) {
            warnID(12105);
            return null;
          }
          if (!patches) {
            return this._shader;
          }
          var pipeline = this._root.pipeline;
          for (var _i = 0; _i < patches.length; _i++) {
            var patch = patches[_i];
            this._defines[patch.name] = patch.value;
          }
          if (this._isBlend) {
            this._defines.CC_IS_TRANSPARENCY_PASS = 1;
          }
          var shader = null;
          if (legacyCC.rendering && legacyCC.rendering.enableEffectImport) {
            var program = legacyCC.rendering.programLib.getProgramVariant(this._device, this._phaseID, this._programName, this._defines);
            if (program) {
              shader = program.shader;
            }
          } else {
            shader = programLib.getGFXShader(this._device, this._programName, this._defines, pipeline);
          }
          for (var _i2 = 0; _i2 < patches.length; _i2++) {
            var _patch = patches[_i2];
            delete this._defines[_patch.name];
          }
          return shader;
        };
        _proto.beginChangeStatesSilently = function beginChangeStatesSilently() {};
        _proto.endChangeStatesSilently = function endChangeStatesSilently() {};
        _proto._doInit = function _doInit(info, copyDefines) {
          if (copyDefines === void 0) {
            copyDefines = false;
          }
          this._priority = RenderPriority.DEFAULT;
          this._stage = RenderPassStage.DEFAULT;
          if (legacyCC.rendering && legacyCC.rendering.enableEffectImport) {
            var r = legacyCC.rendering;
            if (typeof info.phase === 'number') {
              this._passID = info._passID;
              this._subpassID = info._subpassID;
              this._phaseID = info._phaseID;
            } else {
              this._passID = r.getPassID(info.pass);
              if (this._passID !== r.INVALID_ID) {
                if (info.subpass) {
                  this._subpassID = r.getSubpassID(this._passID, info.subpass);
                  this._phaseID = r.getPhaseID(this._subpassID, info.phase);
                } else {
                  this._phaseID = r.getPhaseID(this._passID, info.phase);
                }
              }
            }
            if (this._passID === r.INVALID_ID) {
              errorID(12107, info.program);
              return;
            }
            if (this._phaseID === r.INVALID_ID) {
              errorID(12108, info.program);
              return;
            }
          }
          this._phase = getPhaseID('default');
          this._primitive = PrimitiveMode.TRIANGLE_LIST;
          this._passIndex = info.passIndex;
          this._propertyIndex = info.propertyIndex !== undefined ? info.propertyIndex : info.passIndex;
          this._programName = info.program;
          this._defines = copyDefines ? _extends({}, info.defines) : info.defines;
          if (legacyCC.rendering && legacyCC.rendering.enableEffectImport) {
            this._shaderInfo = legacyCC.rendering.programLib.getProgramInfo(this._phaseID, this._programName);
          } else {
            this._shaderInfo = programLib.getTemplate(info.program);
          }
          this._properties = info.properties || this._properties;
          var device = this._device;
          Pass.fillPipelineInfo(this, info);
          if (info.stateOverrides) {
            Pass.fillPipelineInfo(this, info.stateOverrides);
          }
          if (legacyCC.rendering && legacyCC.rendering.enableEffectImport) {
            _dsInfo$2.layout = legacyCC.rendering.programLib.getMaterialDescriptorSetLayout(this._device, this._phaseID, info.program);
          } else {
            _dsInfo$2.layout = programLib.getDescriptorSetLayout(this._device, info.program);
          }
          this._descriptorSet = this._device.createDescriptorSet(_dsInfo$2);
          var blocks = this._shaderInfo.blocks;
          var blockSizes;
          var handleMap;
          if (legacyCC.rendering && legacyCC.rendering.enableEffectImport) {
            var _programLib2 = legacyCC.rendering.programLib;
            blockSizes = _programLib2.getBlockSizes(this._phaseID, this._programName);
            handleMap = _programLib2.getHandleMap(this._phaseID, this._programName);
          } else {
            var tmplInfo = programLib.getTemplateInfo(info.program);
            blockSizes = tmplInfo.blockSizes;
            handleMap = tmplInfo.handleMap;
          }
          if (legacyCC.rendering && legacyCC.rendering.enableEffectImport) {
            var _programLib3 = legacyCC.rendering.programLib;
            var shaderInfo = _programLib3.getShaderInfo(this._phaseID, this.program);
            this._buildMaterialUniformBlocks(device, shaderInfo.blocks, blockSizes);
          } else {
            this._buildUniformBlocks(device, blocks, blockSizes);
          }
          var directHandleMap = this._propertyHandleMap = handleMap;
          var indirectHandleMap = {};
          for (var name in this._properties) {
            var prop = this._properties[name];
            if (!prop.handleInfo) {
              continue;
            }
            indirectHandleMap[name] = this.getHandle.apply(this, prop.handleInfo);
          }
          Object.assign(directHandleMap, indirectHandleMap);
        };
        _proto._buildUniformBlocks = function _buildUniformBlocks(device, blocks, blockSizes) {
          var alignment = device.capabilities.uboOffsetAlignment;
          var startOffsets = [];
          var lastSize = 0;
          var lastOffset = 0;
          for (var i = 0; i < blocks.length; i++) {
            var size = blockSizes[i];
            startOffsets.push(lastOffset);
            lastOffset += Math.ceil(size / alignment) * alignment;
            lastSize = size;
          }
          var totalSize = startOffsets[startOffsets.length - 1] + lastSize;
          if (totalSize) {
            _bufferInfo.size = Math.ceil(totalSize / 16) * 16;
            this._rootBuffer = device.createBuffer(_bufferInfo);
            this._rootBlock = new ArrayBuffer(totalSize);
          }
          for (var _i3 = 0, count = 0; _i3 < blocks.length; _i3++) {
            var binding = blocks[_i3].binding;
            var _size = blockSizes[_i3];
            _bufferViewInfo.buffer = this._rootBuffer;
            _bufferViewInfo.offset = startOffsets[count++];
            _bufferViewInfo.range = Math.ceil(_size / 16) * 16;
            var bufferView = this._buffers[binding] = device.createBuffer(_bufferViewInfo);
            this._blocks[binding] = new Float32Array(this._rootBlock, _bufferViewInfo.offset, _size / Float32Array.BYTES_PER_ELEMENT);
            this._blocksInt[binding] = new Int32Array(this._blocks[binding].buffer, this._blocks[binding].byteOffset, this._blocks[binding].length);
            this._descriptorSet.bindBuffer(binding, bufferView);
          }
        };
        _proto._buildMaterialUniformBlocks = function _buildMaterialUniformBlocks(device, blocks, blockSizes) {
          var alignment = device.capabilities.uboOffsetAlignment;
          var startOffsets = [];
          var lastSize = 0;
          var lastOffset = 0;
          for (var i = 0; i < blocks.length; i++) {
            var block = blocks[i];
            if (block.set !== _materialSet) {
              continue;
            }
            var size = blockSizes[i];
            startOffsets.push(lastOffset);
            lastOffset += Math.ceil(size / alignment) * alignment;
            lastSize = size;
          }
          if (lastSize !== 0) {
            var totalSize = startOffsets[startOffsets.length - 1] + lastSize;
            if (totalSize) {
              _bufferInfo.size = Math.ceil(totalSize / 16) * 16;
              this._rootBuffer = device.createBuffer(_bufferInfo);
              this._rootBlock = new ArrayBuffer(totalSize);
            }
          }
          for (var _i4 = 0, count = 0; _i4 < blocks.length; _i4++) {
            var _block = blocks[_i4];
            if (_block.set !== _materialSet) {
              continue;
            }
            var binding = blocks[_i4].binding;
            var _size2 = blockSizes[_i4];
            _bufferViewInfo.buffer = this._rootBuffer;
            _bufferViewInfo.offset = startOffsets[count++];
            _bufferViewInfo.range = Math.ceil(_size2 / 16) * 16;
            var bufferView = this._buffers[binding] = device.createBuffer(_bufferViewInfo);
            this._blocks[binding] = new Float32Array(this._rootBlock, _bufferViewInfo.offset, _size2 / Float32Array.BYTES_PER_ELEMENT);
            this._blocksInt[binding] = new Int32Array(this._blocks[binding].buffer, this._blocks[binding].byteOffset, this._blocks[binding].length);
            this._descriptorSet.bindBuffer(binding, bufferView);
          }
        };
        _proto._syncBatchingScheme = function _syncBatchingScheme() {
          if (this._defines.USE_INSTANCING) {
            if (this._device.hasFeature(Feature.INSTANCED_ARRAYS)) {
              this._batchingScheme = BatchingSchemes.INSTANCING;
            } else {
              this._defines.USE_INSTANCING = false;
              this._batchingScheme = BatchingSchemes.NONE;
            }
          } else {
            this._batchingScheme = BatchingSchemes.NONE;
          }
        };
        _proto._getBlockView = function _getBlockView(type, binding) {
          return type < Type$1.FLOAT ? this._blocksInt[binding] : this._blocks[binding];
        };
        _proto._initPassFromTarget = function _initPassFromTarget(target, dss, hashFactor) {
          this._priority = target.priority;
          this._stage = target.stage;
          this._phase = target.phase;
          this._phaseID = target._phaseID;
          this._passID = target._passID;
          this._batchingScheme = target.batchingScheme;
          this._primitive = target.primitive;
          this._dynamicStates = target.dynamicStates;
          this._bs = target.blendState;
          this._dss = dss;
          this._descriptorSet = target.descriptorSet;
          this._rs = target.rasterizerState;
          this._passIndex = target.passIndex;
          this._propertyIndex = target.propertyIndex;
          this._programName = target.program;
          this._defines = target.defines;
          this._shaderInfo = target._shaderInfo;
          this._properties = target._properties;
          this._blocks = target._blocks;
          this._blocksInt = target._blocksInt;
          this._dynamics = target._dynamics;
          this._shader = target._shader;
          if (legacyCC.rendering && legacyCC.rendering.enableEffectImport) {
            this._pipelineLayout = legacyCC.rendering.programLib.getPipelineLayout(this.device, this._phaseID, this._programName);
          } else {
            this._pipelineLayout = programLib.getTemplateInfo(this._programName).pipelineLayout;
          }
          this._hash = target._hash ^ hashFactor;
        };
        _proto._updatePassHash = function _updatePassHash() {
          this._hash = Pass.getPassHash(this);
        };
        _proto.setRootBufferDirty = function setRootBufferDirty(val) {
          this._rootBufferDirty = val;
        };
        _proto.setPriority = function setPriority(val) {
          this._priority = val;
        };
        _createClass(Pass, [{
          key: "_isBlend",
          get: function get() {
            var bBlend = false;
            for (var _iterator = _createForOfIteratorHelperLoose(this.blendState.targets), _step; !(_step = _iterator()).done;) {
              var target = _step.value;
              if (target.blend) {
                bBlend = true;
              }
            }
            return bBlend;
          }
        }, {
          key: "root",
          get: function get() {
            return this._root;
          }
        }, {
          key: "device",
          get: function get() {
            return this._device;
          }
        }, {
          key: "shaderInfo",
          get: function get() {
            return this._shaderInfo;
          }
        }, {
          key: "localSetLayout",
          get: function get() {
            if (legacyCC.rendering && legacyCC.rendering.enableEffectImport) {
              return legacyCC.rendering.programLib.getLocalDescriptorSetLayout(this._device, this._phaseID, this._programName);
            } else {
              return programLib.getDescriptorSetLayout(this._device, this._programName, true);
            }
          }
        }, {
          key: "program",
          get: function get() {
            return this._programName;
          }
        }, {
          key: "properties",
          get: function get() {
            return this._properties;
          }
        }, {
          key: "defines",
          get: function get() {
            return this._defines;
          }
        }, {
          key: "passIndex",
          get: function get() {
            return this._passIndex;
          }
        }, {
          key: "propertyIndex",
          get: function get() {
            return this._propertyIndex;
          }
        }, {
          key: "dynamics",
          get: function get() {
            return this._dynamics;
          }
        }, {
          key: "blocks",
          get: function get() {
            return this._blocks;
          }
        }, {
          key: "blocksInt",
          get: function get() {
            return this._blocksInt;
          }
        }, {
          key: "rootBufferDirty",
          get: function get() {
            return this._rootBufferDirty;
          }
        }, {
          key: "priority",
          get: function get() {
            return this._priority;
          }
        }, {
          key: "primitive",
          get: function get() {
            return this._primitive;
          }
        }, {
          key: "stage",
          get: function get() {
            return this._stage;
          }
        }, {
          key: "phase",
          get: function get() {
            return this._phase;
          }
        }, {
          key: "passID",
          get: function get() {
            return this._passID;
          }
        }, {
          key: "phaseID",
          get: function get() {
            return this._phaseID;
          }
        }, {
          key: "rasterizerState",
          get: function get() {
            return this._rs;
          }
        }, {
          key: "depthStencilState",
          get: function get() {
            return this._dss;
          }
        }, {
          key: "blendState",
          get: function get() {
            return this._bs;
          }
        }, {
          key: "dynamicStates",
          get: function get() {
            return this._dynamicStates;
          }
        }, {
          key: "batchingScheme",
          get: function get() {
            return this._batchingScheme;
          }
        }, {
          key: "descriptorSet",
          get: function get() {
            return this._descriptorSet;
          }
        }, {
          key: "hash",
          get: function get() {
            return this._hash;
          }
        }, {
          key: "pipelineLayout",
          get: function get() {
            return this._pipelineLayout;
          }
        }]);
        return Pass;
      }();
      Pass.getTypeFromHandle = getTypeFromHandle;
      Pass.getBindingFromHandle = getBindingFromHandle;
      Pass.getCountFromHandle = getCountFromHandle;
      Pass.getOffsetFromHandle = getOffsetFromHandle;
      function serializeBlendState(bs) {
        var res = ",bs," + bs.isA2C;
        for (var _iterator2 = _createForOfIteratorHelperLoose(bs.targets), _step2; !(_step2 = _iterator2()).done;) {
          var t = _step2.value;
          res += ",bt," + t.blend + "," + t.blendEq + "," + t.blendAlphaEq + "," + t.blendColorMask;
          res += "," + t.blendSrc + "," + t.blendDst + "," + t.blendSrcAlpha + "," + t.blendDstAlpha;
        }
        return res;
      }
      function serializeRasterizerState(rs) {
        return ",rs," + rs.cullMode + "," + rs.depthBias + "," + rs.isFrontFaceCCW;
      }
      function serializeDepthStencilState(dss) {
        var res = ",dss," + dss.depthTest + "," + dss.depthWrite + "," + dss.depthFunc;
        res += "," + dss.stencilTestFront + "," + dss.stencilFuncFront + "," + dss.stencilRefFront + "," + dss.stencilReadMaskFront;
        res += "," + dss.stencilFailOpFront + "," + dss.stencilZFailOpFront + "," + dss.stencilPassOpFront + "," + dss.stencilWriteMaskFront;
        res += "," + dss.stencilTestBack + "," + dss.stencilFuncBack + "," + dss.stencilRefBack + "," + dss.stencilReadMaskBack;
        res += "," + dss.stencilFailOpBack + "," + dss.stencilZFailOpBack + "," + dss.stencilPassOpBack + "," + dss.stencilWriteMaskBack;
        return res;
      }

      var PipelineStateManager = exports('dk', function () {
        function PipelineStateManager() {}
        PipelineStateManager.getOrCreatePipelineState = function getOrCreatePipelineState(device, pass, shader, renderPass, ia) {
          var hash1 = pass.hash;
          var hash2 = renderPass.hash;
          var hash3 = ia.attributesHash;
          var hash4 = shader.typedID;
          var newHash = hash1 ^ hash2 ^ hash3 ^ hash4;
          var pso = this._PSOHashMap.get(newHash);
          if (!pso) {
            var pipelineLayout = pass.pipelineLayout;
            var inputState = new InputState(ia.attributes);
            var psoInfo = new PipelineStateInfo(shader, pipelineLayout, renderPass, inputState, pass.rasterizerState, pass.depthStencilState, pass.blendState, pass.primitive, pass.dynamicStates);
            pso = device.createPipelineState(psoInfo);
            this._PSOHashMap.set(newHash, pso);
          }
          return pso;
        };
        return PipelineStateManager;
      }());
      PipelineStateManager._PSOHashMap = new Map();

      var profilerViewport = new Viewport();
      var profilerScissor = new Rect();
      function SRGBToLinear(out, gamma) {
        out.x = gamma.x * gamma.x;
        out.y = gamma.y * gamma.y;
        out.z = gamma.z * gamma.z;
      }
      var profilerCamera = null;
      function getProfilerCamera() {
        return profilerCamera;
      }
      function decideProfilerCamera(cameras) {
        for (var i = cameras.length - 1; i >= 0; --i) {
          var camera = cameras[i];
          if (camera.window.swapchain) {
            profilerCamera = camera;
            return;
          }
        }
        profilerCamera = null;
      }
      function renderProfiler(device, renderPass, cmdBuff, profiler, camera) {
        if (isEnableEffect()) {
          return;
        }
        if (!profiler || !profiler.enabled) {
          return;
        }
        if (camera !== profilerCamera) {
          return;
        }
        var _profiler$subModels$ = profiler.subModels[0],
          inputAssembler = _profiler$subModels$.inputAssembler,
          passes = _profiler$subModels$.passes,
          shaders = _profiler$subModels$.shaders,
          descriptorSet = _profiler$subModels$.descriptorSet;
        profilerViewport.width = profilerScissor.width = camera.window.width;
        profilerViewport.height = profilerScissor.height = camera.window.height;
        var pso = PipelineStateManager.getOrCreatePipelineState(device, passes[0], shaders[0], renderPass, inputAssembler);
        cmdBuff.setViewport(profilerViewport);
        cmdBuff.setScissor(profilerScissor);
        cmdBuff.bindPipelineState(pso);
        cmdBuff.bindDescriptorSet(SetIndex.MATERIAL, passes[0].descriptorSet);
        cmdBuff.bindDescriptorSet(SetIndex.LOCAL, descriptorSet);
        cmdBuff.bindInputAssembler(inputAssembler);
        cmdBuff.draw(inputAssembler);
      }

      var _dec$2Q, _dec2$23, _class$2M, _class2$2w, _initializer$2g, _initializer2$1M, _initializer3$1b, _initializer4$W, _initializer5$H;
      var v4_1 = new Vec4();
      var Material = exports('ec', (_dec$2Q = ccclass$n('cc.Material'), _dec2$23 = type$7(EffectAsset), _dec$2Q(_class$2M = (_class2$2w = function (_Asset) {
        _inheritsLoose(Material, _Asset);
        Material.getHash = function getHash(material) {
          var hash = 0;
          for (var _iterator = _createForOfIteratorHelperLoose(material.passes), _step; !(_step = _iterator()).done;) {
            var pass = _step.value;
            hash ^= pass.hash;
          }
          return hash;
        };
        function Material() {
          var _this;
          _this = _Asset.call(this) || this;
          _this._effectAsset = _initializer$2g && _initializer$2g();
          _this._techIdx = _initializer2$1M && _initializer2$1M();
          _this._defines = _initializer3$1b && _initializer3$1b();
          _this._states = _initializer4$W && _initializer4$W();
          _this._props = _initializer5$H && _initializer5$H();
          _this._passes = [];
          _this._hash = 0;
          return _this;
        }
        var _proto = Material.prototype;
        _proto.initialize = function initialize(info) {
          if (this._passes.length) {
            warnID(12005);
            return;
          }
          if (!this._defines) {
            this._defines = [];
          }
          if (!this._states) {
            this._states = [];
          }
          if (!this._props) {
            this._props = [];
          }
          this._fillInfo(info);
          this._update();
        };
        _proto.reset = function reset(info) {
          this.initialize(info);
        };
        _proto.destroy = function destroy() {
          this._doDestroy();
          return _Asset.prototype.destroy.call(this);
        };
        _proto.recompileShaders = function recompileShaders(overrides, passIdx) {
          console.warn("Shaders in material asset '" + this.name + "' cannot be modified at runtime, please instantiate the material first.");
        };
        _proto.overridePipelineStates = function overridePipelineStates(overrides, passIdx) {
          console.warn("Pipeline states in material asset '" + this.name + "' cannot be modified at runtime, please instantiate the material first.");
        };
        _proto.onLoaded = function onLoaded() {
          this._update();
        };
        _proto.resetUniforms = function resetUniforms(clearPasses) {
          if (clearPasses === void 0) {
            clearPasses = true;
          }
          this._props.length = this._passes.length;
          for (var i = 0; i < this._props.length; i++) {
            this._props[i] = {};
          }
          if (!clearPasses) {
            return;
          }
          for (var _iterator2 = _createForOfIteratorHelperLoose(this._passes), _step2; !(_step2 = _iterator2()).done;) {
            var pass = _step2.value;
            pass.resetUBOs();
            pass.resetTextures();
          }
        };
        _proto.setProperty = function setProperty(name, val, passIdx) {
          var success = false;
          if (passIdx === undefined) {
            var passes = this._passes;
            var len = passes.length;
            for (var i = 0; i < len; i++) {
              var pass = passes[i];
              if (this._uploadProperty(pass, name, val)) {
                this._props[pass.propertyIndex][name] = val;
                success = true;
              }
            }
          } else {
            if (passIdx >= this._passes.length) {
              console.warn("illegal pass index: " + passIdx + ".");
              return;
            }
            var _pass = this._passes[passIdx];
            if (this._uploadProperty(_pass, name, val)) {
              this._props[_pass.propertyIndex][name] = val;
              success = true;
            }
          }
          if (!success) {
            console.warn("illegal property name: " + name + ".");
          }
        };
        _proto.getProperty = function getProperty(name, passIdx) {
          if (passIdx === undefined) {
            var propsArray = this._props;
            var len = propsArray.length;
            for (var i = 0; i < len; i++) {
              var props = propsArray[i];
              if (name in props) {
                return props[name];
              }
            }
          } else {
            if (passIdx >= this._passes.length) {
              console.warn("illegal pass index: " + passIdx + ".");
              return null;
            }
            var _props = this._props[this._passes[passIdx].propertyIndex];
            if (name in _props) {
              return _props[name];
            }
          }
          return null;
        };
        _proto.copy = function copy(mat, overrides) {
          this._techIdx = mat._techIdx;
          this._props.length = mat._props.length;
          for (var i = 0; i < mat._props.length; i++) {
            this._props[i] = _extends({}, mat._props[i]);
          }
          this._defines.length = mat._defines.length;
          for (var _i = 0; _i < mat._defines.length; _i++) {
            this._defines[_i] = _extends({}, mat._defines[_i]);
          }
          this._states.length = mat._states.length;
          for (var _i2 = 0; _i2 < mat._states.length; _i2++) {
            this._states[_i2] = _extends({}, mat._states[_i2]);
          }
          this._effectAsset = mat._effectAsset;
          if (overrides) this._fillInfo(overrides);
          this._update();
        };
        _proto._fillInfo = function _fillInfo(info) {
          if (info.technique !== undefined) {
            this._techIdx = info.technique;
          }
          if (info.effectAsset) {
            this._effectAsset = info.effectAsset;
          } else if (info.effectName) {
            this._effectAsset = EffectAsset.get(info.effectName);
          }
          if (info.defines) {
            this._prepareInfo(info.defines, this._defines);
          }
          if (info.states) {
            this._prepareInfo(info.states, this._states);
          }
        };
        _proto._prepareInfo = function _prepareInfo(patch, cur) {
          var patchArray = patch;
          if (!Array.isArray(patchArray)) {
            var len = this._effectAsset ? this._effectAsset.techniques[this._techIdx].passes.length : 1;
            patchArray = Array(len).fill(patchArray);
          }
          for (var i = 0; i < patchArray.length; ++i) {
            Object.assign(cur[i] || (cur[i] = {}), patchArray[i]);
          }
        };
        _proto._createPasses = function _createPasses() {
          var tech = this._effectAsset.techniques[this._techIdx || 0];
          if (!tech) {
            return [];
          }
          var passNum = tech.passes.length;
          var passes = [];
          for (var k = 0; k < passNum; ++k) {
            var passInfo = tech.passes[k];
            var propIdx = passInfo.passIndex = k;
            var defines = passInfo.defines = this._defines[propIdx] || (this._defines[propIdx] = {});
            passInfo.stateOverrides = this._states[propIdx] || (this._states[propIdx] = {});
            if (passInfo.propertyIndex !== undefined) {
              Object.assign(defines, this._defines[passInfo.propertyIndex]);
            }
            if (passInfo.embeddedMacros !== undefined) {
              Object.assign(defines, passInfo.embeddedMacros);
            }
            if (passInfo["switch"] && !defines[passInfo["switch"]]) {
              continue;
            }
            var pass = new Pass(legacyCC.director.root);
            pass.initialize(passInfo);
            passes.push(pass);
          }
          return passes;
        };
        _proto._update = function _update(keepProps) {
          var _this2 = this;
          if (keepProps === void 0) {
            keepProps = true;
          }
          if (this._effectAsset) {
            this._passes = this._createPasses();
            var totalPasses = this._effectAsset.techniques[this._techIdx].passes.length;
            this._props.length = totalPasses;
            if (keepProps) {
              this._passes.forEach(function (pass, i) {
                var props = _this2._props[i];
                if (!props) {
                  props = _this2._props[i] = {};
                }
                if (pass.propertyIndex !== undefined) {
                  Object.assign(props, _this2._props[pass.propertyIndex]);
                }
                for (var p in props) {
                  _this2._uploadProperty(pass, p, props[p]);
                }
              });
            } else {
              for (var i = 0; i < this._props.length; i++) {
                this._props[i] = {};
              }
            }
          }
          this._hash = Material.getHash(this);
        };
        _proto._uploadProperty = function _uploadProperty(pass, name, val) {
          var handle = pass.getHandle(name);
          if (!handle) {
            return false;
          }
          var type = Pass.getTypeFromHandle(handle);
          if (type < Type$1.SAMPLER1D) {
            if (Array.isArray(val)) {
              pass.setUniformArray(handle, val);
            } else if (val !== null) {
              var _pass$properties$name;
              if ((_pass$properties$name = pass.properties[name]) !== null && _pass$properties$name !== void 0 && _pass$properties$name.linear) {
                var v4 = val;
                SRGBToLinear(v4_1, v4);
                v4_1.w = v4.w;
                val = v4_1;
              }
              pass.setUniform(handle, val);
            } else {
              pass.resetUniform(name);
            }
          } else if (Array.isArray(val)) {
            for (var i = 0; i < val.length; i++) {
              this._bindTexture(pass, handle, val[i], i);
            }
          } else if (val) {
            this._bindTexture(pass, handle, val);
          } else {
            pass.resetTexture(name);
          }
          return true;
        };
        _proto._bindTexture = function _bindTexture(pass, handle, val, index) {
          var binding = Pass.getBindingFromHandle(handle);
          if (val instanceof Texture) {
            pass.bindTexture(binding, val, index);
          } else if (val instanceof TextureBase) {
            var texture = val.getGFXTexture();
            if (!texture || !texture.width || !texture.height) {
              return;
            }
            pass.bindTexture(binding, texture, index);
            pass.bindSampler(binding, val.getGFXSampler(), index);
          }
        };
        _proto._doDestroy = function _doDestroy() {
          if (this._passes && this._passes.length) {
            for (var _iterator3 = _createForOfIteratorHelperLoose(this._passes), _step3; !(_step3 = _iterator3()).done;) {
              var pass = _step3.value;
              pass.destroy();
            }
          }
          this._passes.length = 0;
        };
        _proto.initDefault = function initDefault(uuid) {
          _Asset.prototype.initDefault.call(this, uuid);
          this.initialize({
            effectName: 'builtin-unlit',
            defines: {
              USE_COLOR: true
            },
            technique: 0
          });
          this.setProperty('mainColor', new Color$1('#ff00ff'));
        };
        _proto.validate = function validate() {
          return !!this._effectAsset && !this._effectAsset.isDefault && this.passes.length > 0;
        };
        _createClass(Material, [{
          key: "effectAsset",
          get: function get() {
            return this._effectAsset;
          }
        }, {
          key: "effectName",
          get: function get() {
            return this._effectAsset ? this._effectAsset.name : '';
          }
        }, {
          key: "technique",
          get: function get() {
            return this._techIdx;
          }
        }, {
          key: "passes",
          get: function get() {
            return this._passes;
          }
        }, {
          key: "hash",
          get: function get() {
            return this._hash;
          }
        }, {
          key: "parent",
          get: function get() {
            return null;
          }
        }, {
          key: "owner",
          get: function get() {
            return null;
          }
        }]);
        return Material;
      }(Asset), (_initializer$2g = applyDecoratedInitializer(_class2$2w.prototype, "_effectAsset", [_dec2$23], function () {
        return null;
      }), _initializer2$1M = applyDecoratedInitializer(_class2$2w.prototype, "_techIdx", [serializable$j], function () {
        return 0;
      }), _initializer3$1b = applyDecoratedInitializer(_class2$2w.prototype, "_defines", [serializable$j], function () {
        return [];
      }), _initializer4$W = applyDecoratedInitializer(_class2$2w.prototype, "_states", [serializable$j], function () {
        return [];
      }), _initializer5$H = applyDecoratedInitializer(_class2$2w.prototype, "_props", [serializable$j], function () {
        return [];
      })), _class2$2w)) || _class$2M));
      legacyCC.Material = Material;

      var CameraFOVAxis;
      (function (CameraFOVAxis) {
        CameraFOVAxis[CameraFOVAxis["VERTICAL"] = 0] = "VERTICAL";
        CameraFOVAxis[CameraFOVAxis["HORIZONTAL"] = 1] = "HORIZONTAL";
      })(CameraFOVAxis || (CameraFOVAxis = {}));
      var CameraProjection;
      (function (CameraProjection) {
        CameraProjection[CameraProjection["ORTHO"] = 0] = "ORTHO";
        CameraProjection[CameraProjection["PERSPECTIVE"] = 1] = "PERSPECTIVE";
      })(CameraProjection || (CameraProjection = {}));
      var CameraAperture;
      (function (CameraAperture) {
        CameraAperture[CameraAperture["F1_8"] = 0] = "F1_8";
        CameraAperture[CameraAperture["F2_0"] = 1] = "F2_0";
        CameraAperture[CameraAperture["F2_2"] = 2] = "F2_2";
        CameraAperture[CameraAperture["F2_5"] = 3] = "F2_5";
        CameraAperture[CameraAperture["F2_8"] = 4] = "F2_8";
        CameraAperture[CameraAperture["F3_2"] = 5] = "F3_2";
        CameraAperture[CameraAperture["F3_5"] = 6] = "F3_5";
        CameraAperture[CameraAperture["F4_0"] = 7] = "F4_0";
        CameraAperture[CameraAperture["F4_5"] = 8] = "F4_5";
        CameraAperture[CameraAperture["F5_0"] = 9] = "F5_0";
        CameraAperture[CameraAperture["F5_6"] = 10] = "F5_6";
        CameraAperture[CameraAperture["F6_3"] = 11] = "F6_3";
        CameraAperture[CameraAperture["F7_1"] = 12] = "F7_1";
        CameraAperture[CameraAperture["F8_0"] = 13] = "F8_0";
        CameraAperture[CameraAperture["F9_0"] = 14] = "F9_0";
        CameraAperture[CameraAperture["F10_0"] = 15] = "F10_0";
        CameraAperture[CameraAperture["F11_0"] = 16] = "F11_0";
        CameraAperture[CameraAperture["F13_0"] = 17] = "F13_0";
        CameraAperture[CameraAperture["F14_0"] = 18] = "F14_0";
        CameraAperture[CameraAperture["F16_0"] = 19] = "F16_0";
        CameraAperture[CameraAperture["F18_0"] = 20] = "F18_0";
        CameraAperture[CameraAperture["F20_0"] = 21] = "F20_0";
        CameraAperture[CameraAperture["F22_0"] = 22] = "F22_0";
      })(CameraAperture || (CameraAperture = {}));
      var CameraISO;
      (function (CameraISO) {
        CameraISO[CameraISO["ISO100"] = 0] = "ISO100";
        CameraISO[CameraISO["ISO200"] = 1] = "ISO200";
        CameraISO[CameraISO["ISO400"] = 2] = "ISO400";
        CameraISO[CameraISO["ISO800"] = 3] = "ISO800";
      })(CameraISO || (CameraISO = {}));
      var CameraShutter;
      (function (CameraShutter) {
        CameraShutter[CameraShutter["D1"] = 0] = "D1";
        CameraShutter[CameraShutter["D2"] = 1] = "D2";
        CameraShutter[CameraShutter["D4"] = 2] = "D4";
        CameraShutter[CameraShutter["D8"] = 3] = "D8";
        CameraShutter[CameraShutter["D15"] = 4] = "D15";
        CameraShutter[CameraShutter["D30"] = 5] = "D30";
        CameraShutter[CameraShutter["D60"] = 6] = "D60";
        CameraShutter[CameraShutter["D125"] = 7] = "D125";
        CameraShutter[CameraShutter["D250"] = 8] = "D250";
        CameraShutter[CameraShutter["D500"] = 9] = "D500";
        CameraShutter[CameraShutter["D1000"] = 10] = "D1000";
        CameraShutter[CameraShutter["D2000"] = 11] = "D2000";
        CameraShutter[CameraShutter["D4000"] = 12] = "D4000";
      })(CameraShutter || (CameraShutter = {}));
      var CameraType;
      (function (CameraType) {
        CameraType[CameraType["DEFAULT"] = -1] = "DEFAULT";
        CameraType[CameraType["LEFT_EYE"] = 0] = "LEFT_EYE";
        CameraType[CameraType["RIGHT_EYE"] = 1] = "RIGHT_EYE";
        CameraType[CameraType["MAIN"] = 2] = "MAIN";
      })(CameraType || (CameraType = {}));
      var TrackingType;
      (function (TrackingType) {
        TrackingType[TrackingType["NO_TRACKING"] = 0] = "NO_TRACKING";
        TrackingType[TrackingType["POSITION_AND_ROTATION"] = 1] = "POSITION_AND_ROTATION";
        TrackingType[TrackingType["POSITION"] = 2] = "POSITION";
        TrackingType[TrackingType["ROTATION"] = 3] = "ROTATION";
      })(TrackingType || (TrackingType = {}));
      var CameraUsage;
      (function (CameraUsage) {
        CameraUsage[CameraUsage["EDITOR"] = 0] = "EDITOR";
        CameraUsage[CameraUsage["GAME_VIEW"] = 1] = "GAME_VIEW";
        CameraUsage[CameraUsage["SCENE_VIEW"] = 2] = "SCENE_VIEW";
        CameraUsage[CameraUsage["PREVIEW"] = 3] = "PREVIEW";
        CameraUsage[CameraUsage["GAME"] = 100] = "GAME";
      })(CameraUsage || (CameraUsage = {}));
      var FSTOPS = [1.8, 2.0, 2.2, 2.5, 2.8, 3.2, 3.5, 4.0, 4.5, 5.0, 5.6, 6.3, 7.1, 8.0, 9.0, 10.0, 11.0, 13.0, 14.0, 16.0, 18.0, 20.0, 22.0];
      var SHUTTERS = [1.0, 1.0 / 2.0, 1.0 / 4.0, 1.0 / 8.0, 1.0 / 15.0, 1.0 / 30.0, 1.0 / 60.0, 1.0 / 125.0, 1.0 / 250.0, 1.0 / 500.0, 1.0 / 1000.0, 1.0 / 2000.0, 1.0 / 4000.0];
      var ISOS = [100.0, 200.0, 400.0, 800.0];
      var v_a = new Vec3();
      var v_b = new Vec3();
      var _tempMat1 = new Mat4();
      var SKYBOX_FLAG = ClearFlagBit.STENCIL << 1;
      var correctionMatrices = [];
      var Camera$1 = function () {
        function Camera(device) {
          this.isWindowSize = true;
          this.screenScale = void 0;
          this.postProcess = null;
          this.usePostProcess = false;
          this.pipeline = '';
          this._device = void 0;
          this._scene = null;
          this._node = null;
          this._name = null;
          this._enabled = false;
          this._proj = -1;
          this._aspect = void 0;
          this._orthoHeight = 10.0;
          this._fovAxis = CameraFOVAxis.VERTICAL;
          this._fov = toRadian(45);
          this._nearClip = 1.0;
          this._farClip = 1000.0;
          this._clearColor = new Color(0.2, 0.2, 0.2, 1);
          this._viewport = new Rect$1(0, 0, 1, 1);
          this._orientedViewport = new Rect$1(0, 0, 1, 1);
          this._curTransform = SurfaceTransform.IDENTITY;
          this._isProjDirty = true;
          this._matView = new Mat4();
          this._matProj = new Mat4();
          this._matProjInv = new Mat4();
          this._matViewProj = new Mat4();
          this._matViewProjInv = new Mat4();
          this._frustum = new Frustum();
          this._forward = new Vec3();
          this._position = new Vec3();
          this._priority = 0;
          this._aperture = CameraAperture.F16_0;
          this._apertureValue = void 0;
          this._shutter = CameraShutter.D125;
          this._shutterValue = 0.0;
          this._iso = CameraISO.ISO100;
          this._isoValue = 0.0;
          this._window = null;
          this._width = 1;
          this._height = 1;
          this._clearFlag = ClearFlagBit.NONE;
          this._clearDepth = 1.0;
          this._visibility = CAMERA_DEFAULT_MASK;
          this._exposure = 0;
          this._clearStencil = 0;
          this._geometryRenderer = null;
          this._windowId = 0;
          this._cameraType = CameraType.DEFAULT;
          this._trackingType = TrackingType.NO_TRACKING;
          this._usage = CameraUsage.GAME;
          this._device = device;
          this._apertureValue = FSTOPS[this._aperture];
          this._shutterValue = SHUTTERS[this._shutter];
          this._isoValue = ISOS[this._iso];
          this._aspect = this.screenScale = 1;
          this._frustum.accurate = true;
          if (!correctionMatrices.length) {
            var ySign = device.capabilities.clipSpaceSignY;
            correctionMatrices[SurfaceTransform.IDENTITY] = new Mat4(1, 0, 0, 0, 0, ySign);
            correctionMatrices[SurfaceTransform.ROTATE_90] = new Mat4(0, 1, 0, 0, -ySign, 0);
            correctionMatrices[SurfaceTransform.ROTATE_180] = new Mat4(-1, 0, 0, 0, 0, -ySign);
            correctionMatrices[SurfaceTransform.ROTATE_270] = new Mat4(0, -1, 0, 0, ySign, 0);
          }
        }
        var _proto = Camera.prototype;
        _proto._updateAspect = function _updateAspect(oriented) {
          if (oriented === void 0) {
            oriented = true;
          }
          this._aspect = this.window.width * this._viewport.width / (this.window.height * this._viewport.height);
          if (oriented) {
            var swapchain = this.window.swapchain;
            var orientation = swapchain && swapchain.surfaceTransform || SurfaceTransform.IDENTITY;
            if (orientation % 2) this._aspect = 1 / this._aspect;
          }
          this._isProjDirty = true;
        };
        _proto.initialize = function initialize(info) {
          if (info.usage !== undefined) {
            this._usage = info.usage;
          } else {
            this.setDefaultUsage();
          }
          if (info.trackingType !== undefined) {
            this._trackingType = info.trackingType;
          }
          if (info.cameraType !== undefined) {
            this._cameraType = info.cameraType;
          }
          this.node = info.node;
          this._width = 1;
          this._height = 1;
          this.clearFlag = ClearFlagBit.NONE;
          this.clearDepth = 1.0;
          this.visibility = CAMERA_DEFAULT_MASK;
          this._name = info.name;
          this._proj = info.projection;
          this._priority = info.priority || 0;
          this._aspect = this.screenScale = 1;
          this.updateExposure();
          this.changeTargetWindow(info.window);
        };
        _proto.destroy = function destroy() {
          var _this$_geometryRender;
          this._node = null;
          this.detachFromScene();
          if (this._window) {
            this._window.detachCamera(this);
            this.window = null;
          }
          this._name = null;
          (_this$_geometryRender = this._geometryRenderer) === null || _this$_geometryRender === void 0 ? void 0 : _this$_geometryRender.destroy();
        };
        _proto.attachToScene = function attachToScene(scene) {
          this._enabled = true;
          this._scene = scene;
        };
        _proto.detachFromScene = function detachFromScene() {
          this._enabled = false;
          this._scene = null;
        };
        _proto.resize = function resize(width, height) {
          if (!this._window) return;
          this._width = width;
          this._height = height;
          this._aspect = width * this._viewport.width / (height * this._viewport.height);
          this._isProjDirty = true;
        };
        _proto.setFixedSize = function setFixedSize(width, height) {
          this._width = width;
          this._height = height;
          this._updateAspect();
          this.isWindowSize = false;
        };
        _proto.syncCameraEditor = function syncCameraEditor(camera) {
        };
        _proto.update = function update(forceUpdate) {
          var _this$window;
          if (forceUpdate === void 0) {
            forceUpdate = false;
          }
          if (!this._node) return;
          var viewProjDirty = false;
          var xr = globalThis.__globalXR;
          if (xr && xr.isWebXR && xr.webXRWindowMap && xr.updateViewport) {
            var x = xr.webXRMatProjs ? 1 / xr.webXRMatProjs.length : 1;
            var wndXREye = xr.webXRWindowMap.get(this._window);
            this.setViewportInOrientedSpace(new Rect$1(x * wndXREye, 0, x, 1));
          }
          if (this._node.hasChangedFlags || forceUpdate) {
            Mat4.invert(this._matView, this._node.worldMatrix);
            this._forward.x = -this._matView.m02;
            this._forward.y = -this._matView.m06;
            this._forward.z = -this._matView.m10;
            Mat4.multiply(this._matView, new Mat4().scale(this._node.worldScale), this._matView);
            this._node.getWorldPosition(this._position);
            viewProjDirty = true;
          }
          var swapchain = (_this$window = this.window) === null || _this$window === void 0 ? void 0 : _this$window.swapchain;
          var orientation = swapchain && swapchain.surfaceTransform || SurfaceTransform.IDENTITY;
          if (this._isProjDirty || this._curTransform !== orientation) {
            this._curTransform = orientation;
            var projectionSignY = this._device.capabilities.clipSpaceSignY;
            if (this._proj === CameraProjection.PERSPECTIVE) {
              if (xr && xr.isWebXR && xr.webXRWindowMap && xr.webXRMatProjs) {
                var _wndXREye = xr.webXRWindowMap.get(this._window);
                this._matProj.set(xr.webXRMatProjs[_wndXREye]);
              } else {
                Mat4.perspective(this._matProj, this._fov, this._aspect, this._nearClip, this._farClip, this._fovAxis === CameraFOVAxis.VERTICAL, this._device.capabilities.clipSpaceMinZ, projectionSignY, orientation);
              }
            } else {
              var _x = this._orthoHeight * this._aspect;
              var y = this._orthoHeight;
              Mat4.ortho(this._matProj, -_x, _x, -y, y, this._nearClip, this._farClip, this._device.capabilities.clipSpaceMinZ, projectionSignY, orientation);
            }
            Mat4.invert(this._matProjInv, this._matProj);
            viewProjDirty = true;
            this._isProjDirty = false;
          }
          if (viewProjDirty) {
            Mat4.multiply(this._matViewProj, this._matProj, this._matView);
            Mat4.invert(this._matViewProjInv, this._matViewProj);
            this._frustum.update(this._matViewProj, this._matViewProjInv);
          }
        };
        _proto.setViewportInOrientedSpace = function setViewportInOrientedSpace(val) {
          var _this$window2;
          var x = val.x,
            width = val.width,
            height = val.height;
          var y = this._device.capabilities.screenSpaceSignY < 0 ? 1 - val.y - height : val.y;
          var swapchain = (_this$window2 = this.window) === null || _this$window2 === void 0 ? void 0 : _this$window2.swapchain;
          var orientation = swapchain && swapchain.surfaceTransform || SurfaceTransform.IDENTITY;
          switch (orientation) {
            case SurfaceTransform.ROTATE_90:
              this._viewport.x = 1 - y - height;
              this._viewport.y = x;
              this._viewport.width = height;
              this._viewport.height = width;
              break;
            case SurfaceTransform.ROTATE_180:
              this._viewport.x = 1 - x - width;
              this._viewport.y = 1 - y - height;
              this._viewport.width = width;
              this._viewport.height = height;
              break;
            case SurfaceTransform.ROTATE_270:
              this._viewport.x = y;
              this._viewport.y = 1 - x - width;
              this._viewport.width = height;
              this._viewport.height = width;
              break;
            case SurfaceTransform.IDENTITY:
              this._viewport.x = x;
              this._viewport.y = y;
              this._viewport.width = width;
              this._viewport.height = height;
              break;
          }
          this._orientedViewport.x = x;
          this._orientedViewport.y = y;
          this._orientedViewport.width = width;
          this._orientedViewport.height = height;
          this.resize(this.width, this.height);
        };
        _proto.initGeometryRenderer = function initGeometryRenderer() {
          if (!this._geometryRenderer) {
            var _this$_geometryRender2;
            this._geometryRenderer = legacyCC.internal.GeometryRenderer ? new legacyCC.internal.GeometryRenderer() : null;
            (_this$_geometryRender2 = this._geometryRenderer) === null || _this$_geometryRender2 === void 0 ? void 0 : _this$_geometryRender2.activate(this._device);
          }
        };
        _proto.changeTargetWindow = function changeTargetWindow(window) {
          if (window === void 0) {
            window = null;
          }
          if (this._window) {
            this._window.detachCamera(this);
          }
          var win = window || legacyCC.director.root.mainWindow;
          if (win) {
            win.attachCamera(this);
            this.window = win;
            var swapchain = win.swapchain;
            var orientation = swapchain && swapchain.surfaceTransform || SurfaceTransform.IDENTITY;
            if (orientation % 2) this.resize(win.height, win.width);else this.resize(win.width, win.height);
          }
        };
        _proto.detachCamera = function detachCamera() {
          if (this._window) {
            this._window.detachCamera(this);
          }
        };
        _proto.screenPointToRay = function screenPointToRay(out, x, y) {
          if (!this._node) return null;
          var width = this.width;
          var height = this.height;
          var cx = this._orientedViewport.x * width;
          var cy = this._orientedViewport.y * height;
          var cw = this._orientedViewport.width * width;
          var ch = this._orientedViewport.height * height;
          var isProj = this._proj === CameraProjection.PERSPECTIVE;
          var ySign = this._device.capabilities.clipSpaceSignY;
          var preTransform = preTransforms[this._curTransform];
          Vec3.set(v_a, (x - cx) / cw * 2 - 1, (y - cy) / ch * 2 - 1, isProj ? 1 : -1);
          var ox = v_a.x,
            oy = v_a.y;
          v_a.x = ox * preTransform[0] + oy * preTransform[2] * ySign;
          v_a.y = ox * preTransform[1] + oy * preTransform[3] * ySign;
          Vec3.transformMat4(isProj ? v_a : out.o, v_a, this._matViewProjInv);
          if (isProj) {
            this._node.getWorldPosition(v_b);
            Ray.fromPoints(out, v_b, v_a);
          } else {
            Vec3.transformQuat(out.d, Vec3.FORWARD, this._node.worldRotation);
          }
          return out;
        };
        _proto.screenToWorld = function screenToWorld(out, screenPos) {
          var width = this.width;
          var height = this.height;
          var cx = this._orientedViewport.x * width;
          var cy = this._orientedViewport.y * height;
          var cw = this._orientedViewport.width * width;
          var ch = this._orientedViewport.height * height;
          var ySign = this._device.capabilities.clipSpaceSignY;
          var preTransform = preTransforms[this._curTransform];
          if (this._proj === CameraProjection.PERSPECTIVE) {
            Vec3.set(out, (screenPos.x - cx) / cw * 2 - 1, (screenPos.y - cy) / ch * 2 - 1, 1.0);
            var x = out.x,
              y = out.y;
            out.x = x * preTransform[0] + y * preTransform[2] * ySign;
            out.y = x * preTransform[1] + y * preTransform[3] * ySign;
            Vec3.transformMat4(out, out, this._matViewProjInv);
            if (this._node) {
              this._node.getWorldPosition(v_a);
            }
            Vec3.lerp(out, v_a, out, lerp(this._nearClip / this._farClip, 1, screenPos.z));
          } else {
            Vec3.set(out, (screenPos.x - cx) / cw * 2 - 1, (screenPos.y - cy) / ch * 2 - 1, screenPos.z * 2 - 1);
            var _x2 = out.x,
              _y = out.y;
            out.x = _x2 * preTransform[0] + _y * preTransform[2] * ySign;
            out.y = _x2 * preTransform[1] + _y * preTransform[3] * ySign;
            Vec3.transformMat4(out, out, this._matViewProjInv);
          }
          return out;
        };
        _proto.worldToScreen = function worldToScreen(out, worldPos) {
          var ySign = this._device.capabilities.clipSpaceSignY;
          var preTransform = preTransforms[this._curTransform];
          Vec3.transformMat4(out, worldPos, this._matViewProj);
          var x = out.x,
            y = out.y;
          out.x = x * preTransform[0] + y * preTransform[2] * ySign;
          out.y = x * preTransform[1] + y * preTransform[3] * ySign;
          var width = this.width;
          var height = this.height;
          var cx = this._orientedViewport.x * width;
          var cy = this._orientedViewport.y * height;
          var cw = this._orientedViewport.width * width;
          var ch = this._orientedViewport.height * height;
          out.x = cx + (out.x + 1) * 0.5 * cw;
          out.y = cy + (out.y + 1) * 0.5 * ch;
          out.z = out.z * 0.5 + 0.5;
          return out;
        };
        _proto.worldMatrixToScreen = function worldMatrixToScreen(out, worldMatrix, width, height) {
          Mat4.multiply(out, this._matViewProj, worldMatrix);
          Mat4.multiply(out, correctionMatrices[this._curTransform], out);
          var halfWidth = width / 2;
          var halfHeight = height / 2;
          Mat4.identity(_tempMat1);
          Mat4.transform(_tempMat1, _tempMat1, Vec3.set(v_a, halfWidth, halfHeight, 0));
          Mat4.scale(_tempMat1, _tempMat1, Vec3.set(v_a, halfWidth, halfHeight, 1));
          Mat4.multiply(out, _tempMat1, out);
          return out;
        };
        _proto.calculateObliqueMat = function calculateObliqueMat(viewSpacePlane) {
          var clipFar = new Vec4(Math.sign(viewSpacePlane.x), Math.sign(viewSpacePlane.y), 1.0, 1.0);
          var viewFar = clipFar.transformMat4(this._matProjInv);
          var m4 = new Vec4(this._matProj.m03, this._matProj.m07, this._matProj.m11, this._matProj.m15);
          var scale = 2.0 / Vec4.dot(viewSpacePlane, viewFar);
          var newViewSpaceNearPlane = viewSpacePlane.multiplyScalar(scale);
          var m3 = newViewSpaceNearPlane.subtract(m4);
          this._matProj.m02 = m3.x;
          this._matProj.m06 = m3.y;
          this._matProj.m10 = m3.z;
          this._matProj.m14 = m3.w;
        };
        _proto.getClipSpaceMinz = function getClipSpaceMinz() {
          return this._device.capabilities.clipSpaceMinZ;
        };
        _proto.setExposure = function setExposure(ev100) {
          this._exposure = 0.833333 / Math.pow(2.0, ev100);
        };
        _proto.updateExposure = function updateExposure() {
          var ev100 = Math.log2(this._apertureValue * this._apertureValue / this._shutterValue * 100.0 / this._isoValue);
          this.setExposure(ev100);
        };
        _proto.setDefaultUsage = function setDefaultUsage() {
          {
            this._usage = CameraUsage.GAME;
          }
        };
        _createClass(Camera, [{
          key: "name",
          get: function get() {
            return this._name;
          }
        }, {
          key: "scene",
          get: function get() {
            return this._scene;
          }
        }, {
          key: "node",
          get: function get() {
            return this._node;
          },
          set: function set(val) {
            this._node = val;
          }
        }, {
          key: "systemWindowId",
          get: function get() {
            return this._windowId;
          }
        }, {
          key: "window",
          get: function get() {
            return this._window;
          },
          set: function set(val) {
            this._window = val;
          }
        }, {
          key: "enabled",
          get: function get() {
            return this._enabled;
          },
          set: function set(val) {
            this._enabled = val;
          }
        }, {
          key: "visibility",
          get: function get() {
            return this._visibility;
          },
          set: function set(vis) {
            this._visibility = vis;
          }
        }, {
          key: "priority",
          get: function get() {
            return this._priority;
          },
          set: function set(val) {
            this._priority = val;
          }
        }, {
          key: "width",
          get: function get() {
            return this._width;
          }
        }, {
          key: "height",
          get: function get() {
            return this._height;
          }
        }, {
          key: "position",
          get: function get() {
            return this._position;
          },
          set: function set(val) {
            this._position = val;
          }
        }, {
          key: "forward",
          get: function get() {
            return this._forward;
          },
          set: function set(val) {
            this._forward = val;
          }
        }, {
          key: "aperture",
          get: function get() {
            return this._aperture;
          },
          set: function set(val) {
            this._aperture = val;
            this._apertureValue = FSTOPS[this._aperture];
            this.updateExposure();
          }
        }, {
          key: "apertureValue",
          get: function get() {
            return this._apertureValue;
          }
        }, {
          key: "shutter",
          get: function get() {
            return this._shutter;
          },
          set: function set(val) {
            this._shutter = val;
            this._shutterValue = SHUTTERS[this._shutter];
            this.updateExposure();
          }
        }, {
          key: "shutterValue",
          get: function get() {
            return this._shutterValue;
          }
        }, {
          key: "iso",
          get: function get() {
            return this._iso;
          },
          set: function set(val) {
            this._iso = val;
            this._isoValue = ISOS[this._iso];
            this.updateExposure();
          }
        }, {
          key: "isoValue",
          get: function get() {
            return this._isoValue;
          }
        }, {
          key: "exposure",
          get: function get() {
            return this._exposure;
          }
        }, {
          key: "clearFlag",
          get: function get() {
            return this._clearFlag;
          },
          set: function set(flag) {
            this._clearFlag = flag;
          }
        }, {
          key: "clearColor",
          get: function get() {
            return this._clearColor;
          },
          set: function set(val) {
            this._clearColor.x = val.x;
            this._clearColor.y = val.y;
            this._clearColor.z = val.z;
            this._clearColor.w = val.w;
          }
        }, {
          key: "clearDepth",
          get: function get() {
            return this._clearDepth;
          },
          set: function set(depth) {
            this._clearDepth = depth;
          }
        }, {
          key: "clearStencil",
          get: function get() {
            return this._clearStencil;
          },
          set: function set(stencil) {
            this._clearStencil = stencil;
          }
        }, {
          key: "projectionType",
          get: function get() {
            return this._proj;
          },
          set: function set(val) {
            this._proj = val;
            this._isProjDirty = true;
          }
        }, {
          key: "aspect",
          get: function get() {
            return this._aspect;
          }
        }, {
          key: "orthoHeight",
          get: function get() {
            return this._orthoHeight;
          },
          set: function set(val) {
            this._orthoHeight = val;
            this._isProjDirty = true;
          }
        }, {
          key: "fovAxis",
          get: function get() {
            return this._fovAxis;
          },
          set: function set(axis) {
            this._fovAxis = axis;
            this._isProjDirty = true;
          }
        }, {
          key: "fov",
          get: function get() {
            return this._fov;
          },
          set: function set(fov) {
            this._fov = fov;
            this._isProjDirty = true;
          }
        }, {
          key: "nearClip",
          get: function get() {
            return this._nearClip;
          },
          set: function set(nearClip) {
            this._nearClip = nearClip;
            this._isProjDirty = true;
          }
        }, {
          key: "farClip",
          get: function get() {
            return this._farClip;
          },
          set: function set(farClip) {
            this._farClip = farClip;
            this._isProjDirty = true;
          }
        }, {
          key: "viewport",
          get: function get() {
            return this._viewport;
          },
          set: function set(val) {
            warnID(8302);
            this.setViewportInOrientedSpace(val);
          }
        }, {
          key: "frustum",
          get: function get() {
            return this._frustum;
          },
          set: function set(val) {
            this._frustum = val;
          }
        }, {
          key: "matView",
          get: function get() {
            return this._matView;
          }
        }, {
          key: "matProj",
          get: function get() {
            return this._matProj;
          }
        }, {
          key: "matProjInv",
          get: function get() {
            return this._matProjInv;
          }
        }, {
          key: "matViewProj",
          get: function get() {
            return this._matViewProj;
          }
        }, {
          key: "matViewProjInv",
          get: function get() {
            return this._matViewProjInv;
          }
        }, {
          key: "surfaceTransform",
          get: function get() {
            return this._curTransform;
          }
        }, {
          key: "geometryRenderer",
          get: function get() {
            return this._geometryRenderer;
          }
        }, {
          key: "cameraType",
          get: function get() {
            return this._cameraType;
          },
          set: function set(type) {
            this._cameraType = type;
          }
        }, {
          key: "trackingType",
          get: function get() {
            return this._trackingType;
          },
          set: function set(type) {
            this._trackingType = type;
          }
        }, {
          key: "cameraUsage",
          get: function get() {
            return this._usage;
          },
          set: function set(usage) {
            this._usage = usage;
          }
        }], [{
          key: "standardExposureValue",
          get: function get() {
            return 1.0 / 38400.0;
          }
        }, {
          key: "standardLightMeterScale",
          get: function get() {
            return 10000.0;
          }
        }]);
        return Camera;
      }();

      var ShadowSize = Enum({
        Low_256x256: 256,
        Medium_512x512: 512,
        High_1024x1024: 1024,
        Ultra_2048x2048: 2048
      });
      var ShadowType = Enum({
        Planar: 0,
        ShadowMap: 1
      });
      var PCFType = Enum({
        HARD: 0,
        SOFT: 1,
        SOFT_2X: 2,
        SOFT_4X: 3
      });
      var CSMLevel = Enum({
        LEVEL_1: 1,
        LEVEL_2: 2,
        LEVEL_3: 3,
        LEVEL_4: 4
      });
      var CSMOptimizationMode = Enum({
        NONE: 1,
        RemoveDuplicates: 2,
        DisableRotationFix: 3
      });
      var SHADOW_TYPE_NONE = ShadowType.ShadowMap + 1;
      var Shadows = function () {
        function Shadows() {
          this.fixedSphere = new Sphere(0.0, 0.0, 0.0, 0.01);
          this.maxReceived = 4;
          this._matLight = new Mat4();
          this._material = null;
          this._instancingMaterial = null;
          this._enabled = false;
          this._type = SHADOW_TYPE_NONE;
          this._distance = 0;
          this._normal = new Vec3(0, 1, 0);
          this._shadowColor = new Color$1(0, 0, 0, 76);
          this._size = new Vec2(1024, 1024);
          this._shadowMapDirty = false;
        }
        var _proto = Shadows.prototype;
        _proto.getPlanarShader = function getPlanarShader(patches) {
          if (!this._material) {
            this._material = new Material();
            this._material.initialize({
              effectName: 'pipeline/planar-shadow'
            });
          }
          var passes = this._material.passes;
          {
            assert(passes.length > 0, 'passes should not be empty!');
          }
          return passes.length > 0 ? passes[0].getShaderVariant(patches) : null;
        };
        _proto.initialize = function initialize(shadowsInfo) {
          this._enabled = shadowsInfo.enabled;
          this._type = this.enabled ? shadowsInfo.type : SHADOW_TYPE_NONE;
          this.normal = shadowsInfo.planeDirection;
          this.distance = shadowsInfo.planeHeight;
          this.shadowColor = shadowsInfo.shadowColor;
          this.maxReceived = shadowsInfo.maxReceived;
          if (shadowsInfo.shadowMapSize !== this._size.x) {
            this.size.set(shadowsInfo.shadowMapSize, shadowsInfo.shadowMapSize);
            this._shadowMapDirty = true;
          }
        };
        _proto.activate = function activate() {
          if (this._enabled) {
            if (this.type === ShadowType.Planar) {
              this._updatePlanarInfo();
            } else {
              var root = legacyCC.director.root;
              var pipeline = root.pipeline;
              pipeline.macros.CC_SHADOW_TYPE = 2;
              root.onGlobalPipelineStateChanged();
            }
          } else {
            var _root = legacyCC.director.root;
            var _pipeline = _root.pipeline;
            _pipeline.macros.CC_SHADOW_TYPE = 0;
            _root.onGlobalPipelineStateChanged();
          }
        };
        _proto._updatePlanarInfo = function _updatePlanarInfo() {
          if (!this._material) {
            this._material = new Material();
            this._material.initialize({
              effectName: 'pipeline/planar-shadow'
            });
          }
          var root = legacyCC.director.root;
          var pipeline = root.pipeline;
          pipeline.macros.CC_SHADOW_TYPE = 1;
          root.onGlobalPipelineStateChanged();
        };
        _proto.destroy = function destroy() {
          if (this._material) {
            this._material.destroy();
          }
          if (this._instancingMaterial) {
            this._instancingMaterial.destroy();
          }
          this.fixedSphere.destroy();
        };
        _createClass(Shadows, [{
          key: "enabled",
          get: function get() {
            return this._enabled;
          },
          set: function set(val) {
            this._enabled = val;
            this.activate();
          }
        }, {
          key: "type",
          get: function get() {
            return this._type;
          },
          set: function set(val) {
            this._type = this.enabled ? val : SHADOW_TYPE_NONE;
            this.activate();
          }
        }, {
          key: "normal",
          get: function get() {
            return this._normal;
          },
          set: function set(val) {
            Vec3.copy(this._normal, val);
          }
        }, {
          key: "distance",
          get: function get() {
            return this._distance;
          },
          set: function set(val) {
            this._distance = val;
          }
        }, {
          key: "shadowColor",
          get: function get() {
            return this._shadowColor;
          },
          set: function set(color) {
            this._shadowColor = color;
          }
        }, {
          key: "size",
          get: function get() {
            return this._size;
          },
          set: function set(val) {
            this._size.set(val);
          }
        }, {
          key: "shadowMapDirty",
          get: function get() {
            return this._shadowMapDirty;
          },
          set: function set(val) {
            this._shadowMapDirty = val;
          }
        }, {
          key: "matLight",
          get: function get() {
            return this._matLight;
          }
        }, {
          key: "material",
          get: function get() {
            return this._material;
          }
        }, {
          key: "instancingMaterial",
          get: function get() {
            return this._instancingMaterial;
          }
        }]);
        return Shadows;
      }();
      Shadows.MAX_FAR = 2000.0;
      Shadows.COEFFICIENT_OF_EXPANSION = 2.0 * Math.sqrt(3.0);
      legacyCC.Shadows = Shadows;

      var _tempVec3$4 = new Vec3();
      var _sphere = Sphere.create(0, 0, 0, 1);
      var _rangedDirLightBoundingBox$3 = new AABB(0.0, 0.0, 0.0, 0.5, 0.5, 0.5);
      var _tmpBoundingBox$3 = new AABB();
      var roPool = new Pool(function () {
        return {
          model: null,
          depth: 0
        };
      }, 128);
      function getRenderObject(model, camera) {
        var depth = 0;
        if (model.node) {
          Vec3.subtract(_tempVec3$4, model.node.worldPosition, camera.position);
          depth = Vec3.dot(_tempVec3$4, camera.forward);
        }
        var ro = roPool.alloc();
        ro.model = model;
        ro.depth = depth;
        return ro;
      }
      function validPunctualLightsCulling$1(pipeline, camera) {
        var sceneData = pipeline.pipelineSceneData;
        var validPunctualLights = sceneData.validPunctualLights;
        validPunctualLights.length = 0;
        var _ref = camera.scene,
          spotLights = _ref.spotLights;
        for (var i = 0; i < spotLights.length; i++) {
          var light = spotLights[i];
          if (light.baked && !camera.node.scene.globals.disableLightmap) {
            continue;
          }
          Sphere.set(_sphere, light.position.x, light.position.y, light.position.z, light.range);
          if (intersect.sphereFrustum(_sphere, camera.frustum)) {
            validPunctualLights.push(light);
          }
        }
        var _ref2 = camera.scene,
          sphereLights = _ref2.sphereLights;
        for (var _i = 0; _i < sphereLights.length; _i++) {
          var _light = sphereLights[_i];
          if (_light.baked && !camera.node.scene.globals.disableLightmap) {
            continue;
          }
          Sphere.set(_sphere, _light.position.x, _light.position.y, _light.position.z, _light.range);
          if (intersect.sphereFrustum(_sphere, camera.frustum)) {
            validPunctualLights.push(_light);
          }
        }
        var _ref3 = camera.scene,
          pointLights = _ref3.pointLights;
        for (var _i2 = 0; _i2 < pointLights.length; _i2++) {
          var _light2 = pointLights[_i2];
          if (_light2.baked) {
            continue;
          }
          Sphere.set(_sphere, _light2.position.x, _light2.position.y, _light2.position.z, _light2.range);
          if (intersect.sphereFrustum(_sphere, camera.frustum)) {
            validPunctualLights.push(_light2);
          }
        }
        var _ref4 = camera.scene,
          rangedDirLights = _ref4.rangedDirLights;
        for (var _i3 = 0; _i3 < rangedDirLights.length; _i3++) {
          var _light3 = rangedDirLights[_i3];
          AABB.transform(_tmpBoundingBox$3, _rangedDirLightBoundingBox$3, _light3.node.getWorldMatrix());
          if (intersect.aabbFrustum(_tmpBoundingBox$3, camera.frustum)) {
            validPunctualLights.push(_light3);
          }
        }
        sceneData.validPunctualLights = validPunctualLights;
      }
      function shadowCulling(camera, sceneData, layer) {
        var scene = camera.scene;
        var mainLight = scene.mainLight;
        var csmLayers = sceneData.csmLayers;
        var csmLayerObjects = csmLayers.layerObjects;
        var dirLightFrustum = layer.validFrustum;
        var dirShadowObjects = layer.shadowObjects;
        dirShadowObjects.length = 0;
        var visibility = camera.visibility;
        for (var i = csmLayerObjects.length - 1; i >= 0; i--) {
          var obj = csmLayerObjects.array[i];
          if (!obj) {
            csmLayerObjects.fastRemove(i);
            continue;
          }
          var model = obj.model;
          if (!model || !model.enabled || !model.node) {
            csmLayerObjects.fastRemove(i);
            continue;
          }
          if ((visibility & model.node.layer) !== model.node.layer && !(visibility & model.visFlags)) {
            csmLayerObjects.fastRemove(i);
            continue;
          }
          if (!model.worldBounds || !model.castShadow) {
            csmLayerObjects.fastRemove(i);
            continue;
          }
          var accurate = intersect.aabbFrustum(model.worldBounds, dirLightFrustum);
          if (!accurate) {
            continue;
          }
          dirShadowObjects.push(obj);
          if (layer.level < mainLight.csmLevel) {
            if (mainLight.csmOptimizationMode === CSMOptimizationMode.RemoveDuplicates && intersect.aabbFrustumCompletelyInside(model.worldBounds, dirLightFrustum)) {
              csmLayerObjects.fastRemove(i);
            }
          }
        }
      }
      function sceneCulling(pipeline, camera) {
        var scene = camera.scene;
        var mainLight = scene.mainLight;
        var sceneData = pipeline.pipelineSceneData;
        var shadows = sceneData.shadows;
        var skybox = sceneData.skybox;
        var csmLayers = sceneData.csmLayers;
        var renderObjects = sceneData.renderObjects;
        roPool.freeArray(renderObjects);
        renderObjects.length = 0;
        var castShadowObjects = csmLayers.castShadowObjects;
        castShadowObjects.length = 0;
        var csmLayerObjects = csmLayers.layerObjects;
        csmLayerObjects.clear();
        if (shadows.enabled) {
          pipeline.pipelineUBO.updateShadowUBORange(UBOShadow.SHADOW_COLOR_OFFSET, shadows.shadowColor);
          if (shadows.type === ShadowType.ShadowMap) {
            if (mainLight && mainLight.node) {
              csmLayers.update(sceneData, camera);
            }
          }
        }
        if (camera.clearFlag & SKYBOX_FLAG) {
          if (skybox.enabled && skybox.model) {
            renderObjects.push(getRenderObject(skybox.model, camera));
          } else if (camera.cameraUsage !== CameraUsage.EDITOR && camera.cameraUsage !== CameraUsage.SCENE_VIEW) {
            legacyCC.warnID(15100, camera.name);
          }
        }
        var models = scene.models;
        var visibility = camera.visibility;
        function enqueueRenderObject(model) {
          if (model.enabled) {
            if (scene.isCulledByLod(camera, model)) {
              return;
            }
            if (model.castShadow) {
              castShadowObjects.push(getRenderObject(model, camera));
              csmLayerObjects.push(getRenderObject(model, camera));
            }
            if (model.node && (visibility & model.node.layer) === model.node.layer || visibility & model.visFlags) {
              if (model.worldBounds && !intersect.aabbFrustum(model.worldBounds, camera.frustum)) {
                return;
              }
              renderObjects.push(getRenderObject(model, camera));
            }
          }
        }
        for (var i = 0; i < models.length; i++) {
          enqueueRenderObject(models[i]);
        }
      }

      var _dec$2P, _class$2L;
      var _colorAttachment = new ColorAttachment();
      _colorAttachment.format = Format.RGBA8;
      var _depthStencilAttachment = new DepthStencilAttachment();
      _depthStencilAttachment.format = Format.DEPTH_STENCIL;
      var passInfo = new RenderPassInfo([_colorAttachment], _depthStencilAttachment);
      var _windowInfo = {
        width: 1,
        height: 1,
        renderPassInfo: passInfo
      };
      var RenderTexture = exports('ed', (_dec$2P = ccclass$n('cc.RenderTexture'), _dec$2P(_class$2L = function (_TextureBase) {
        _inheritsLoose(RenderTexture, _TextureBase);
        function RenderTexture() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _TextureBase.call.apply(_TextureBase, [this].concat(args)) || this;
          _this._window = null;
          return _this;
        }
        var _proto = RenderTexture.prototype;
        _proto.initialize = function initialize(info) {
          this._name = info.name || '';
          this._width = info.width;
          this._height = info.height;
          this._initWindow(info);
        };
        _proto.reset = function reset(info) {
          this.initialize(info);
        };
        _proto.destroy = function destroy() {
          if (this._window) {
            var root = legacyCC.director.root;
            root === null || root === void 0 ? void 0 : root.destroyWindow(this._window);
            this._window = null;
          }
          return _TextureBase.prototype.destroy.call(this);
        };
        _proto.resize = function resize(width, height) {
          this._width = Math.floor(clamp$1(width, 1, 2048));
          this._height = Math.floor(clamp$1(height, 1, 2048));
          if (this._window) {
            this._window.resize(this._width, this._height);
          }
          this.emit('resize', this._window);
        };
        _proto._serialize = function _serialize(ctxForExporting) {
          return {};
        };
        _proto._deserialize = function _deserialize(serializedData, handle) {
          var data = serializedData;
          this._width = data.w;
          this._height = data.h;
          this._name = data.n;
          _TextureBase.prototype._deserialize.call(this, data.base, handle);
        };
        _proto.getGFXTexture = function getGFXTexture() {
          return this._window && this._window.framebuffer.colorTextures[0];
        };
        _proto.onLoaded = function onLoaded() {
          this._initWindow();
        };
        _proto._initWindow = function _initWindow(info) {
          var root = legacyCC.director.root;
          _windowInfo.title = this._name;
          _windowInfo.width = this._width;
          _windowInfo.height = this._height;
          _windowInfo.renderPassInfo = info && info.passInfo ? info.passInfo : passInfo;
          _windowInfo.externalResLow = info && info.externalResLow ? info.externalResLow : 0;
          _windowInfo.externalResHigh = info && info.externalResHigh ? info.externalResHigh : 0;
          _windowInfo.externalFlag = info && info.externalFlag ? info.externalFlag : TextureFlagBit.NONE;
          _colorAttachment.barrier = deviceManager.gfxDevice.getGeneralBarrier(new GeneralBarrierInfo(AccessFlagBit.FRAGMENT_SHADER_READ_TEXTURE, AccessFlagBit.FRAGMENT_SHADER_READ_TEXTURE));
          if (this._window) {
            this._window.destroy();
            this._window.initialize(deviceManager.gfxDevice, _windowInfo);
          } else {
            this._window = root.createWindow(_windowInfo);
          }
        };
        _proto.initDefault = function initDefault(uuid) {
          _TextureBase.prototype.initDefault.call(this, uuid);
          this._width = this._height = 1;
          this._initWindow();
        };
        _proto.validate = function validate() {
          return this.width >= 1 && this.width <= 2048 && this.height >= 1 && this.height <= 2048;
        };
        _proto.readPixels = function readPixels(x, y, width, height, buffer) {
          if (x === void 0) {
            x = 0;
          }
          if (y === void 0) {
            y = 0;
          }
          width = width || this.width;
          height = height || this.height;
          var gfxTexture = this.getGFXTexture();
          if (!gfxTexture) {
            errorID(7606);
            return null;
          }
          var needSize = 4 * width * height;
          if (buffer === undefined) {
            buffer = new Uint8Array(needSize);
          } else if (buffer.length < needSize) {
            errorID(7607, needSize);
            return null;
          }
          var gfxDevice = this._getGFXDevice();
          var bufferViews = [];
          var regions = [];
          var region0 = new BufferTextureCopy();
          region0.texOffset.x = x;
          region0.texOffset.y = y;
          region0.texExtent.width = width;
          region0.texExtent.height = height;
          regions.push(region0);
          bufferViews.push(buffer);
          gfxDevice === null || gfxDevice === void 0 ? void 0 : gfxDevice.copyTextureToBuffers(gfxTexture, bufferViews, regions);
          return buffer;
        };
        _createClass(RenderTexture, [{
          key: "window",
          get: function get() {
            return this._window;
          }
        }]);
        return RenderTexture;
      }(TextureBase)) || _class$2L));
      legacyCC.RenderTexture = RenderTexture;

      var ProbeClearFlag;
      (function (ProbeClearFlag) {
        ProbeClearFlag[ProbeClearFlag["SKYBOX"] = SKYBOX_FLAG | ClearFlagBit.DEPTH_STENCIL] = "SKYBOX";
        ProbeClearFlag[ProbeClearFlag["SOLID_COLOR"] = ClearFlagBit.ALL] = "SOLID_COLOR";
      })(ProbeClearFlag || (ProbeClearFlag = {}));
      var ProbeType;
      (function (ProbeType) {
        ProbeType[ProbeType["CUBE"] = 0] = "CUBE";
        ProbeType[ProbeType["PLANAR"] = 1] = "PLANAR";
      })(ProbeType || (ProbeType = {}));
      var cameraDir = [new Vec3(0, -90, 0), new Vec3(0, 90, 0), new Vec3(90, 0, 0), new Vec3(-90, 0, 0), new Vec3(0, 0, 0), new Vec3(0, 180, 0)];
      var ReflectionProbe$1 = function () {
        function ReflectionProbe(id) {
          this.bakedCubeTextures = [];
          this.realtimePlanarTexture = null;
          this._resolution = 256;
          this._clearFlag = ProbeClearFlag.SKYBOX;
          this._backgroundColor = new Color$1(0, 0, 0, 255);
          this._visibility = CAMERA_DEFAULT_MASK;
          this._probeType = ProbeType.CUBE;
          this._cubemap = null;
          this._size = new Vec3(1, 1, 1);
          this._camera = null;
          this._probeId = 0;
          this._needRefresh = false;
          this._needRender = false;
          this._node = null;
          this._cameraNode = null;
          this._boundingBox = null;
          this._cameraWorldPos = new Vec3();
          this._cameraWorldRotation = new Quat();
          this._forward = new Vec3();
          this._up = new Vec3();
          this._previewSphere = null;
          this._previewPlane = null;
          this._probeId = id;
        }
        var _proto = ReflectionProbe.prototype;
        _proto.initialize = function initialize(node, cameraNode) {
          this._node = node;
          this._cameraNode = cameraNode;
          var pos = this.node.getWorldPosition();
          this._boundingBox = AABB.create(pos.x, pos.y, pos.z, this._size.x, this._size.y, this._size.z);
          this._createCamera(cameraNode);
        };
        _proto.initBakedTextures = function initBakedTextures() {
          if (this.bakedCubeTextures.length === 0) {
            for (var i = 0; i < 6; i++) {
              var renderTexture = this._createTargetTexture(this._resolution, this._resolution);
              this.bakedCubeTextures.push(renderTexture);
            }
          }
        };
        _proto.captureCubemap = function captureCubemap() {
          this.initBakedTextures();
          this._resetCameraParams();
          this._needRender = true;
        };
        _proto.renderPlanarReflection = function renderPlanarReflection(sourceCamera) {
          if (!sourceCamera) return;
          if (!this.realtimePlanarTexture) {
            var canvasSize = legacyCC.view.getDesignResolutionSize();
            this.realtimePlanarTexture = this._createTargetTexture(canvasSize.width, canvasSize.height);
            legacyCC.internal.reflectionProbeManager.updatePlanarMap(this, this.realtimePlanarTexture.getGFXTexture());
          }
          this._syncCameraParams(sourceCamera);
          this._transformReflectionCamera(sourceCamera);
          this._needRender = true;
        };
        _proto.switchProbeType = function switchProbeType(type, sourceCamera) {
          if (type === ProbeType.CUBE) {
            this._needRender = false;
          } else if (sourceCamera !== null) {
            this.renderPlanarReflection(sourceCamera);
          }
        };
        _proto.getProbeId = function getProbeId() {
          return this._probeId;
        };
        _proto.updateProbeId = function updateProbeId(id) {
          this._probeId = id;
        };
        _proto.renderArea = function renderArea() {
          if (this._probeType === ProbeType.PLANAR) {
            return new Vec2(this.realtimePlanarTexture.width, this.realtimePlanarTexture.height);
          } else {
            return new Vec2(this.resolution, this.resolution);
          }
        };
        _proto.isFinishedRendering = function isFinishedRendering() {
          return true;
        };
        _proto.validate = function validate() {
          return this.cubemap !== null;
        };
        _proto.destroy = function destroy() {
          if (this._camera) {
            this._camera.destroy();
            this._camera = null;
          }
          for (var i = 0; i < this.bakedCubeTextures.length; i++) {
            this.bakedCubeTextures[i].destroy();
          }
          this.bakedCubeTextures = [];
          if (this.realtimePlanarTexture) {
            this.realtimePlanarTexture.destroy();
            this.realtimePlanarTexture = null;
          }
        };
        _proto.enable = function enable() {};
        _proto.disable = function disable() {};
        _proto.updateCameraDir = function updateCameraDir(faceIdx) {
          this.cameraNode.setRotationFromEuler(cameraDir[faceIdx]);
          this.camera.update(true);
        };
        _proto.updateBoundingBox = function updateBoundingBox() {
          if (this.node) {
            var pos = this.node.getWorldPosition();
            AABB.set(this._boundingBox, pos.x, pos.y, pos.z, this._size.x, this._size.y, this._size.z);
          }
        };
        _proto.hasFrameBuffer = function hasFrameBuffer(framebuffer) {
          if (this.probeType === ProbeType.PLANAR) {
            var _this$realtimePlanarT;
            if (!this.realtimePlanarTexture) return false;
            if (((_this$realtimePlanarT = this.realtimePlanarTexture.window) === null || _this$realtimePlanarT === void 0 ? void 0 : _this$realtimePlanarT.framebuffer) === framebuffer) {
              return true;
            }
          } else {
            if (this.bakedCubeTextures.length === 0) return false;
            for (var i = 0; i < this.bakedCubeTextures.length; i++) {
              var _rt$window;
              var rt = this.bakedCubeTextures[i];
              if (((_rt$window = rt.window) === null || _rt$window === void 0 ? void 0 : _rt$window.framebuffer) === framebuffer) {
                return true;
              }
            }
          }
          return false;
        };
        _proto.isRGBE = function isRGBE() {
          return true;
        };
        _proto._syncCameraParams = function _syncCameraParams(camera) {
          this.camera.projectionType = camera.projectionType;
          this.camera.orthoHeight = camera.orthoHeight;
          this.camera.nearClip = camera.nearClip;
          this.camera.farClip = camera.farClip;
          this.camera.fov = camera.fov;
          this.camera.clearFlag = camera.clearFlag;
          this.camera.clearColor = camera.clearColor;
          this.camera.priority = camera.priority - 1;
          this.camera.resize(camera.width, camera.height);
        };
        _proto._createCamera = function _createCamera(cameraNode) {
          var root = legacyCC.director.root;
          if (!this._camera) {
            this._camera = root.createCamera();
            if (!this._camera) return null;
            this._camera.initialize({
              name: cameraNode.name,
              node: cameraNode,
              projection: CameraProjection.PERSPECTIVE,
              window: root && root.tempWindow,
              priority: 0,
              cameraType: CameraType.DEFAULT,
              trackingType: TrackingType.NO_TRACKING
            });
          }
          this._camera.setViewportInOrientedSpace(new Rect$1(0, 0, 1, 1));
          this._camera.fovAxis = CameraFOVAxis.VERTICAL;
          this._camera.fov = toRadian(90);
          this._camera.orthoHeight = 10;
          this._camera.nearClip = 1;
          this._camera.farClip = 1000;
          this._camera.clearColor = this._backgroundColor;
          this._camera.clearDepth = 1.0;
          this._camera.clearStencil = 0.0;
          this._camera.clearFlag = this._clearFlag;
          this._camera.visibility = this._visibility;
          this._camera.aperture = CameraAperture.F16_0;
          this._camera.shutter = CameraShutter.D125;
          this._camera.iso = CameraISO.ISO100;
          return this._camera;
        };
        _proto._resetCameraParams = function _resetCameraParams() {
          this.camera.projectionType = CameraProjection.PERSPECTIVE;
          this.camera.orthoHeight = 10;
          this.camera.nearClip = 1;
          this.camera.farClip = 1000;
          this.camera.fov = toRadian(90);
          this.camera.priority = 0;
          this.camera.resize(this.resolution, this.resolution);
          this.camera.visibility = this._visibility;
          this.camera.clearFlag = this._clearFlag;
          this.camera.clearColor = this._backgroundColor;
          this.cameraNode.worldPosition = this.node.worldPosition;
          this.cameraNode.worldRotation = this.node.worldRotation;
          this.camera.update(true);
        };
        _proto._createTargetTexture = function _createTargetTexture(width, height) {
          var rt = new RenderTexture();
          rt.reset({
            width: width,
            height: height
          });
          return rt;
        };
        _proto._transformReflectionCamera = function _transformReflectionCamera(sourceCamera) {
          var offset = Vec3.dot(this.node.worldPosition, this.node.up);
          this._reflect(this._cameraWorldPos, sourceCamera.node.worldPosition, this.node.up, offset);
          this.cameraNode.worldPosition = this._cameraWorldPos;
          Vec3.transformQuat(this._forward, Vec3.FORWARD, sourceCamera.node.worldRotation);
          this._reflect(this._forward, this._forward, this.node.up, 0);
          this._forward.normalize();
          this._forward.negative();
          Vec3.transformQuat(this._up, Vec3.UP, sourceCamera.node.worldRotation);
          this._reflect(this._up, this._up, this.node.up, 0);
          this._up.normalize();
          Quat.fromViewUp(this._cameraWorldRotation, this._forward, this._up);
          this.cameraNode.worldRotation = this._cameraWorldRotation;
          this.camera.update(true);
          var viewSpaceProbe = new Vec4(this.node.up.x, this.node.up.y, this.node.up.z, -Vec3.dot(this.node.up, this.node.worldPosition));
          viewSpaceProbe.transformMat4(this.camera.matView.clone().invert().transpose());
          this.camera.calculateObliqueMat(viewSpaceProbe);
        };
        _proto._reflect = function _reflect(out, point, normal, offset) {
          var n = Vec3.clone(normal);
          n.normalize();
          var dist = Vec3.dot(n, point) - offset;
          n.multiplyScalar(2.0 * dist);
          Vec3.subtract(out, point, n);
          return out;
        };
        _createClass(ReflectionProbe, [{
          key: "probeType",
          get: function get() {
            return this._probeType;
          },
          set: function set(value) {
            this._probeType = value;
          }
        }, {
          key: "resolution",
          get: function get() {
            return this._resolution;
          },
          set: function set(value) {
            if (value !== this._resolution) {
              this.bakedCubeTextures.forEach(function (rt, idx) {
                rt.resize(value, value);
              });
            }
            this._resolution = value;
          }
        }, {
          key: "clearFlag",
          get: function get() {
            return this._clearFlag;
          },
          set: function set(value) {
            this._clearFlag = value;
            this.camera.clearFlag = this._clearFlag;
          }
        }, {
          key: "backgroundColor",
          get: function get() {
            return this._backgroundColor;
          },
          set: function set(val) {
            this._backgroundColor = val;
            this.camera.clearColor = this._backgroundColor;
          }
        }, {
          key: "visibility",
          get: function get() {
            return this._visibility;
          },
          set: function set(val) {
            this._visibility = val;
            this._camera.visibility = this._visibility;
          }
        }, {
          key: "size",
          get: function get() {
            return this._size;
          },
          set: function set(value) {
            this._size.set(value);
            var pos = this.node.getWorldPosition();
            AABB.set(this._boundingBox, pos.x, pos.y, pos.z, this._size.x, this._size.y, this._size.z);
          }
        }, {
          key: "cubemap",
          get: function get() {
            return this._cubemap;
          },
          set: function set(val) {
            this._cubemap = val;
          }
        }, {
          key: "node",
          get: function get() {
            return this._node;
          }
        }, {
          key: "camera",
          get: function get() {
            return this._camera;
          }
        }, {
          key: "needRefresh",
          get: function get() {
            return this._needRefresh;
          },
          set: function set(value) {
            this._needRefresh = value;
          }
        }, {
          key: "needRender",
          get: function get() {
            return this._needRender;
          },
          set: function set(value) {
            this._needRender = value;
          }
        }, {
          key: "boundingBox",
          get: function get() {
            return this._boundingBox;
          }
        }, {
          key: "cameraNode",
          get: function get() {
            return this._cameraNode;
          },
          set: function set(node) {
            this._cameraNode = node;
          }
        }, {
          key: "previewSphere",
          get: function get() {
            return this._previewSphere;
          },
          set: function set(val) {
            this._previewSphere = val;
          }
        }, {
          key: "previewPlane",
          get: function get() {
            return this._previewPlane;
          },
          set: function set(val) {
            this._previewPlane = val;
          }
        }]);
        return ReflectionProbe;
      }();

      var NodeSpace; exports('dC', NodeSpace);
      (function (NodeSpace) {
        NodeSpace[NodeSpace["LOCAL"] = 0] = "LOCAL";
        NodeSpace[NodeSpace["WORLD"] = 1] = "WORLD";
      })(NodeSpace || (exports('dC', NodeSpace = {})));
      var TransformBit; exports('dD', TransformBit);
      (function (TransformBit) {
        TransformBit[TransformBit["NONE"] = 0] = "NONE";
        TransformBit[TransformBit["POSITION"] = 1] = "POSITION";
        TransformBit[TransformBit["ROTATION"] = 2] = "ROTATION";
        TransformBit[TransformBit["SCALE"] = 4] = "SCALE";
        TransformBit[TransformBit["RS"] = TransformBit.ROTATION | TransformBit.SCALE] = "RS";
        TransformBit[TransformBit["TRS"] = TransformBit.POSITION | TransformBit.ROTATION | TransformBit.SCALE] = "TRS";
        TransformBit[TransformBit["TRS_MASK"] = ~TransformBit.TRS] = "TRS_MASK";
      })(TransformBit || (exports('dD', TransformBit = {})));
      legacyCC.internal.TransformBit = TransformBit;
      var MobilityMode = exports('dE', Enum({
        Static: 0,
        Stationary: 1,
        Movable: 2
      }));

      function ColorTemperatureToRGB(rgb, kelvin) {
        if (kelvin < 1000.0) {
          kelvin = 1000.0;
        } else if (kelvin > 15000.0) {
          kelvin = 15000.0;
        }
        var kSqr = kelvin * kelvin;
        var u = (0.860117757 + 1.54118254e-4 * kelvin + 1.28641212e-7 * kSqr) / (1.0 + 8.42420235e-4 * kelvin + 7.08145163e-7 * kSqr);
        var v = (0.317398726 + 4.22806245e-5 * kelvin + 4.20481691e-8 * kSqr) / (1.0 - 2.89741816e-5 * kelvin + 1.61456053e-7 * kSqr);
        var d = 2.0 * u - 8.0 * v + 4.0;
        var x = 3.0 * u / d;
        var y = 2.0 * v / d;
        var z = 1.0 - x - y;
        var X = 1.0 / y * x;
        var Z = 1.0 / y * z;
        rgb.x = 3.2404542 * X + -1.5371385 + -0.4985314 * Z;
        rgb.y = -0.9692660 * X + 1.8760108 + 0.0415560 * Z;
        rgb.z = 0.0556434 * X + -0.2040259 + 1.0572252 * Z;
      }
      var LightType;
      (function (LightType) {
        LightType[LightType["DIRECTIONAL"] = 0] = "DIRECTIONAL";
        LightType[LightType["SPHERE"] = 1] = "SPHERE";
        LightType[LightType["SPOT"] = 2] = "SPOT";
        LightType[LightType["POINT"] = 3] = "POINT";
        LightType[LightType["RANGED_DIRECTIONAL"] = 4] = "RANGED_DIRECTIONAL";
        LightType[LightType["UNKNOWN"] = 5] = "UNKNOWN";
      })(LightType || (LightType = {}));
      var nt2lm = function nt2lm(size) {
        return 4 * Math.PI * Math.PI * size * size;
      };
      var Light$1 = function () {
        function Light() {
          this._baked = false;
          this._color = new Vec3(1, 1, 1);
          this._colorTemp = 6550.0;
          this._colorTempRGB = new Vec3(1, 1, 1);
          this._finalColor = new Vec3(1, 1, 1);
          this._scene = null;
          this._node = null;
          this._name = null;
          this._useColorTemperature = false;
          this._type = LightType.UNKNOWN;
          this._visibility = CAMERA_DEFAULT_MASK;
        }
        var _proto = Light.prototype;
        _proto.initialize = function initialize() {
          this.color = new Vec3(1, 1, 1);
          this.colorTemperature = 6550.0;
        };
        _proto.attachToScene = function attachToScene(scene) {
          this._scene = scene;
        };
        _proto.detachFromScene = function detachFromScene() {
          this._scene = null;
        };
        _proto.destroy = function destroy() {
          this._name = null;
          this._node = null;
        };
        _proto.update = function update() {};
        _createClass(Light, [{
          key: "baked",
          get: function get() {
            return this._baked;
          },
          set: function set(val) {
            this._baked = val;
          }
        }, {
          key: "color",
          get: function get() {
            return this._color;
          },
          set: function set(color) {
            this._color.set(color);
            if (this._useColorTemperature) {
              Vec3.multiply(this._finalColor, this._color, this._colorTempRGB);
            }
          }
        }, {
          key: "useColorTemperature",
          get: function get() {
            return this._useColorTemperature;
          },
          set: function set(enable) {
            this._useColorTemperature = enable;
            if (enable) {
              Vec3.multiply(this._finalColor, this._color, this._colorTempRGB);
            }
          }
        }, {
          key: "colorTemperature",
          get: function get() {
            return this._colorTemp;
          },
          set: function set(val) {
            this._colorTemp = val;
            ColorTemperatureToRGB(this._colorTempRGB, this._colorTemp);
            if (this._useColorTemperature) {
              Vec3.multiply(this._finalColor, this._color, this._colorTempRGB);
            }
          }
        }, {
          key: "colorTemperatureRGB",
          get: function get() {
            return this._colorTempRGB;
          }
        }, {
          key: "finalColor",
          get: function get() {
            return this._finalColor;
          }
        }, {
          key: "visibility",
          get: function get() {
            return this._visibility;
          },
          set: function set(vis) {
            this._visibility = vis;
          }
        }, {
          key: "node",
          get: function get() {
            return this._node;
          },
          set: function set(n) {
            this._node = n;
            if (this._node) {
              this._node.hasChangedFlags |= TransformBit.ROTATION;
            }
          }
        }, {
          key: "type",
          get: function get() {
            return this._type;
          }
        }, {
          key: "name",
          get: function get() {
            return this._name;
          },
          set: function set(n) {
            this._name = n;
          }
        }, {
          key: "scene",
          get: function get() {
            return this._scene;
          }
        }]);
        return Light;
      }();

      var UpdateFrequency;
      (function (UpdateFrequency) {
        UpdateFrequency[UpdateFrequency["PER_INSTANCE"] = 0] = "PER_INSTANCE";
        UpdateFrequency[UpdateFrequency["PER_BATCH"] = 1] = "PER_BATCH";
        UpdateFrequency[UpdateFrequency["PER_PHASE"] = 2] = "PER_PHASE";
        UpdateFrequency[UpdateFrequency["PER_PASS"] = 3] = "PER_PASS";
        UpdateFrequency[UpdateFrequency["COUNT"] = 4] = "COUNT";
      })(UpdateFrequency || (UpdateFrequency = {}));
      var ParameterType;
      (function (ParameterType) {
        ParameterType[ParameterType["CONSTANTS"] = 0] = "CONSTANTS";
        ParameterType[ParameterType["CBV"] = 1] = "CBV";
        ParameterType[ParameterType["UAV"] = 2] = "UAV";
        ParameterType[ParameterType["SRV"] = 3] = "SRV";
        ParameterType[ParameterType["TABLE"] = 4] = "TABLE";
        ParameterType[ParameterType["SSV"] = 5] = "SSV";
      })(ParameterType || (ParameterType = {}));
      var ResourceResidency;
      (function (ResourceResidency) {
        ResourceResidency[ResourceResidency["MANAGED"] = 0] = "MANAGED";
        ResourceResidency[ResourceResidency["MEMORYLESS"] = 1] = "MEMORYLESS";
        ResourceResidency[ResourceResidency["PERSISTENT"] = 2] = "PERSISTENT";
        ResourceResidency[ResourceResidency["EXTERNAL"] = 3] = "EXTERNAL";
        ResourceResidency[ResourceResidency["BACKBUFFER"] = 4] = "BACKBUFFER";
      })(ResourceResidency || (ResourceResidency = {}));
      var QueueHint;
      (function (QueueHint) {
        QueueHint[QueueHint["NONE"] = 0] = "NONE";
        QueueHint[QueueHint["OPAQUE"] = 1] = "OPAQUE";
        QueueHint[QueueHint["MASK"] = 2] = "MASK";
        QueueHint[QueueHint["BLEND"] = 3] = "BLEND";
        QueueHint[QueueHint["RENDER_OPAQUE"] = 1] = "RENDER_OPAQUE";
        QueueHint[QueueHint["RENDER_CUTOUT"] = 2] = "RENDER_CUTOUT";
        QueueHint[QueueHint["RENDER_TRANSPARENT"] = 3] = "RENDER_TRANSPARENT";
      })(QueueHint || (QueueHint = {}));
      var ResourceDimension;
      (function (ResourceDimension) {
        ResourceDimension[ResourceDimension["BUFFER"] = 0] = "BUFFER";
        ResourceDimension[ResourceDimension["TEXTURE1D"] = 1] = "TEXTURE1D";
        ResourceDimension[ResourceDimension["TEXTURE2D"] = 2] = "TEXTURE2D";
        ResourceDimension[ResourceDimension["TEXTURE3D"] = 3] = "TEXTURE3D";
      })(ResourceDimension || (ResourceDimension = {}));
      var ResourceFlags;
      (function (ResourceFlags) {
        ResourceFlags[ResourceFlags["NONE"] = 0] = "NONE";
        ResourceFlags[ResourceFlags["UNIFORM"] = 1] = "UNIFORM";
        ResourceFlags[ResourceFlags["INDIRECT"] = 2] = "INDIRECT";
        ResourceFlags[ResourceFlags["STORAGE"] = 4] = "STORAGE";
        ResourceFlags[ResourceFlags["SAMPLED"] = 8] = "SAMPLED";
        ResourceFlags[ResourceFlags["COLOR_ATTACHMENT"] = 16] = "COLOR_ATTACHMENT";
        ResourceFlags[ResourceFlags["DEPTH_STENCIL_ATTACHMENT"] = 32] = "DEPTH_STENCIL_ATTACHMENT";
        ResourceFlags[ResourceFlags["INPUT_ATTACHMENT"] = 64] = "INPUT_ATTACHMENT";
        ResourceFlags[ResourceFlags["SHADING_RATE"] = 128] = "SHADING_RATE";
        ResourceFlags[ResourceFlags["TRANSFER_SRC"] = 256] = "TRANSFER_SRC";
        ResourceFlags[ResourceFlags["TRANSFER_DST"] = 512] = "TRANSFER_DST";
      })(ResourceFlags || (ResourceFlags = {}));
      var TaskType;
      (function (TaskType) {
        TaskType[TaskType["SYNC"] = 0] = "SYNC";
        TaskType[TaskType["ASYNC"] = 1] = "ASYNC";
      })(TaskType || (TaskType = {}));
      var SceneFlags;
      (function (SceneFlags) {
        SceneFlags[SceneFlags["NONE"] = 0] = "NONE";
        SceneFlags[SceneFlags["OPAQUE"] = 1] = "OPAQUE";
        SceneFlags[SceneFlags["MASK"] = 2] = "MASK";
        SceneFlags[SceneFlags["BLEND"] = 4] = "BLEND";
        SceneFlags[SceneFlags["OPAQUE_OBJECT"] = 1] = "OPAQUE_OBJECT";
        SceneFlags[SceneFlags["CUTOUT_OBJECT"] = 2] = "CUTOUT_OBJECT";
        SceneFlags[SceneFlags["TRANSPARENT_OBJECT"] = 4] = "TRANSPARENT_OBJECT";
        SceneFlags[SceneFlags["SHADOW_CASTER"] = 8] = "SHADOW_CASTER";
        SceneFlags[SceneFlags["UI"] = 16] = "UI";
        SceneFlags[SceneFlags["DEFAULT_LIGHTING"] = 32] = "DEFAULT_LIGHTING";
        SceneFlags[SceneFlags["VOLUMETRIC_LIGHTING"] = 64] = "VOLUMETRIC_LIGHTING";
        SceneFlags[SceneFlags["CLUSTERED_LIGHTING"] = 128] = "CLUSTERED_LIGHTING";
        SceneFlags[SceneFlags["PLANAR_SHADOW"] = 256] = "PLANAR_SHADOW";
        SceneFlags[SceneFlags["GEOMETRY"] = 512] = "GEOMETRY";
        SceneFlags[SceneFlags["PROFILER"] = 1024] = "PROFILER";
        SceneFlags[SceneFlags["DRAW_INSTANCING"] = 2048] = "DRAW_INSTANCING";
        SceneFlags[SceneFlags["DRAW_NON_INSTANCING"] = 4096] = "DRAW_NON_INSTANCING";
        SceneFlags[SceneFlags["REFLECTION_PROBE"] = 8192] = "REFLECTION_PROBE";
        SceneFlags[SceneFlags["GPU_DRIVEN"] = 16384] = "GPU_DRIVEN";
        SceneFlags[SceneFlags["ALL"] = 4294967295] = "ALL";
      })(SceneFlags || (SceneFlags = {}));
      var LightingMode;
      (function (LightingMode) {
        LightingMode[LightingMode["NONE"] = 0] = "NONE";
        LightingMode[LightingMode["DEFAULT"] = 1] = "DEFAULT";
        LightingMode[LightingMode["CLUSTERED"] = 2] = "CLUSTERED";
      })(LightingMode || (LightingMode = {}));
      var AttachmentType;
      (function (AttachmentType) {
        AttachmentType[AttachmentType["RENDER_TARGET"] = 0] = "RENDER_TARGET";
        AttachmentType[AttachmentType["DEPTH_STENCIL"] = 1] = "DEPTH_STENCIL";
        AttachmentType[AttachmentType["SHADING_RATE"] = 2] = "SHADING_RATE";
      })(AttachmentType || (AttachmentType = {}));
      var AccessType;
      (function (AccessType) {
        AccessType[AccessType["READ"] = 0] = "READ";
        AccessType[AccessType["READ_WRITE"] = 1] = "READ_WRITE";
        AccessType[AccessType["WRITE"] = 2] = "WRITE";
      })(AccessType || (AccessType = {}));
      var ClearValueType;
      (function (ClearValueType) {
        ClearValueType[ClearValueType["NONE"] = 0] = "NONE";
        ClearValueType[ClearValueType["FLOAT_TYPE"] = 1] = "FLOAT_TYPE";
        ClearValueType[ClearValueType["INT_TYPE"] = 2] = "INT_TYPE";
      })(ClearValueType || (ClearValueType = {}));
      var LightInfo = function LightInfo(light, level, culledByLight) {
        if (light === void 0) {
          light = null;
        }
        if (level === void 0) {
          level = 0;
        }
        if (culledByLight === void 0) {
          culledByLight = false;
        }
        this.light = void 0;
        this.level = void 0;
        this.culledByLight = void 0;
        this.light = light;
        this.level = level;
        this.culledByLight = culledByLight;
      };
      var DescriptorTypeOrder;
      (function (DescriptorTypeOrder) {
        DescriptorTypeOrder[DescriptorTypeOrder["UNIFORM_BUFFER"] = 0] = "UNIFORM_BUFFER";
        DescriptorTypeOrder[DescriptorTypeOrder["DYNAMIC_UNIFORM_BUFFER"] = 1] = "DYNAMIC_UNIFORM_BUFFER";
        DescriptorTypeOrder[DescriptorTypeOrder["SAMPLER_TEXTURE"] = 2] = "SAMPLER_TEXTURE";
        DescriptorTypeOrder[DescriptorTypeOrder["SAMPLER"] = 3] = "SAMPLER";
        DescriptorTypeOrder[DescriptorTypeOrder["TEXTURE"] = 4] = "TEXTURE";
        DescriptorTypeOrder[DescriptorTypeOrder["STORAGE_BUFFER"] = 5] = "STORAGE_BUFFER";
        DescriptorTypeOrder[DescriptorTypeOrder["DYNAMIC_STORAGE_BUFFER"] = 6] = "DYNAMIC_STORAGE_BUFFER";
        DescriptorTypeOrder[DescriptorTypeOrder["STORAGE_IMAGE"] = 7] = "STORAGE_IMAGE";
        DescriptorTypeOrder[DescriptorTypeOrder["INPUT_ATTACHMENT"] = 8] = "INPUT_ATTACHMENT";
      })(DescriptorTypeOrder || (DescriptorTypeOrder = {}));
      var ResolveFlags;
      (function (ResolveFlags) {
        ResolveFlags[ResolveFlags["NONE"] = 0] = "NONE";
        ResolveFlags[ResolveFlags["COLOR"] = 1] = "COLOR";
        ResolveFlags[ResolveFlags["DEPTH"] = 2] = "DEPTH";
        ResolveFlags[ResolveFlags["STENCIL"] = 4] = "STENCIL";
      })(ResolveFlags || (ResolveFlags = {}));
      var UploadPair = function UploadPair(source, target, mipLevels, numSlices, targetMostDetailedMip, targetFirstSlice, targetPlaneSlice) {
        if (source === void 0) {
          source = new Uint8Array(0);
        }
        if (target === void 0) {
          target = '';
        }
        if (mipLevels === void 0) {
          mipLevels = 0xFFFFFFFF;
        }
        if (numSlices === void 0) {
          numSlices = 0xFFFFFFFF;
        }
        if (targetMostDetailedMip === void 0) {
          targetMostDetailedMip = 0;
        }
        if (targetFirstSlice === void 0) {
          targetFirstSlice = 0;
        }
        if (targetPlaneSlice === void 0) {
          targetPlaneSlice = 0;
        }
        this.source = void 0;
        this.target = void 0;
        this.mipLevels = void 0;
        this.numSlices = void 0;
        this.targetMostDetailedMip = void 0;
        this.targetFirstSlice = void 0;
        this.targetPlaneSlice = void 0;
        this.source = source;
        this.target = target;
        this.mipLevels = mipLevels;
        this.numSlices = numSlices;
        this.targetMostDetailedMip = targetMostDetailedMip;
        this.targetFirstSlice = targetFirstSlice;
        this.targetPlaneSlice = targetPlaneSlice;
      };

      removeProperty(TextureBase.prototype, 'TextureBase.prototype', [{
        name: 'hasPremultipliedAlpha'
      }, {
        name: 'setPremultiplyAlpha'
      }, {
        name: 'setFlipY'
      }]);
      replaceProperty(RenderTexture.prototype, 'RenderTexture.prototype', [{
        name: 'getGFXWindow',
        customFunction: function customFunction() {
          return this.window;
        }
      }]);

      var _typeMap2;
      var _typeMap = (_typeMap2 = {}, _typeMap2[FormatType.UNORM] = 'Uint', _typeMap2[FormatType.SNORM] = 'Int', _typeMap2[FormatType.UINT] = 'Uint', _typeMap2[FormatType.INT] = 'Int', _typeMap2[FormatType.UFLOAT] = 'Float', _typeMap2[FormatType.FLOAT] = 'Float', _typeMap2["default"] = 'Uint', _typeMap2);
      function _getDataViewType(info) {
        var type = _typeMap[info.type] || _typeMap["default"];
        var bytes = info.size / info.count * 8;
        return "" + type + bytes;
      }
      function writeBuffer(target, data, format, offset, stride) {
        if (format === void 0) {
          format = Format.R32F;
        }
        if (offset === void 0) {
          offset = 0;
        }
        if (stride === void 0) {
          stride = 0;
        }
        var info = FormatInfos[format];
        if (!stride) {
          stride = info.size;
        }
        var writer = "set" + _getDataViewType(info);
        var componentBytesLength = info.size / info.count;
        var nSeg = Math.floor(data.length / info.count);
        var isLittleEndian = sys.isLittleEndian;
        for (var iSeg = 0; iSeg < nSeg; ++iSeg) {
          var x = offset + stride * iSeg;
          for (var iComponent = 0; iComponent < info.count; ++iComponent) {
            var y = x + componentBytesLength * iComponent;
            target[writer](y, data[info.count * iSeg + iComponent], isLittleEndian);
          }
        }
      }
      function readBuffer(target, format, offset, length, stride, out) {
        if (format === void 0) {
          format = Format.R32F;
        }
        if (offset === void 0) {
          offset = 0;
        }
        if (length === void 0) {
          length = target.byteLength - offset;
        }
        if (stride === void 0) {
          stride = 0;
        }
        if (out === void 0) {
          out = [];
        }
        var info = FormatInfos[format];
        if (!stride) {
          stride = info.size;
        }
        var reader = "get" + _getDataViewType(info);
        var componentBytesLength = info.size / info.count;
        var nSeg = Math.floor(length / stride);
        var isLittleEndian = sys.isLittleEndian;
        for (var iSeg = 0; iSeg < nSeg; ++iSeg) {
          var x = offset + stride * iSeg;
          for (var iComponent = 0; iComponent < info.count; ++iComponent) {
            var y = x + componentBytesLength * iComponent;
            out[info.count * iSeg + iComponent] = target[reader](y, isLittleEndian);
          }
        }
        return out;
      }
      function mapBuffer(target, callback, format, offset, length, stride, out) {
        if (format === void 0) {
          format = Format.R32F;
        }
        if (offset === void 0) {
          offset = 0;
        }
        if (length === void 0) {
          length = target.byteLength - offset;
        }
        if (stride === void 0) {
          stride = 0;
        }
        if (!out) {
          out = new DataView(target.buffer.slice(target.byteOffset, target.byteOffset + target.byteLength));
        }
        var info = FormatInfos[format];
        if (!stride) {
          stride = info.size;
        }
        var writer = "set" + _getDataViewType(info);
        var reader = "get" + _getDataViewType(info);
        var componentBytesLength = info.size / info.count;
        var nSeg = Math.floor(length / stride);
        var isLittleEndian = sys.isLittleEndian;
        for (var iSeg = 0; iSeg < nSeg; ++iSeg) {
          var x = offset + stride * iSeg;
          for (var iComponent = 0; iComponent < info.count; ++iComponent) {
            var y = x + componentBytesLength * iComponent;
            var _cur = target[reader](y, isLittleEndian);
            out[writer](y, callback(_cur, iComponent, target), isLittleEndian);
          }
        }
        return out;
      }

      var RenderingSubMesh = exports('e4', function () {
        function RenderingSubMesh(vertexBuffers, attributes, primitiveMode, indexBuffer, indirectBuffer, isOwnerOfIndexBuffer) {
          if (indexBuffer === void 0) {
            indexBuffer = null;
          }
          if (indirectBuffer === void 0) {
            indirectBuffer = null;
          }
          if (isOwnerOfIndexBuffer === void 0) {
            isOwnerOfIndexBuffer = true;
          }
          this.mesh = void 0;
          this.subMeshIdx = void 0;
          this._flatBuffers = [];
          this._jointMappedBuffers = void 0;
          this._jointMappedBufferIndices = void 0;
          this._vertexIdChannel = void 0;
          this._geometricInfo = void 0;
          this._vertexBuffers = void 0;
          this._attributes = void 0;
          this._indexBuffer = null;
          this._indirectBuffer = null;
          this._primitiveMode = void 0;
          this._iaInfo = void 0;
          this._isOwnerOfIndexBuffer = true;
          this._drawInfo = null;
          this._attributes = attributes;
          this._vertexBuffers = vertexBuffers;
          this._indexBuffer = indexBuffer;
          this._indirectBuffer = indirectBuffer;
          this._primitiveMode = primitiveMode;
          this._iaInfo = new InputAssemblerInfo(attributes, vertexBuffers, indexBuffer, indirectBuffer);
          this._isOwnerOfIndexBuffer = isOwnerOfIndexBuffer;
        }
        var _proto = RenderingSubMesh.prototype;
        _proto.invalidateGeometricInfo = function invalidateGeometricInfo() {
          this._geometricInfo = undefined;
        };
        _proto.genFlatBuffers = function genFlatBuffers() {
          if (this._flatBuffers.length || !this.mesh || this.subMeshIdx === undefined) {
            return;
          }
          var mesh = this.mesh;
          var idxCount = 0;
          var prim = mesh.struct.primitives[this.subMeshIdx];
          if (prim.indexView) {
            idxCount = prim.indexView.count;
          }
          for (var i = 0; i < prim.vertexBundelIndices.length; i++) {
            var bundleIdx = prim.vertexBundelIndices[i];
            var vertexBundle = mesh.struct.vertexBundles[bundleIdx];
            var vbCount = prim.indexView ? prim.indexView.count : vertexBundle.view.count;
            var vbStride = vertexBundle.view.stride;
            var vbSize = vbStride * vbCount;
            var view = new Uint8Array(mesh.data.buffer, vertexBundle.view.offset, vertexBundle.view.length);
            var sharedView = new Uint8Array(prim.indexView ? vbSize : vertexBundle.view.length);
            if (!prim.indexView) {
              sharedView.set(mesh.data.subarray(vertexBundle.view.offset, vertexBundle.view.offset + vertexBundle.view.length));
              this._flatBuffers.push({
                stride: vbStride,
                count: vbCount,
                buffer: sharedView
              });
              continue;
            }
            var ibView = mesh.readIndices(this.subMeshIdx);
            for (var n = 0; n < idxCount; ++n) {
              var idx = ibView[n];
              var offset = n * vbStride;
              var srcOffset = idx * vbStride;
              for (var m = 0; m < vbStride; ++m) {
                sharedView[offset + m] = view[srcOffset + m];
              }
            }
            this._flatBuffers.push({
              stride: vbStride,
              count: vbCount,
              buffer: sharedView
            });
          }
        };
        _proto.destroy = function destroy() {
          for (var i = 0; i < this.vertexBuffers.length; i++) {
            this.vertexBuffers[i].destroy();
          }
          this.vertexBuffers.length = 0;
          if (this._indexBuffer) {
            if (this._isOwnerOfIndexBuffer) {
              this._indexBuffer.destroy();
            }
            this._indexBuffer = null;
          }
          if (this._jointMappedBuffers && this._jointMappedBufferIndices) {
            for (var _i = 0; _i < this._jointMappedBufferIndices.length; _i++) {
              this._jointMappedBuffers[this._jointMappedBufferIndices[_i]].destroy();
            }
            this._jointMappedBuffers = undefined;
            this._jointMappedBufferIndices = undefined;
          }
          if (this._indirectBuffer) {
            this._indirectBuffer.destroy();
            this._indirectBuffer = null;
          }
        };
        _proto.enableVertexIdChannel = function enableVertexIdChannel(device) {
          if (this._vertexIdChannel) {
            return;
          }
          var streamIndex = this.vertexBuffers.length;
          var attributeIndex = this.attributes.length;
          var vertexIdBuffer = this._allocVertexIdBuffer(device);
          this._vertexBuffers.push(vertexIdBuffer);
          this._attributes.push(new Attribute('a_vertexId', Format.R32F, false, streamIndex));
          this._iaInfo.attributes = this._attributes;
          this._iaInfo.vertexBuffers = this._vertexBuffers;
          this._vertexIdChannel = {
            stream: streamIndex,
            index: attributeIndex
          };
        };
        _proto._allocVertexIdBuffer = function _allocVertexIdBuffer(device) {
          var vertexCount = this.vertexBuffers.length === 0 || this.vertexBuffers[0].stride === 0 ? 0 : this.vertexBuffers[0].size / this.vertexBuffers[0].stride;
          var vertexIds = new Float32Array(vertexCount);
          for (var iVertex = 0; iVertex < vertexCount; ++iVertex) {
            vertexIds[iVertex] = iVertex + 0.5;
          }
          var vertexIdBuffer = device.createBuffer(new BufferInfo(BufferUsageBit.VERTEX | BufferUsageBit.TRANSFER_DST, MemoryUsageBit.DEVICE, vertexIds.byteLength, vertexIds.BYTES_PER_ELEMENT));
          vertexIdBuffer.update(vertexIds);
          return vertexIdBuffer;
        };
        _createClass(RenderingSubMesh, [{
          key: "attributes",
          get: function get() {
            return this._attributes;
          }
        }, {
          key: "vertexBuffers",
          get: function get() {
            return this._vertexBuffers;
          }
        }, {
          key: "indexBuffer",
          get: function get() {
            return this._indexBuffer;
          }
        }, {
          key: "indirectBuffer",
          get: function get() {
            return this._indirectBuffer;
          }
        }, {
          key: "primitiveMode",
          get: function get() {
            return this._primitiveMode;
          }
        }, {
          key: "geometricInfo",
          get: function get() {
            if (this._geometricInfo) {
              return this._geometricInfo;
            }
            if (this.mesh === undefined) {
              return RenderingSubMesh.EMPTY_GEOMETRIC_INFO;
            }
            if (this.subMeshIdx === undefined) {
              return RenderingSubMesh.EMPTY_GEOMETRIC_INFO;
            }
            var mesh = this.mesh;
            var index = this.subMeshIdx;
            var pAttri = this.attributes.find(function (element) {
              return element.name === AttributeName.ATTR_POSITION;
            });
            if (!pAttri) {
              return RenderingSubMesh.EMPTY_GEOMETRIC_INFO;
            }
            var positions;
            switch (pAttri.format) {
              case Format.RG32F:
              case Format.RGB32F:
                {
                  positions = mesh.readAttribute(index, AttributeName.ATTR_POSITION);
                  if (!positions) {
                    return RenderingSubMesh.EMPTY_GEOMETRIC_INFO;
                  }
                  break;
                }
              case Format.RGBA32F:
                {
                  var data = mesh.readAttribute(index, AttributeName.ATTR_POSITION);
                  if (!data) {
                    return RenderingSubMesh.EMPTY_GEOMETRIC_INFO;
                  }
                  var count = data.length / 4;
                  positions = new Float32Array(count * 3);
                  for (var i = 0; i < count; ++i) {
                    var dstPtr = i * 3;
                    var srcPtr = i * 4;
                    positions[dstPtr] = data[srcPtr];
                    positions[dstPtr + 1] = data[srcPtr + 1];
                    positions[dstPtr + 2] = data[srcPtr + 2];
                  }
                  break;
                }
              case Format.RG16F:
              case Format.RGB16F:
                {
                  var _data = mesh.readAttribute(index, AttributeName.ATTR_POSITION);
                  if (!_data) {
                    return RenderingSubMesh.EMPTY_GEOMETRIC_INFO;
                  }
                  positions = new Float32Array(_data.length);
                  for (var _i2 = 0; _i2 < _data.length; ++_i2) {
                    positions[_i2] = halfToFloat(_data[_i2]);
                  }
                  break;
                }
              case Format.RGBA16F:
                {
                  var _data2 = mesh.readAttribute(index, AttributeName.ATTR_POSITION);
                  if (!_data2) {
                    return RenderingSubMesh.EMPTY_GEOMETRIC_INFO;
                  }
                  var _count = _data2.length / 4;
                  positions = new Float32Array(_count * 3);
                  for (var _i3 = 0; _i3 < _count; ++_i3) {
                    var _dstPtr = _i3 * 3;
                    var _srcPtr = _i3 * 4;
                    positions[_dstPtr] = halfToFloat(_data2[_srcPtr]);
                    positions[_dstPtr + 1] = halfToFloat(_data2[_srcPtr + 1]);
                    positions[_dstPtr + 2] = halfToFloat(_data2[_srcPtr + 2]);
                  }
                  break;
                }
              default:
                return RenderingSubMesh.EMPTY_GEOMETRIC_INFO;
            }
            var indices = mesh.readIndices(index) || undefined;
            var max = new Vec3();
            var min = new Vec3();
            var conut = FormatInfos[pAttri.format].count;
            if (conut === 2) {
              max.set(positions[0], positions[1], 0);
              min.set(positions[0], positions[1], 0);
            } else {
              max.set(positions[0], positions[1], positions[2]);
              min.set(positions[0], positions[1], positions[2]);
            }
            for (var _i4 = 0; _i4 < positions.length; _i4 += conut) {
              if (conut === 2) {
                max.x = positions[_i4] > max.x ? positions[_i4] : max.x;
                max.y = positions[_i4 + 1] > max.y ? positions[_i4 + 1] : max.y;
                min.x = positions[_i4] < min.x ? positions[_i4] : min.x;
                min.y = positions[_i4 + 1] < min.y ? positions[_i4 + 1] : min.y;
              } else {
                max.x = positions[_i4] > max.x ? positions[_i4] : max.x;
                max.y = positions[_i4 + 1] > max.y ? positions[_i4 + 1] : max.y;
                max.z = positions[_i4 + 2] > max.z ? positions[_i4 + 2] : max.z;
                min.x = positions[_i4] < min.x ? positions[_i4] : min.x;
                min.y = positions[_i4 + 1] < min.y ? positions[_i4 + 1] : min.y;
                min.z = positions[_i4 + 2] < min.z ? positions[_i4 + 2] : min.z;
              }
            }
            this._geometricInfo = {
              positions: positions,
              indices: indices,
              boundingBox: {
                max: max,
                min: min
              }
            };
            return this._geometricInfo;
          }
        }, {
          key: "drawInfo",
          get: function get() {
            return this._drawInfo;
          },
          set: function set(info) {
            this._drawInfo = info;
          }
        }, {
          key: "flatBuffers",
          get: function get() {
            return this._flatBuffers;
          }
        }, {
          key: "jointMappedBuffers",
          get: function get() {
            var _this = this;
            if (this._jointMappedBuffers) {
              return this._jointMappedBuffers;
            }
            var buffers = this._jointMappedBuffers = [];
            var indices = this._jointMappedBufferIndices = [];
            if (!this.mesh || this.subMeshIdx === undefined) {
              return this._jointMappedBuffers = this.vertexBuffers;
            }
            var struct = this.mesh.struct;
            var prim = struct.primitives[this.subMeshIdx];
            if (!struct.jointMaps || prim.jointMapIndex === undefined || !struct.jointMaps[prim.jointMapIndex]) {
              return this._jointMappedBuffers = this.vertexBuffers;
            }
            var jointFormat;
            var jointOffset;
            var _ref = legacyCC.director.root,
              device = _ref.device;
            var _loop = function _loop() {
              var bundle = struct.vertexBundles[prim.vertexBundelIndices[i]];
              jointOffset = 0;
              jointFormat = Format.UNKNOWN;
              for (var j = 0; j < bundle.attributes.length; j++) {
                var attr = bundle.attributes[j];
                if (attr.name === AttributeName.ATTR_JOINTS) {
                  jointFormat = attr.format;
                  break;
                }
                jointOffset += FormatInfos[attr.format].size;
              }
              if (jointFormat) {
                var data = new Uint8Array(_this.mesh.data.buffer, bundle.view.offset, bundle.view.length);
                var dataView = new DataView(data.slice().buffer);
                var idxMap = struct.jointMaps[prim.jointMapIndex];
                mapBuffer(dataView, function (cur) {
                  return idxMap.indexOf(cur);
                }, jointFormat, jointOffset, bundle.view.length, bundle.view.stride, dataView);
                var buffer = device.createBuffer(new BufferInfo(BufferUsageBit.VERTEX | BufferUsageBit.TRANSFER_DST, MemoryUsageBit.DEVICE, bundle.view.length, bundle.view.stride));
                buffer.update(dataView.buffer);
                buffers.push(buffer);
                indices.push(i);
              } else {
                buffers.push(_this.vertexBuffers[prim.vertexBundelIndices[i]]);
              }
            };
            for (var i = 0; i < prim.vertexBundelIndices.length; i++) {
              _loop();
            }
            if (this._vertexIdChannel) {
              buffers.push(this._allocVertexIdBuffer(device));
            }
            return buffers;
          }
        }, {
          key: "iaInfo",
          get: function get() {
            return this._iaInfo;
          }
        }]);
        return RenderingSubMesh;
      }());
      RenderingSubMesh.EMPTY_GEOMETRIC_INFO = {
        positions: new Float32Array(),
        indices: new Uint8Array(),
        boundingBox: {
          min: Vec3.ZERO,
          max: Vec3.ZERO
        }
      };

      var NodeUIProperties = function () {
        var _proto = NodeUIProperties.prototype;
        _proto.setOpacity = function setOpacity(v) {
          this._opacity = v;
        };
        function NodeUIProperties(node) {
          this._uiComp = null;
          this._opacity = 1;
          this._localOpacity = 1;
          this.colorDirty = true;
          this._uiTransformComp = null;
          this._node = void 0;
          this._node = node;
        }
        _proto.applyOpacity = function applyOpacity(effectOpacity) {
          this._opacity = this._localOpacity * effectOpacity;
        };
        NodeUIProperties.markOpacityTree = function markOpacityTree(node, isDirty) {
        };
        _createClass(NodeUIProperties, [{
          key: "uiTransformComp",
          get: function get() {
            if (!this._uiTransformComp) {
              this._uiTransformComp = this._node.getComponent('cc.UITransform');
            }
            return this._uiTransformComp;
          },
          set: function set(value) {
            this._uiTransformComp = value;
          }
        }, {
          key: "uiComp",
          get: function get() {
            return this._uiComp;
          },
          set: function set(comp) {
            if (this._uiComp && comp) {
              warnID(12002);
              return;
            }
            this._uiComp = comp;
          }
        }, {
          key: "opacity",
          get: function get() {
            return this._opacity;
          }
        }, {
          key: "localOpacity",
          get: function get() {
            return this._localOpacity;
          },
          set: function set(val) {
            this._localOpacity = val;
            this.colorDirty = true;
          }
        }]);
        return NodeUIProperties;
      }();

      CCObject.Flags.Destroying;
      !!legacyCC.GAME_VIEW;

      var NodeEventType; exports('dF', NodeEventType);
      (function (NodeEventType) {
        NodeEventType["TOUCH_START"] = "touch-start";
        NodeEventType["TOUCH_MOVE"] = "touch-move";
        NodeEventType["TOUCH_END"] = "touch-end";
        NodeEventType["TOUCH_CANCEL"] = "touch-cancel";
        NodeEventType["MOUSE_DOWN"] = "mouse-down";
        NodeEventType["MOUSE_MOVE"] = "mouse-move";
        NodeEventType["MOUSE_UP"] = "mouse-up";
        NodeEventType["MOUSE_WHEEL"] = "mouse-wheel";
        NodeEventType["MOUSE_ENTER"] = "mouse-enter";
        NodeEventType["MOUSE_LEAVE"] = "mouse-leave";
        NodeEventType["KEY_DOWN"] = "keydown";
        NodeEventType["KEY_UP"] = "keyup";
        NodeEventType["DEVICEMOTION"] = "devicemotion";
        NodeEventType["TRANSFORM_CHANGED"] = "transform-changed";
        NodeEventType["MOBILITY_CHANGED"] = "mobility-changed";
        NodeEventType["SCENE_CHANGED_FOR_PERSISTS"] = "scene-changed-for-persists";
        NodeEventType["SIZE_CHANGED"] = "size-changed";
        NodeEventType["ANCHOR_CHANGED"] = "anchor-changed";
        NodeEventType["COLOR_CHANGED"] = "color-changed";
        NodeEventType["CHILD_ADDED"] = "child-added";
        NodeEventType["CHILD_REMOVED"] = "child-removed";
        NodeEventType["PARENT_CHANGED"] = "parent-changed";
        NodeEventType["NODE_DESTROYED"] = "node-destroyed";
        NodeEventType["LAYER_CHANGED"] = "layer-changed";
        NodeEventType["SIBLING_ORDER_CHANGED"] = "sibling-order-changed";
        NodeEventType["ACTIVE_IN_HIERARCHY_CHANGED"] = "active-in-hierarchy-changed";
        NodeEventType["COMPONENT_ADDED"] = "component-added";
        NodeEventType["COMPONENT_REMOVED"] = "component-removed";
        NodeEventType["LIGHT_PROBE_CHANGED"] = "light-probe-changed";
        NodeEventType["LIGHT_PROBE_BAKING_CHANGED"] = "light-probe-baking-changed";
      })(NodeEventType || (exports('dF', NodeEventType = {})));

      var _dec$2O, _dec2$22, _dec3$1p, _class$2K, _class2$2v, _initializer$2f, _initializer2$1L, _initializer3$1a, _initializer4$V, _initializer5$G, _initializer6$x, _initializer7$r, _initializer8$q, _initializer9$o, _initializer10$m, _initializer11$j, _class3$J;
      var Destroying = CCObject.Flags.Destroying;
      var DontDestroy = CCObject.Flags.DontDestroy;
      var Deactivating$1 = CCObject.Flags.Deactivating;
      var TRANSFORM_ON = 1 << 0;
      var idGenerator = new IDGenerator('Node');
      function getConstructor(typeOrClassName) {
        if (!typeOrClassName) {
          errorID(3804);
          return null;
        }
        if (typeof typeOrClassName === 'string') {
          return getClassByName(typeOrClassName);
        }
        return typeOrClassName;
      }
      var v3_a = new Vec3();
      var v3_b = new Vec3();
      var q_a = new Quat();
      var q_b = new Quat();
      var qt_1 = new Quat();
      var m3_1 = new Mat3();
      new Mat3();
      var m4_1$7 = new Mat4();
      var m4_2$3 = new Mat4();
      var dirtyNodes = [];
      var reserveContentsForAllSyncablePrefabTag = Symbol('ReserveContentsForAllSyncablePrefab');
      var globalFlagChangeVersion = 0;
      var Node$1 = exports('du', (_dec$2O = ccclass$n('cc.Node'), _dec2$22 = type$7(Vec3), _dec3$1p = type$7(MobilityMode), _dec$2O(_class$2K = (_class2$2v = (_class3$J = function (_CCObject) {
        _inheritsLoose(Node, _CCObject);
        var _proto = Node.prototype;
        _proto._setActiveInHierarchy = function _setActiveInHierarchy(v) {
          this._activeInHierarchy = v;
        };
        Node._setScene = function _setScene(node) {
          node._updateScene();
        };
        Node._findComponent = function _findComponent(node, constructor) {
          var cls = constructor;
          var comps = node._components;
          if (cls._sealed) {
            for (var i = 0; i < comps.length; ++i) {
              var comp = comps[i];
              if (comp.constructor === constructor) {
                return comp;
              }
            }
          } else {
            for (var _i = 0; _i < comps.length; ++_i) {
              var _comp = comps[_i];
              if (_comp instanceof constructor) {
                return _comp;
              }
            }
          }
          return null;
        };
        Node._findComponents = function _findComponents(node, constructor, components) {
          var cls = constructor;
          var comps = node._components;
          if (cls._sealed) {
            for (var i = 0; i < comps.length; ++i) {
              var comp = comps[i];
              if (comp.constructor === constructor) {
                components.push(comp);
              }
            }
          } else {
            for (var _i2 = 0; _i2 < comps.length; ++_i2) {
              var _comp2 = comps[_i2];
              if (_comp2 instanceof constructor) {
                components.push(_comp2);
              }
            }
          }
        };
        Node._findChildComponent = function _findChildComponent(children, constructor) {
          for (var i = 0; i < children.length; ++i) {
            var node = children[i];
            var comp = Node._findComponent(node, constructor);
            if (comp) {
              return comp;
            }
            if (node._children.length > 0) {
              comp = Node._findChildComponent(node._children, constructor);
              if (comp) {
                return comp;
              }
            }
          }
          return null;
        };
        Node._findChildComponents = function _findChildComponents(children, constructor, components) {
          for (var i = 0; i < children.length; ++i) {
            var node = children[i];
            Node._findComponents(node, constructor, components);
            if (node._children.length > 0) {
              Node._findChildComponents(node._children, constructor, components);
            }
          }
        };
        _proto.getWritableComponents = function getWritableComponents() {
          return this._components;
        };
        _proto._updateScene = function _updateScene() {
          if (this._parent == null) {
            error('Node %s(%s) has not attached to a scene.', this.name, this.uuid);
          } else {
            this._scene = this._parent._scene;
          }
        };
        _proto.attr = function attr(attrs) {
          mixin(this, attrs);
        };
        _proto.getParent = function getParent() {
          return this._parent;
        };
        _proto.modifyParent = function modifyParent(parent) {
          this._parent = parent;
        };
        _proto.setParent = function setParent(value, keepWorldTransform) {
          if (keepWorldTransform === void 0) {
            keepWorldTransform = false;
          }
          if (keepWorldTransform) {
            this.updateWorldTransform();
          }
          if (this._parent === value) {
            return;
          }
          var oldParent = this._parent;
          var newParent = value;
          if (oldParent && oldParent._objFlags & Deactivating$1) {
            errorID(3821);
          }
          this._parent = newParent;
          this._siblingIndex = 0;
          this._onSetParent(oldParent, keepWorldTransform);
          if (this.emit) {
            this.emit(NodeEventType.PARENT_CHANGED, oldParent);
          }
          if (oldParent) {
            if (!(oldParent._objFlags & Destroying)) {
              var removeAt = oldParent._children.indexOf(this);
              oldParent._children.splice(removeAt, 1);
              oldParent._updateSiblingIndex();
              if (oldParent.emit) {
                oldParent.emit(NodeEventType.CHILD_REMOVED, this);
              }
            }
          }
          if (newParent) {
            if (newParent._objFlags & Deactivating$1) {
              errorID(3821);
            }
            newParent._children.push(this);
            this._siblingIndex = newParent._children.length - 1;
            if (newParent.emit) {
              newParent.emit(NodeEventType.CHILD_ADDED, this);
            }
          }
          this._onHierarchyChanged(oldParent);
        };
        _proto.getChildByUuid = function getChildByUuid(uuid) {
          if (!uuid) {
            log('Invalid uuid');
            return null;
          }
          var locChildren = this._children;
          for (var i = 0, len = locChildren.length; i < len; i++) {
            if (locChildren[i]._id === uuid) {
              return locChildren[i];
            }
          }
          return null;
        };
        _proto.getChildByName = function getChildByName(name) {
          if (!name) {
            log('Invalid name');
            return null;
          }
          var locChildren = this._children;
          for (var i = 0, len = locChildren.length; i < len; i++) {
            if (locChildren[i]._name === name) {
              return locChildren[i];
            }
          }
          return null;
        };
        _proto.getChildByPath = function getChildByPath(path) {
          var segments = path.split('/');
          var lastNode = this;
          var _loop = function _loop() {
              var segment = segments[i];
              if (segment.length === 0) {
                return 0;
              }
              var next = lastNode.children.find(function (childNode) {
                return childNode.name === segment;
              });
              if (!next) {
                return {
                  v: null
                };
              }
              lastNode = next;
            },
            _ret;
          for (var i = 0; i < segments.length; ++i) {
            _ret = _loop();
            if (_ret === 0) continue;
            if (_ret) return _ret.v;
          }
          return lastNode;
        };
        _proto.addChild = function addChild(child) {
          child.setParent(this);
        };
        _proto.insertChild = function insertChild(child, siblingIndex) {
          child.setParent(this);
          child.setSiblingIndex(siblingIndex);
        };
        _proto.getSiblingIndex = function getSiblingIndex() {
          return this._siblingIndex;
        };
        _proto.setSiblingIndex = function setSiblingIndex(index) {
          if (!this._parent) {
            return;
          }
          if (this._parent._objFlags & Deactivating$1) {
            errorID(3821);
            return;
          }
          var siblings = this._parent._children;
          index = index !== -1 ? index : siblings.length - 1;
          var oldIndex = siblings.indexOf(this);
          if (index !== oldIndex) {
            siblings.splice(oldIndex, 1);
            if (index < siblings.length) {
              siblings.splice(index, 0, this);
            } else {
              siblings.push(this);
            }
            this._parent._updateSiblingIndex();
            if (this._onSiblingIndexChanged) {
              this._onSiblingIndexChanged(index);
            }
            this._eventProcessor.onUpdatingSiblingIndex();
          }
        };
        _proto.walk = function walk(preFunc, postFunc) {
          var index = 1;
          var children = null;
          var curr = null;
          var i = 0;
          var stack = Node._stacks[Node._stackId];
          if (!stack) {
            stack = [];
            Node._stacks.push(stack);
          }
          Node._stackId++;
          stack.length = 0;
          stack[0] = this;
          var parent = null;
          var afterChildren = false;
          while (index) {
            index--;
            curr = stack[index];
            if (!curr) {
              continue;
            }
            if (!afterChildren && preFunc) {
              preFunc(curr);
            } else if (afterChildren && postFunc) {
              postFunc(curr);
            }
            stack[index] = null;
            if (afterChildren) {
              if (parent === this._parent) break;
              afterChildren = false;
            } else {
              if (curr._children.length > 0) {
                parent = curr;
                children = curr._children;
                i = 0;
                stack[index] = children[i];
                index++;
              } else {
                stack[index] = curr;
                index++;
                afterChildren = true;
              }
              continue;
            }
            if (children) {
              i++;
              if (children[i]) {
                stack[index] = children[i];
                index++;
              } else if (parent) {
                stack[index] = parent;
                index++;
                afterChildren = true;
                if (parent._parent) {
                  children = parent._parent._children;
                  i = children.indexOf(parent);
                  parent = parent._parent;
                } else {
                  parent = null;
                  children = null;
                }
                if (i < 0) {
                  break;
                }
              }
            }
          }
          stack.length = 0;
          Node._stackId--;
        };
        _proto.removeFromParent = function removeFromParent() {
          if (this._parent) {
            this._parent.removeChild(this);
          }
        };
        _proto.removeChild = function removeChild(child) {
          if (this._children.indexOf(child) > -1) {
            child.parent = null;
          }
        };
        _proto.removeAllChildren = function removeAllChildren() {
          var children = this._children;
          for (var i = children.length - 1; i >= 0; i--) {
            var node = children[i];
            if (node) {
              node.parent = null;
            }
          }
          this._children.length = 0;
        };
        _proto.isChildOf = function isChildOf(parent) {
          var child = this;
          do {
            if (child === parent) {
              return true;
            }
            child = child._parent;
          } while (child);
          return false;
        };
        _proto.getComponent = function getComponent(typeOrClassName) {
          var constructor = getConstructor(typeOrClassName);
          if (constructor) {
            return Node._findComponent(this, constructor);
          }
          return null;
        };
        _proto.getComponents = function getComponents(typeOrClassName) {
          var constructor = getConstructor(typeOrClassName);
          var components = [];
          if (constructor) {
            Node._findComponents(this, constructor, components);
          }
          return components;
        };
        _proto.getComponentInChildren = function getComponentInChildren(typeOrClassName) {
          var constructor = getConstructor(typeOrClassName);
          if (constructor) {
            return Node._findChildComponent(this._children, constructor);
          }
          return null;
        };
        _proto.getComponentsInChildren = function getComponentsInChildren(typeOrClassName) {
          var constructor = getConstructor(typeOrClassName);
          var components = [];
          if (constructor) {
            Node._findComponents(this, constructor, components);
            Node._findChildComponents(this._children, constructor, components);
          }
          return components;
        };
        _proto.addComponent = function addComponent(typeOrClassName) {
          var constructor;
          if (typeof typeOrClassName === 'string') {
            constructor = getClassByName(typeOrClassName);
            if (!constructor) {
              if (legacyCC._RF.peek()) {
                errorID(3808, typeOrClassName);
              }
              throw TypeError(getError(3807, typeOrClassName));
            }
          } else {
            if (!typeOrClassName) {
              throw TypeError(getError(3804));
            }
            constructor = typeOrClassName;
          }
          if (typeof constructor !== 'function') {
            throw TypeError(getError(3809));
          }
          if (!isChildClassOf(constructor, legacyCC.Component)) {
            throw TypeError(getError(3810));
          }
          var reqComps = constructor._requireComponent;
          if (reqComps) {
            if (Array.isArray(reqComps)) {
              for (var i = 0; i < reqComps.length; i++) {
                var reqComp = reqComps[i];
                if (!this.getComponent(reqComp)) {
                  this.addComponent(reqComp);
                }
              }
            } else {
              var _reqComp = reqComps;
              if (!this.getComponent(_reqComp)) {
                this.addComponent(_reqComp);
              }
            }
          }
          var component = new constructor();
          component.node = this;
          this._components.push(component);
          this.emit(NodeEventType.COMPONENT_ADDED, component);
          if (this._activeInHierarchy) {
            legacyCC.director._nodeActivator.activateComp(component);
          }
          return component;
        };
        _proto.removeComponent = function removeComponent(component) {
          if (!component) {
            errorID(3813);
            return;
          }
          var componentInstance = null;
          if (component instanceof Component) {
            componentInstance = component;
          } else {
            componentInstance = this.getComponent(component);
          }
          if (componentInstance) {
            componentInstance.destroy();
          }
        };
        _proto.on = function on(type, callback, target, useCapture) {
          if (useCapture === void 0) {
            useCapture = false;
          }
          switch (type) {
            case NodeEventType.TRANSFORM_CHANGED:
              this._eventMask |= TRANSFORM_ON;
              break;
          }
          this._eventProcessor.on(type, callback, target, useCapture);
        };
        _proto.off = function off(type, callback, target, useCapture) {
          if (useCapture === void 0) {
            useCapture = false;
          }
          this._eventProcessor.off(type, callback, target, useCapture);
          var hasListeners = this._eventProcessor.hasEventListener(type);
          if (!hasListeners) {
            switch (type) {
              case NodeEventType.TRANSFORM_CHANGED:
                this._eventMask &= ~TRANSFORM_ON;
                break;
            }
          }
        };
        _proto.once = function once(type, callback, target, useCapture) {
          this._eventProcessor.once(type, callback, target, useCapture);
        };
        _proto.emit = function emit(type, arg0, arg1, arg2, arg3, arg4) {
          this._eventProcessor.emit(type, arg0, arg1, arg2, arg3, arg4);
        };
        _proto.dispatchEvent = function dispatchEvent(event) {
          this._eventProcessor.dispatchEvent(event);
        };
        _proto.hasEventListener = function hasEventListener(type, callback, target) {
          return this._eventProcessor.hasEventListener(type, callback, target);
        };
        _proto.targetOff = function targetOff(target) {
          this._eventProcessor.targetOff(target);
          if (this._eventMask & TRANSFORM_ON && !this._eventProcessor.hasEventListener(NodeEventType.TRANSFORM_CHANGED)) {
            this._eventMask &= ~TRANSFORM_ON;
          }
        };
        _proto.destroy = function destroy() {
          if (_CCObject.prototype.destroy.call(this)) {
            this.active = false;
            return true;
          }
          return false;
        };
        _proto.destroyAllChildren = function destroyAllChildren() {
          var children = this._children;
          for (var i = 0; i < children.length; ++i) {
            children[i].destroy();
          }
        };
        _proto._removeComponent = function _removeComponent(component) {
          if (!component) {
            errorID(3814);
            return;
          }
          if (!(this._objFlags & Destroying)) {
            var i = this._components.indexOf(component);
            if (i !== -1) {
              this._components.splice(i, 1);
              this.emit(NodeEventType.COMPONENT_REMOVED, component);
            } else if (component.node !== this) {
              errorID(3815);
            }
          }
        };
        _proto._updateSiblingIndex = function _updateSiblingIndex() {
          for (var i = 0; i < this._children.length; ++i) {
            this._children[i]._siblingIndex = i;
          }
          this.emit(NodeEventType.SIBLING_ORDER_CHANGED);
        };
        _proto._instantiate = function _instantiate(cloned, isSyncedNode) {
          if (!cloned) {
            cloned = legacyCC.instantiate._clone(this, this);
          }
          cloned._prefab;
          cloned._parent = null;
          cloned._onBatchCreated(isSyncedNode);
          return cloned;
        };
        _proto._onHierarchyChangedBase = function _onHierarchyChangedBase(oldParent) {
          var newParent = this._parent;
          if (this._persistNode && !(newParent instanceof legacyCC.Scene)) {
            legacyCC.game.removePersistRootNode(this);
          }
          var shouldActiveNow = this._active && !!(newParent && newParent._activeInHierarchy);
          if (this._activeInHierarchy !== shouldActiveNow) {
            legacyCC.director._nodeActivator.activateNode(this, shouldActiveNow);
          }
        };
        _proto._onPreDestroyBase = function _onPreDestroyBase() {
          this._objFlags |= Destroying;
          var parent = this._parent;
          var destroyByParent = !!parent && (parent._objFlags & Destroying) !== 0;
          if (!destroyByParent && EDITOR) {
            this._registerIfAttached(false);
          }
          if (this._persistNode) {
            legacyCC.game.removePersistRootNode(this);
          }
          if (!destroyByParent) {
            if (parent) {
              this.emit(NodeEventType.PARENT_CHANGED, this);
              var childIndex = parent._children.indexOf(this);
              parent._children.splice(childIndex, 1);
              this._siblingIndex = 0;
              parent._updateSiblingIndex();
              if (parent.emit) {
                parent.emit(NodeEventType.CHILD_REMOVED, this);
              }
            }
          }
          this.emit(NodeEventType.NODE_DESTROYED, this);
          this._eventProcessor.destroy();
          var children = this._children;
          for (var i = 0; i < children.length; ++i) {
            children[i]._destroyImmediate();
          }
          var comps = this._components;
          for (var _i3 = 0; _i3 < comps.length; ++_i3) {
            comps[_i3]._destroyImmediate();
          }
          return destroyByParent;
        };
        function Node(name) {
          var _this;
          _this = _CCObject.call(this, name) || this;
          _this._parent = _initializer$2f && _initializer$2f();
          _this._children = _initializer2$1L && _initializer2$1L();
          _this._active = _initializer3$1a && _initializer3$1a();
          _this._components = _initializer4$V && _initializer4$V();
          _this._prefab = _initializer5$G && _initializer5$G();
          _this._scene = null;
          _this._activeInHierarchy = false;
          _this._id = idGenerator.getNewId();
          _this._name = void 0;
          _this._eventProcessor = new legacyCC.NodeEventProcessor(_assertThisInitialized(_this));
          _this._eventMask = 0;
          _this._siblingIndex = 0;
          _this._originalSceneId = '';
          _this._uiProps = new NodeUIProperties(_assertThisInitialized(_this));
          _this._static = false;
          _this._lpos = _initializer6$x && _initializer6$x();
          _this._lrot = _initializer7$r && _initializer7$r();
          _this._lscale = _initializer8$q && _initializer8$q();
          _this._mobility = _initializer9$o && _initializer9$o();
          _this._layer = _initializer10$m && _initializer10$m();
          _this._euler = _initializer11$j && _initializer11$j();
          _this._transformFlags = TransformBit.NONE;
          _this._eulerDirty = false;
          _this._flagChangeVersion = 0;
          _this._hasChangedFlags = 0;
          _this._name = name !== undefined ? name : 'New Node';
          _this._pos = new Vec3();
          _this._rot = new Quat();
          _this._scale = new Vec3(1, 1, 1);
          _this._mat = new Mat4();
          return _this;
        }
        Node.isNode = function isNode(obj) {
          return obj instanceof Node && (obj.constructor === Node || !(obj instanceof legacyCC.Scene));
        };
        _proto._onPreDestroy = function _onPreDestroy() {
          return this._onPreDestroyBase();
        };
        _proto[serializeTag] = function (serializationOutput, context) {
          {
            serializationOutput.writeThis();
            return;
          }
        };
        _proto._onSetParent = function _onSetParent(oldParent, keepWorldTransform) {
          if (keepWorldTransform === void 0) {
            keepWorldTransform = false;
          }
          if (this._parent) {
            if ((oldParent == null || oldParent._scene !== this._parent._scene) && this._parent._scene != null) {
              this.walk(Node._setScene);
            }
          }
          if (keepWorldTransform) {
            var parent = this._parent;
            if (parent) {
              parent.updateWorldTransform();
              if (approx(Mat4.determinant(parent._mat), 0, EPSILON$3)) {
                warnID(14300);
                this._transformFlags |= TransformBit.TRS;
                this.updateWorldTransform();
              } else {
                Mat4.multiply(m4_1$7, Mat4.invert(m4_1$7, parent._mat), this._mat);
                Mat4.toRTS(m4_1$7, this._lrot, this._lpos, this._lscale);
              }
            } else {
              Vec3.copy(this._lpos, this._pos);
              Quat.copy(this._lrot, this._rot);
              Vec3.copy(this._lscale, this._scale);
            }
            this._eulerDirty = true;
          }
          this.invalidateChildren(TransformBit.TRS);
        };
        _proto._onHierarchyChanged = function _onHierarchyChanged(oldParent) {
          this.eventProcessor.reattach();
          this._onHierarchyChangedBase(oldParent);
        };
        _proto._onBatchCreated = function _onBatchCreated(dontSyncChildPrefab) {
          this.hasChangedFlags = TransformBit.TRS;
          this._transformFlags |= TransformBit.TRS;
          var len = this._children.length;
          for (var i = 0; i < len; ++i) {
            this._children[i]._siblingIndex = i;
            this._children[i]._onBatchCreated(dontSyncChildPrefab);
          }
        };
        _proto._onBeforeSerialize = function _onBeforeSerialize() {
          this.eulerAngles;
        };
        _proto._onPostActivated = function _onPostActivated(active) {
          if (active) {
            this._eventProcessor.setEnabled(true);
            this.invalidateChildren(TransformBit.TRS);
            if (this._uiProps && this._uiProps.uiComp) {
              this._uiProps.uiComp.setNodeDirty();
              this._uiProps.uiComp.setTextureDirty();
              this._uiProps.uiComp.markForUpdateRenderData();
            }
          } else {
            this._eventProcessor.setEnabled(false);
          }
        };
        _proto.translate = function translate(trans, ns) {
          var space = ns || NodeSpace.LOCAL;
          if (space === NodeSpace.LOCAL) {
            Vec3.transformQuat(v3_a, trans, this._lrot);
            this._lpos.x += v3_a.x;
            this._lpos.y += v3_a.y;
            this._lpos.z += v3_a.z;
          } else if (space === NodeSpace.WORLD) {
            if (this._parent) {
              Quat.invert(q_a, this._parent.worldRotation);
              Vec3.transformQuat(v3_a, trans, q_a);
              var _scale = this.worldScale;
              this._lpos.x += v3_a.x / _scale.x;
              this._lpos.y += v3_a.y / _scale.y;
              this._lpos.z += v3_a.z / _scale.z;
            } else {
              this._lpos.x += trans.x;
              this._lpos.y += trans.y;
              this._lpos.z += trans.z;
            }
          }
          this.invalidateChildren(TransformBit.POSITION);
          if (this._eventMask & TRANSFORM_ON) {
            this.emit(NodeEventType.TRANSFORM_CHANGED, TransformBit.POSITION);
          }
        };
        _proto.rotate = function rotate(rot, ns) {
          var space = ns || NodeSpace.LOCAL;
          Quat.normalize(q_a, rot);
          if (space === NodeSpace.LOCAL) {
            Quat.multiply(this._lrot, this._lrot, q_a);
          } else if (space === NodeSpace.WORLD) {
            var worldRot = this.worldRotation;
            Quat.multiply(q_b, q_a, worldRot);
            Quat.invert(q_a, worldRot);
            Quat.multiply(q_b, q_a, q_b);
            Quat.multiply(this._lrot, this._lrot, q_b);
          }
          this._eulerDirty = true;
          this.invalidateChildren(TransformBit.ROTATION);
          if (this._eventMask & TRANSFORM_ON) {
            this.emit(NodeEventType.TRANSFORM_CHANGED, TransformBit.ROTATION);
          }
        };
        _proto.lookAt = function lookAt(pos, up) {
          this.getWorldPosition(v3_a);
          Vec3.subtract(v3_a, v3_a, pos);
          Vec3.normalize(v3_a, v3_a);
          Quat.fromViewUp(q_a, v3_a, up);
          this.setWorldRotation(q_a);
        };
        _proto.invalidateChildren = function invalidateChildren(dirtyBit) {
          var i = 0;
          var j = 0;
          var l = 0;
          var cur;
          var children;
          var hasChangedFlags = 0;
          var childDirtyBit = dirtyBit | TransformBit.POSITION;
          dirtyNodes[0] = this;
          while (i >= 0) {
            cur = dirtyNodes[i--];
            hasChangedFlags = cur.hasChangedFlags;
            if (cur.isValid && (cur._transformFlags & hasChangedFlags & dirtyBit) !== dirtyBit) {
              cur._transformFlags |= dirtyBit;
              cur.hasChangedFlags = hasChangedFlags | dirtyBit;
              children = cur._children;
              l = children.length;
              for (j = 0; j < l; j++) {
                dirtyNodes[++i] = children[j];
              }
            }
            dirtyBit = childDirtyBit;
          }
        };
        _proto.updateWorldTransform = function updateWorldTransform() {
          if (!this._transformFlags) {
            return;
          }
          var cur = this;
          var i = 0;
          while (cur && cur._transformFlags) {
            dirtyNodes[i++] = cur;
            cur = cur._parent;
          }
          var child;
          var dirtyBits = 0;
          while (i) {
            child = dirtyNodes[--i];
            dirtyBits |= child._transformFlags;
            if (cur) {
              if (dirtyBits & TransformBit.POSITION) {
                Vec3.transformMat4(child._pos, child._lpos, cur._mat);
                child._mat.m12 = child._pos.x;
                child._mat.m13 = child._pos.y;
                child._mat.m14 = child._pos.z;
              }
              if (dirtyBits & TransformBit.RS) {
                Mat4.fromRTS(child._mat, child._lrot, child._lpos, child._lscale);
                Mat4.multiply(child._mat, cur._mat, child._mat);
                var rotTmp = dirtyBits & TransformBit.ROTATION ? child._rot : null;
                Mat4.toRTS(child._mat, rotTmp, null, child._scale);
              }
            } else {
              if (dirtyBits & TransformBit.POSITION) {
                Vec3.copy(child._pos, child._lpos);
                child._mat.m12 = child._pos.x;
                child._mat.m13 = child._pos.y;
                child._mat.m14 = child._pos.z;
              }
              if (dirtyBits & TransformBit.RS) {
                if (dirtyBits & TransformBit.ROTATION) {
                  Quat.copy(child._rot, child._lrot);
                }
                if (dirtyBits & TransformBit.SCALE) {
                  Vec3.copy(child._scale, child._lscale);
                }
                Mat4.fromRTS(child._mat, child._rot, child._pos, child._scale);
              }
            }
            child._transformFlags = TransformBit.NONE;
            cur = child;
          }
        };
        _proto.setPosition = function setPosition(val, y, z) {
          if (y === undefined && z === undefined) {
            Vec3.copy(this._lpos, val);
          } else if (z === undefined) {
            Vec3.set(this._lpos, val, y, this._lpos.z);
          } else {
            Vec3.set(this._lpos, val, y, z);
          }
          this.invalidateChildren(TransformBit.POSITION);
          if (this._eventMask & TRANSFORM_ON) {
            this.emit(NodeEventType.TRANSFORM_CHANGED, TransformBit.POSITION);
          }
        };
        _proto.getPosition = function getPosition(out) {
          if (out) {
            return Vec3.set(out, this._lpos.x, this._lpos.y, this._lpos.z);
          }
          return Vec3.copy(new Vec3(), this._lpos);
        };
        _proto.setRotation = function setRotation(val, y, z, w) {
          if (y === undefined || z === undefined || w === undefined) {
            Quat.copy(this._lrot, val);
          } else {
            Quat.set(this._lrot, val, y, z, w);
          }
          this._eulerDirty = true;
          this.invalidateChildren(TransformBit.ROTATION);
          if (this._eventMask & TRANSFORM_ON) {
            this.emit(NodeEventType.TRANSFORM_CHANGED, TransformBit.ROTATION);
          }
        };
        _proto.setRotationFromEuler = function setRotationFromEuler(val, y, zOpt) {
          var z = zOpt === undefined ? this._euler.z : zOpt;
          if (y === undefined) {
            Vec3.copy(this._euler, val);
            Quat.fromEuler(this._lrot, val.x, val.y, val.z);
          } else {
            Vec3.set(this._euler, val, y, z);
            Quat.fromEuler(this._lrot, val, y, z);
          }
          this._eulerDirty = false;
          this.invalidateChildren(TransformBit.ROTATION);
          if (this._eventMask & TRANSFORM_ON) {
            this.emit(NodeEventType.TRANSFORM_CHANGED, TransformBit.ROTATION);
          }
        };
        _proto.getRotation = function getRotation(out) {
          if (out) {
            return Quat.set(out, this._lrot.x, this._lrot.y, this._lrot.z, this._lrot.w);
          }
          return Quat.copy(new Quat(), this._lrot);
        };
        _proto.setScale = function setScale(val, y, z) {
          if (y === undefined && z === undefined) {
            Vec3.copy(this._lscale, val);
          } else if (z === undefined) {
            Vec3.set(this._lscale, val, y, this._lscale.z);
          } else {
            Vec3.set(this._lscale, val, y, z);
          }
          this.invalidateChildren(TransformBit.SCALE);
          if (this._eventMask & TRANSFORM_ON) {
            this.emit(NodeEventType.TRANSFORM_CHANGED, TransformBit.SCALE);
          }
        };
        _proto.getScale = function getScale(out) {
          if (out) {
            return Vec3.set(out, this._lscale.x, this._lscale.y, this._lscale.z);
          }
          return Vec3.copy(new Vec3(), this._lscale);
        };
        _proto.inverseTransformPoint = function inverseTransformPoint(out, p) {
          Vec3.copy(out, p);
          var cur = this;
          var i = 0;
          while (cur._parent) {
            dirtyNodes[i++] = cur;
            cur = cur._parent;
          }
          while (i >= 0) {
            Vec3.transformInverseRTS(out, out, cur._lrot, cur._lpos, cur._lscale);
            cur = dirtyNodes[--i];
          }
          return out;
        };
        _proto.setWorldPosition = function setWorldPosition(val, y, z) {
          if (y === undefined || z === undefined) {
            Vec3.copy(this._pos, val);
          } else {
            Vec3.set(this._pos, val, y, z);
          }
          var parent = this._parent;
          var local = this._lpos;
          if (parent) {
            parent.updateWorldTransform();
            Vec3.transformMat4(local, this._pos, Mat4.invert(m4_1$7, parent._mat));
          } else {
            Vec3.copy(local, this._pos);
          }
          this.invalidateChildren(TransformBit.POSITION);
          if (this._eventMask & TRANSFORM_ON) {
            this.emit(NodeEventType.TRANSFORM_CHANGED, TransformBit.POSITION);
          }
        };
        _proto.getWorldPosition = function getWorldPosition(out) {
          this.updateWorldTransform();
          if (out) {
            return Vec3.copy(out, this._pos);
          }
          return Vec3.copy(new Vec3(), this._pos);
        };
        _proto.setWorldRotation = function setWorldRotation(val, y, z, w) {
          if (y === undefined || z === undefined || w === undefined) {
            Quat.copy(this._rot, val);
          } else {
            Quat.set(this._rot, val, y, z, w);
          }
          if (this._parent) {
            this._parent.updateWorldTransform();
            Quat.multiply(this._lrot, Quat.conjugate(this._lrot, this._parent._rot), this._rot);
          } else {
            Quat.copy(this._lrot, this._rot);
          }
          this._eulerDirty = true;
          this.invalidateChildren(TransformBit.ROTATION);
          if (this._eventMask & TRANSFORM_ON) {
            this.emit(NodeEventType.TRANSFORM_CHANGED, TransformBit.ROTATION);
          }
        };
        _proto.setWorldRotationFromEuler = function setWorldRotationFromEuler(x, y, z) {
          Quat.fromEuler(this._rot, x, y, z);
          if (this._parent) {
            this._parent.updateWorldTransform();
            Quat.multiply(this._lrot, Quat.conjugate(this._lrot, this._parent._rot), this._rot);
          } else {
            Quat.copy(this._lrot, this._rot);
          }
          this._eulerDirty = true;
          this.invalidateChildren(TransformBit.ROTATION);
          if (this._eventMask & TRANSFORM_ON) {
            this.emit(NodeEventType.TRANSFORM_CHANGED, TransformBit.ROTATION);
          }
        };
        _proto.getWorldRotation = function getWorldRotation(out) {
          this.updateWorldTransform();
          if (out) {
            return Quat.copy(out, this._rot);
          }
          return Quat.copy(new Quat(), this._rot);
        };
        _proto.setWorldScale = function setWorldScale(val, y, z) {
          var parent = this._parent;
          if (parent) {
            this.updateWorldTransform();
          }
          if (y === undefined || z === undefined) {
            Vec3.copy(this._scale, val);
          } else {
            Vec3.set(this._scale, val, y, z);
          }
          if (parent) {
            v3_a.x = this._scale.x / Vec3.set(v3_b, this._mat.m00, this._mat.m01, this._mat.m02).length();
            v3_a.y = this._scale.y / Vec3.set(v3_b, this._mat.m04, this._mat.m05, this._mat.m06).length();
            v3_a.z = this._scale.z / Vec3.set(v3_b, this._mat.m08, this._mat.m09, this._mat.m10).length();
            Mat4.scale(m4_1$7, this._mat, v3_a);
            Mat4.multiply(m4_2$3, Mat4.invert(m4_2$3, parent._mat), m4_1$7);
            Mat3.fromQuat(m3_1, Quat.conjugate(qt_1, this._lrot));
            Mat3.multiplyMat4(m3_1, m3_1, m4_2$3);
            this._lscale.x = Vec3.set(v3_a, m3_1.m00, m3_1.m01, m3_1.m02).length();
            this._lscale.y = Vec3.set(v3_a, m3_1.m03, m3_1.m04, m3_1.m05).length();
            this._lscale.z = Vec3.set(v3_a, m3_1.m06, m3_1.m07, m3_1.m08).length();
          } else {
            Vec3.copy(this._lscale, this._scale);
          }
          this.invalidateChildren(TransformBit.SCALE);
          if (this._eventMask & TRANSFORM_ON) {
            this.emit(NodeEventType.TRANSFORM_CHANGED, TransformBit.SCALE);
          }
        };
        _proto.getWorldScale = function getWorldScale(out) {
          this.updateWorldTransform();
          if (out) {
            return Vec3.copy(out, this._scale);
          }
          return Vec3.copy(new Vec3(), this._scale);
        };
        _proto.getWorldMatrix = function getWorldMatrix(out) {
          this.updateWorldTransform();
          var target = out || new Mat4();
          return Mat4.copy(target, this._mat);
        };
        _proto.getWorldRS = function getWorldRS(out) {
          this.updateWorldTransform();
          var target = out || new Mat4();
          Mat4.copy(target, this._mat);
          target.m12 = 0;
          target.m13 = 0;
          target.m14 = 0;
          return target;
        };
        _proto.getWorldRT = function getWorldRT(out) {
          this.updateWorldTransform();
          var target = out || new Mat4();
          return Mat4.fromRT(target, this._rot, this._pos);
        };
        _proto.setRTS = function setRTS(rot, pos, scale) {
          var dirtyBit = 0;
          if (rot) {
            dirtyBit |= TransformBit.ROTATION;
            if (rot.w !== undefined) {
              Quat.copy(this._lrot, rot);
              this._eulerDirty = true;
            } else {
              Vec3.copy(this._euler, rot);
              Quat.fromEuler(this._lrot, rot.x, rot.y, rot.z);
              this._eulerDirty = false;
            }
          }
          if (pos) {
            Vec3.copy(this._lpos, pos);
            dirtyBit |= TransformBit.POSITION;
          }
          if (scale) {
            Vec3.copy(this._lscale, scale);
            dirtyBit |= TransformBit.SCALE;
          }
          if (dirtyBit) {
            this.invalidateChildren(dirtyBit);
            if (this._eventMask & TRANSFORM_ON) {
              this.emit(NodeEventType.TRANSFORM_CHANGED, dirtyBit);
            }
          }
        };
        _proto.isTransformDirty = function isTransformDirty() {
          return this._transformFlags !== TransformBit.NONE;
        };
        _proto.pauseSystemEvents = function pauseSystemEvents(recursive) {
          this._eventProcessor.setEnabled(false, recursive);
        };
        _proto.resumeSystemEvents = function resumeSystemEvents(recursive) {
          this._eventProcessor.setEnabled(true, recursive);
        };
        Node.resetHasChangedFlags = function resetHasChangedFlags() {
          globalFlagChangeVersion += 1;
        };
        Node.clearNodeArray = function clearNodeArray() {
          if (Node.ClearFrame < Node.ClearRound && !EDITOR) {
            Node.ClearFrame++;
          } else {
            Node.ClearFrame = 0;
            dirtyNodes.length = 0;
          }
        };
        _proto.getPathInHierarchy = function getPathInHierarchy() {
          var result = this.name;
          var curNode = this.parent;
          while (curNode && !(curNode instanceof legacyCC.Scene)) {
            result = curNode.name + "/" + result;
            curNode = curNode.parent;
          }
          return result;
        };
        _createClass(Node, [{
          key: "components",
          get: function get() {
            return this._components;
          }
        }, {
          key: "_persistNode",
          get: function get() {
            return (this._objFlags & DontDestroy) > 0;
          },
          set: function set(value) {
            if (value) {
              this._objFlags |= DontDestroy;
            } else {
              this._objFlags &= ~DontDestroy;
            }
          }
        }, {
          key: "name",
          get: function get() {
            return this._name;
          },
          set: function set(value) {
            this._name = value;
          }
        }, {
          key: "uuid",
          get: function get() {
            return this._id;
          }
        }, {
          key: "children",
          get: function get() {
            return this._children;
          }
        }, {
          key: "active",
          get: function get() {
            return this._active;
          },
          set: function set(isActive) {
            isActive = !!isActive;
            if (this._active !== isActive) {
              this._active = isActive;
              var parent = this._parent;
              if (parent) {
                var couldActiveInScene = parent._activeInHierarchy;
                if (couldActiveInScene) {
                  legacyCC.director._nodeActivator.activateNode(this, isActive);
                }
              }
            }
          }
        }, {
          key: "activeInHierarchy",
          get: function get() {
            return this._activeInHierarchy;
          }
        }, {
          key: "parent",
          get: function get() {
            return this._parent;
          },
          set: function set(value) {
            this.setParent(value);
          }
        }, {
          key: "scene",
          get: function get() {
            return this._scene;
          }
        }, {
          key: "eventProcessor",
          get: function get() {
            return this._eventProcessor;
          }
        }, {
          key: "prefab",
          get: function get() {
            return this._prefab;
          }
        }, {
          key: "id",
          set: function set(v) {
            this._id = v;
          }
        }, {
          key: "siblingIndex",
          get: function get() {
            return this._siblingIndex;
          },
          set: function set(val) {
            this._siblingIndex = val;
          }
        }, {
          key: "position",
          get: function get() {
            return this._lpos;
          },
          set: function set(val) {
            this.setPosition(val);
          }
        }, {
          key: "worldPosition",
          get: function get() {
            this.updateWorldTransform();
            return this._pos;
          },
          set: function set(val) {
            this.setWorldPosition(val);
          }
        }, {
          key: "rotation",
          get: function get() {
            return this._lrot;
          },
          set: function set(val) {
            this.setRotation(val);
          }
        }, {
          key: "eulerAngles",
          get: function get() {
            if (this._eulerDirty) {
              Quat.toEuler(this._euler, this._lrot);
              this._eulerDirty = false;
            }
            return this._euler;
          },
          set: function set(val) {
            this.setRotationFromEuler(val.x, val.y, val.z);
          }
        }, {
          key: "angle",
          get: function get() {
            return this._euler.z;
          },
          set: function set(val) {
            Vec3.set(this._euler, 0, 0, val);
            Quat.fromAngleZ(this._lrot, val);
            this._eulerDirty = false;
            this.invalidateChildren(TransformBit.ROTATION);
            if (this._eventMask & TRANSFORM_ON) {
              this.emit(NodeEventType.TRANSFORM_CHANGED, TransformBit.ROTATION);
            }
          }
        }, {
          key: "worldRotation",
          get: function get() {
            this.updateWorldTransform();
            return this._rot;
          },
          set: function set(val) {
            this.setWorldRotation(val);
          }
        }, {
          key: "scale",
          get: function get() {
            return this._lscale;
          },
          set: function set(val) {
            this.setScale(val);
          }
        }, {
          key: "worldScale",
          get: function get() {
            this.updateWorldTransform();
            return this._scale;
          },
          set: function set(val) {
            this.setWorldScale(val);
          }
        }, {
          key: "matrix",
          set: function set(val) {
            Mat4.toRTS(val, this._lrot, this._lpos, this._lscale);
            this.invalidateChildren(TransformBit.TRS);
            this._eulerDirty = true;
            if (this._eventMask & TRANSFORM_ON) {
              this.emit(NodeEventType.TRANSFORM_CHANGED, TransformBit.TRS);
            }
          }
        }, {
          key: "worldMatrix",
          get: function get() {
            this.updateWorldTransform();
            return this._mat;
          }
        }, {
          key: "forward",
          get: function get() {
            return Vec3.transformQuat(new Vec3(), Vec3.FORWARD, this.worldRotation);
          },
          set: function set(dir) {
            var len = dir.length();
            Vec3.multiplyScalar(v3_a, dir, -1 / len);
            Quat.fromViewUp(q_a, v3_a);
            this.setWorldRotation(q_a);
          }
        }, {
          key: "up",
          get: function get() {
            return Vec3.transformQuat(new Vec3(), Vec3.UP, this.worldRotation);
          }
        }, {
          key: "right",
          get: function get() {
            return Vec3.transformQuat(new Vec3(), Vec3.RIGHT, this.worldRotation);
          }
        }, {
          key: "mobility",
          get: function get() {
            return this._mobility;
          },
          set: function set(m) {
            this._mobility = m;
            this.emit(NodeEventType.MOBILITY_CHANGED);
          }
        }, {
          key: "layer",
          get: function get() {
            return this._layer;
          },
          set: function set(l) {
            this._layer = l;
            if (this._uiProps && this._uiProps.uiComp) {
              this._uiProps.uiComp.setNodeDirty();
              this._uiProps.uiComp.markForUpdateRenderData();
            }
            this.emit(NodeEventType.LAYER_CHANGED, this._layer);
          }
        }, {
          key: "flagChangedVersion",
          get: function get() {
            return this._flagChangeVersion;
          }
        }, {
          key: "hasChangedFlags",
          get: function get() {
            return this._flagChangeVersion === globalFlagChangeVersion ? this._hasChangedFlags : 0;
          },
          set: function set(val) {
            this._flagChangeVersion = globalFlagChangeVersion;
            this._hasChangedFlags = val;
          }
        }]);
        return Node;
      }(CCObject), _class3$J.idGenerator = idGenerator, _class3$J._stacks = [[]], _class3$J._stackId = 0, _class3$J.EventType = NodeEventType, _class3$J.NodeSpace = NodeSpace, _class3$J.TransformDirtyBit = TransformBit, _class3$J.TransformBit = TransformBit, _class3$J.reserveContentsForAllSyncablePrefabTag = reserveContentsForAllSyncablePrefabTag, _class3$J.ClearFrame = 0, _class3$J.ClearRound = 1000, _class3$J), (_applyDecoratedDescriptor(_class2$2v.prototype, "_persistNode", [property$3], Object.getOwnPropertyDescriptor(_class2$2v.prototype, "_persistNode"), _class2$2v.prototype), _initializer$2f = applyDecoratedInitializer(_class2$2v.prototype, "_parent", [serializable$j], function () {
        return null;
      }), _initializer2$1L = applyDecoratedInitializer(_class2$2v.prototype, "_children", [serializable$j], function () {
        return [];
      }), _initializer3$1a = applyDecoratedInitializer(_class2$2v.prototype, "_active", [serializable$j], function () {
        return true;
      }), _initializer4$V = applyDecoratedInitializer(_class2$2v.prototype, "_components", [serializable$j], function () {
        return [];
      }), _initializer5$G = applyDecoratedInitializer(_class2$2v.prototype, "_prefab", [serializable$j], function () {
        return null;
      }), _initializer6$x = applyDecoratedInitializer(_class2$2v.prototype, "_lpos", [serializable$j], function () {
        return new Vec3();
      }), _initializer7$r = applyDecoratedInitializer(_class2$2v.prototype, "_lrot", [serializable$j], function () {
        return new Quat();
      }), _initializer8$q = applyDecoratedInitializer(_class2$2v.prototype, "_lscale", [serializable$j], function () {
        return new Vec3(1, 1, 1);
      }), _initializer9$o = applyDecoratedInitializer(_class2$2v.prototype, "_mobility", [serializable$j], function () {
        return MobilityMode.Static;
      }), _initializer10$m = applyDecoratedInitializer(_class2$2v.prototype, "_layer", [serializable$j], function () {
        return Layers.Enum.DEFAULT;
      }), _initializer11$j = applyDecoratedInitializer(_class2$2v.prototype, "_euler", [serializable$j], function () {
        return new Vec3();
      }), _applyDecoratedDescriptor(_class2$2v.prototype, "eulerAngles", [_dec2$22], Object.getOwnPropertyDescriptor(_class2$2v.prototype, "eulerAngles"), _class2$2v.prototype), _applyDecoratedDescriptor(_class2$2v.prototype, "mobility", [_dec3$1p], Object.getOwnPropertyDescriptor(_class2$2v.prototype, "mobility"), _class2$2v.prototype)), _class2$2v)) || _class$2K));
      legacyCC.Node = Node$1;

      var Ambient = function () {
        function Ambient() {
          this._groundAlbedoHDR = new Vec4(0.2, 0.2, 0.2, 1.0);
          this._skyColorHDR = new Vec4(0.2, 0.5, 0.8, 1.0);
          this._skyIllumHDR = 0;
          this._groundAlbedoLDR = new Vec4(0.2, 0.2, 0.2, 1.0);
          this._skyColorLDR = new Vec4(0.2, 0.5, 0.8, 1.0);
          this._skyIllumLDR = 0;
          this._mipmapCount = 1;
          this._enabled = false;
        }
        var _proto = Ambient.prototype;
        _proto.initialize = function initialize(ambientInfo) {
          this._skyColorHDR = ambientInfo.skyColorHDR;
          this._groundAlbedoHDR.set(ambientInfo.groundAlbedoHDR);
          this._skyIllumHDR = ambientInfo.skyIllumHDR;
          this._skyColorLDR = ambientInfo.skyColorLDR;
          this._groundAlbedoLDR.set(ambientInfo.groundAlbedoLDR);
          this._skyIllumLDR = ambientInfo.skyIllumLDR;
        };
        _createClass(Ambient, [{
          key: "enabled",
          get: function get() {
            return this._enabled;
          },
          set: function set(val) {
            this._enabled = val;
          }
        }, {
          key: "skyColor",
          get: function get() {
            var isHDR = legacyCC.director.root.pipeline.pipelineSceneData.isHDR;
            if (isHDR) {
              return this._skyColorHDR;
            } else {
              return this._skyColorLDR;
            }
          },
          set: function set(color) {
            var isHDR = legacyCC.director.root.pipeline.pipelineSceneData.isHDR;
            if (isHDR) {
              this._skyColorHDR.set(color);
            } else {
              this._skyColorLDR.set(color);
            }
          }
        }, {
          key: "skyIllum",
          get: function get() {
            var isHDR = legacyCC.director.root.pipeline.pipelineSceneData.isHDR;
            if (isHDR) {
              return this._skyIllumHDR;
            } else {
              return this._skyIllumLDR;
            }
          },
          set: function set(illum) {
            var isHDR = legacyCC.director.root.pipeline.pipelineSceneData.isHDR;
            if (isHDR) {
              this._skyIllumHDR = illum;
            } else {
              this._skyIllumLDR = illum;
            }
          }
        }, {
          key: "groundAlbedo",
          get: function get() {
            var isHDR = legacyCC.director.root.pipeline.pipelineSceneData.isHDR;
            if (isHDR) {
              return this._groundAlbedoHDR;
            } else {
              return this._groundAlbedoLDR;
            }
          },
          set: function set(color) {
            var isHDR = legacyCC.director.root.pipeline.pipelineSceneData.isHDR;
            if (isHDR) {
              this._groundAlbedoHDR.set(color);
            } else {
              this._groundAlbedoLDR.set(color);
            }
          }
        }]);
        return Ambient;
      }();
      Ambient.SUN_ILLUM = 65000.0;
      Ambient.SKY_ILLUM = 20000.0;
      legacyCC.Ambient = Ambient;

      var PassInstance = function (_Pass) {
        _inheritsLoose(PassInstance, _Pass);
        function PassInstance(parent, owner) {
          var _this;
          _this = _Pass.call(this, parent.root) || this;
          _this._parent = void 0;
          _this._owner = void 0;
          _this._dontNotify = false;
          _this._parent = parent;
          _this._owner = owner;
          _this._doInit(_this._parent, true);
          for (var i = 0; i < _this._shaderInfo.blocks.length; i++) {
            var u = _this._shaderInfo.blocks[i];
            var block = _this._blocks[u.binding];
            var parentBlock = _this._parent.blocks[u.binding];
            block.set(parentBlock);
          }
          _this._rootBufferDirty = true;
          var paren = _this._parent;
          for (var _i = 0; _i < _this._shaderInfo.samplerTextures.length; _i++) {
            var _u = _this._shaderInfo.samplerTextures[_i];
            for (var j = 0; j < _u.count; j++) {
              var sampler = paren._descriptorSet.getSampler(_u.binding, j);
              var texture = paren._descriptorSet.getTexture(_u.binding, j);
              _this._descriptorSet.bindSampler(_u.binding, sampler, j);
              _this._descriptorSet.bindTexture(_u.binding, texture, j);
            }
          }
          _Pass.prototype.tryCompile.call(_assertThisInitialized(_this));
          return _this;
        }
        var _proto = PassInstance.prototype;
        _proto.overridePipelineStates = function overridePipelineStates(original, overrides) {
          this._bs.reset();
          this._rs.reset();
          this._dss.reset();
          Pass.fillPipelineInfo(this, original);
          Pass.fillPipelineInfo(this, overrides);
          this._onStateChange();
        };
        _proto.tryCompile = function tryCompile(defineOverrides) {
          if (defineOverrides) {
            if (!overrideMacros(this._defines, defineOverrides)) {
              return false;
            }
          }
          var res = _Pass.prototype.tryCompile.call(this);
          this._onStateChange();
          return res;
        };
        _proto.beginChangeStatesSilently = function beginChangeStatesSilently() {
          this._dontNotify = true;
        };
        _proto.endChangeStatesSilently = function endChangeStatesSilently() {
          this._dontNotify = false;
        };
        _proto._syncBatchingScheme = function _syncBatchingScheme() {
          this._defines.USE_INSTANCING = false;
          this._batchingScheme = BatchingSchemes.NONE;
        };
        _proto._onStateChange = function _onStateChange() {
          this._hash = Pass.getPassHash(this);
          this._owner.onPassStateChange(this._dontNotify);
        };
        _createClass(PassInstance, [{
          key: "parent",
          get: function get() {
            return this._parent;
          }
        }]);
        return PassInstance;
      }(Pass);

      var MaterialInstance = function (_Material) {
        _inheritsLoose(MaterialInstance, _Material);
        function MaterialInstance(info) {
          var _this;
          _this = _Material.call(this) || this;
          _this._passes = [];
          _this._parent = void 0;
          _this._owner = void 0;
          _this._subModelIdx = 0;
          _this._parent = info.parent;
          _this._owner = info.owner || null;
          _this._subModelIdx = info.subModelIdx || 0;
          _this.copy(_this._parent);
          return _this;
        }
        var _proto = MaterialInstance.prototype;
        _proto.recompileShaders = function recompileShaders(overrides, passIdx) {
          if (!this._passes || !this.effectAsset) {
            return;
          }
          if (passIdx === undefined) {
            for (var _iterator = _createForOfIteratorHelperLoose(this._passes), _step; !(_step = _iterator()).done;) {
              var pass = _step.value;
              pass.tryCompile(overrides);
            }
          } else {
            this._passes[passIdx].tryCompile(overrides);
          }
        };
        _proto.overridePipelineStates = function overridePipelineStates(overrides, passIdx) {
          if (!this._passes || !this.effectAsset) {
            return;
          }
          var passInfos = this.effectAsset.techniques[this.technique].passes;
          if (passIdx === undefined) {
            for (var i = 0; i < this._passes.length; i++) {
              var pass = this._passes[i];
              var state = this._states[i] || (this._states[i] = {});
              for (var key in overrides) {
                state[key] = overrides[key];
              }
              pass.overridePipelineStates(passInfos[pass.passIndex], state);
            }
          } else {
            var _state = this._states[passIdx] || (this._states[passIdx] = {});
            for (var _key in overrides) {
              _state[_key] = overrides[_key];
            }
            this._passes[passIdx].overridePipelineStates(passInfos[passIdx], _state);
          }
        };
        _proto.destroy = function destroy() {
          this._doDestroy();
          return true;
        };
        _proto.onPassStateChange = function onPassStateChange(dontNotify) {
          this._hash = Material.getHash(this);
          if (!dontNotify && this._owner) {
            this._owner._onRebuildPSO(this._subModelIdx, this);
          }
        };
        _proto._createPasses = function _createPasses() {
          var passes = [];
          var parentPasses = this._parent.passes;
          if (!parentPasses) {
            return passes;
          }
          for (var k = 0; k < parentPasses.length; ++k) {
            passes.push(new PassInstance(parentPasses[k], this));
          }
          return passes;
        };
        _createClass(MaterialInstance, [{
          key: "parent",
          get: function get() {
            return this._parent;
          }
        }, {
          key: "owner",
          get: function get() {
            return this._owner;
          }
        }]);
        return MaterialInstance;
      }(Material);

      var skybox_mesh = null;
      var skybox_material = null;
      var EnvironmentLightingType = Enum({
        HEMISPHERE_DIFFUSE: 0,
        AUTOGEN_HEMISPHERE_DIFFUSE_WITH_REFLECTION: 1,
        DIFFUSEMAP_WITH_REFLECTION: 2
      });
      var Skybox = function () {
        function Skybox() {
          this._envmapLDR = null;
          this._envmapHDR = null;
          this._diffuseMapLDR = null;
          this._diffuseMapHDR = null;
          this._globalDSManager = null;
          this._model = null;
          this._default = null;
          this._enabled = false;
          this._useIBL = false;
          this._useHDR = true;
          this._useDiffuseMap = false;
          this._editableMaterial = null;
          this._activated = false;
          this._reflectionHDR = null;
          this._reflectionLDR = null;
          this._rotationAngle = 0;
        }
        var _proto = Skybox.prototype;
        _proto.initialize = function initialize(skyboxInfo) {
          this._activated = false;
          this._enabled = skyboxInfo.enabled;
          this._useIBL = skyboxInfo.useIBL;
          this._useDiffuseMap = skyboxInfo.applyDiffuseMap;
          this._useHDR = skyboxInfo.useHDR;
        };
        _proto.setEnvMaps = function setEnvMaps(envmapHDR, envmapLDR) {
          this._envmapHDR = envmapHDR;
          this._envmapLDR = envmapLDR;
          this._updateGlobalBinding();
          this._updatePipeline();
        };
        _proto.setDiffuseMaps = function setDiffuseMaps(diffuseMapHDR, diffuseMapLDR) {
          this._diffuseMapHDR = diffuseMapHDR;
          this._diffuseMapLDR = diffuseMapLDR;
          this._updateGlobalBinding();
          this._updatePipeline();
        };
        _proto.setSkyboxMaterial = function setSkyboxMaterial(skyboxMat) {
          if (skyboxMat) {
            this._editableMaterial = new MaterialInstance({
              parent: skyboxMat
            });
            this._editableMaterial.recompileShaders({
              USE_RGBE_CUBEMAP: this.isRGBE
            });
          } else {
            this._editableMaterial = null;
          }
          this._updatePipeline();
        };
        _proto.setReflectionMaps = function setReflectionMaps(reflectionHDR, reflectionLDR) {
          this._reflectionHDR = reflectionHDR;
          this._reflectionLDR = reflectionLDR;
          this._updateGlobalBinding();
          this._updatePipeline();
        };
        _proto.setRotationAngle = function setRotationAngle(angle) {
          this._rotationAngle = angle;
        };
        _proto.getRotationAngle = function getRotationAngle() {
          return this._rotationAngle;
        };
        _proto.updateMaterialRenderInfo = function updateMaterialRenderInfo() {
          this._updateGlobalBinding();
          this._updatePipeline();
        };
        _proto.activate = function activate() {
          var pipeline = legacyCC.director.root.pipeline;
          this._globalDSManager = pipeline.globalDSManager;
          this._default = builtinResMgr.get('default-cube-texture');
          if (!this._model) {
            this._model = legacyCC.director.root.createModel(legacyCC.renderer.scene.Model);
          }
          var isRGBE = this._default.isRGBE;
          this._default.isUsingOfflineMipmaps();
          if (this.envmap) {
            isRGBE = this.envmap.isRGBE;
            this.envmap.isUsingOfflineMipmaps();
          }
          if (!skybox_material) {
            var mat = new Material();
            mat.initialize({
              effectName: 'pipeline/skybox',
              defines: {
                USE_RGBE_CUBEMAP: isRGBE
              }
            });
            skybox_material = new MaterialInstance({
              parent: mat
            });
          }
          if (this.enabled) {
            if (!skybox_mesh) {
              skybox_mesh = legacyCC.utils.createMesh(legacyCC.primitives.box({
                width: 2,
                height: 2,
                length: 2
              }));
            }
            if (this._editableMaterial) {
              this._model.initSubModel(0, skybox_mesh.renderingSubMeshes[0], this._editableMaterial);
            } else {
              this._model.initSubModel(0, skybox_mesh.renderingSubMeshes[0], skybox_material);
            }
          }
          if (!this.envmap) {
            this.envmap = this._default;
          }
          if (!this.diffuseMap) {
            this.diffuseMap = this._default;
          }
          this._updateGlobalBinding();
          this._updatePipeline();
          this._activated = true;
        };
        _proto._updatePipeline = function _updatePipeline() {
          var root = legacyCC.director.root;
          var pipeline = root.pipeline;
          var useIBLValue = this.useIBL ? this.isRGBE ? 2 : 1 : 0;
          var useDiffuseMapValue = this.useIBL && this.useDiffuseMap && this.diffuseMap && this.diffuseMap !== this._default ? this.isRGBE ? 2 : 1 : 0;
          var useHDRValue = this.useHDR;
          var useConvMapValue = this.useConvolutionMap;
          if (pipeline.macros.CC_USE_IBL !== useIBLValue || pipeline.macros.CC_USE_DIFFUSEMAP !== useDiffuseMapValue || pipeline.macros.CC_USE_HDR !== useHDRValue || pipeline.macros.CC_IBL_CONVOLUTED !== useConvMapValue) {
            pipeline.macros.CC_USE_IBL = useIBLValue;
            pipeline.macros.CC_USE_DIFFUSEMAP = useDiffuseMapValue;
            pipeline.macros.CC_USE_HDR = useHDRValue;
            pipeline.macros.CC_IBL_CONVOLUTED = useConvMapValue;
            if (this._activated) {
              root.onGlobalPipelineStateChanged();
            }
          }
          if (this.enabled) {
            var envmap = this.envmap ? this.envmap : this._default;
            var skyboxMat = this._editableMaterial ? this._editableMaterial : skybox_material;
            if (skyboxMat) {
              skyboxMat.setProperty('environmentMap', envmap);
              skyboxMat.recompileShaders({
                USE_RGBE_CUBEMAP: this.isRGBE
              });
            }
            if (this._model) {
              this._model.setSubModelMaterial(0, skyboxMat);
              this._updateSubModes();
            }
          }
        };
        _proto._updateGlobalBinding = function _updateGlobalBinding() {
          if (this._globalDSManager) {
            var device = deviceManager.gfxDevice;
            if (this.reflectionMap) {
              var texture = this.reflectionMap.getGFXTexture();
              var sampler = device.getSampler(this.reflectionMap.getSamplerInfo());
              this._globalDSManager.bindSampler(UNIFORM_ENVIRONMENT_BINDING, sampler);
              this._globalDSManager.bindTexture(UNIFORM_ENVIRONMENT_BINDING, texture);
            } else {
              var envmap = this.envmap ? this.envmap : this._default;
              if (envmap) {
                var _texture = envmap.getGFXTexture();
                var _sampler = device.getSampler(envmap.getSamplerInfo());
                this._globalDSManager.bindSampler(UNIFORM_ENVIRONMENT_BINDING, _sampler);
                this._globalDSManager.bindTexture(UNIFORM_ENVIRONMENT_BINDING, _texture);
              }
            }
            var diffuseMap = this.diffuseMap ? this.diffuseMap : this._default;
            if (diffuseMap) {
              var _texture2 = diffuseMap.getGFXTexture();
              var _sampler2 = device.getSampler(diffuseMap.getSamplerInfo());
              this._globalDSManager.bindSampler(UNIFORM_DIFFUSEMAP_BINDING, _sampler2);
              this._globalDSManager.bindTexture(UNIFORM_DIFFUSEMAP_BINDING, _texture2);
            }
            this._globalDSManager.update();
          }
        };
        _proto._updateSubModes = function _updateSubModes() {
          if (this._model) {
            var subModels = this._model.subModels;
            for (var i = 0; i < subModels.length; i++) {
              subModels[i].update();
            }
          }
        };
        _createClass(Skybox, [{
          key: "model",
          get: function get() {
            return this._model;
          }
        }, {
          key: "enabled",
          get: function get() {
            return this._enabled;
          },
          set: function set(val) {
            this._enabled = val;
            if (val) this.activate();else this._updatePipeline();
          }
        }, {
          key: "useHDR",
          get: function get() {
            return this._useHDR;
          },
          set: function set(val) {
            this._useHDR = val;
            this.setEnvMaps(this._envmapHDR, this._envmapLDR);
          }
        }, {
          key: "useIBL",
          get: function get() {
            return this._useIBL;
          },
          set: function set(val) {
            this._useIBL = val;
            this._updatePipeline();
          }
        }, {
          key: "useDiffuseMap",
          get: function get() {
            return this._useDiffuseMap;
          },
          set: function set(val) {
            this._useDiffuseMap = val;
            this._updatePipeline();
          }
        }, {
          key: "isRGBE",
          get: function get() {
            if (this.envmap) {
              return this.envmap.isRGBE;
            } else {
              return false;
            }
          }
        }, {
          key: "useConvolutionMap",
          get: function get() {
            if (this.reflectionMap) {
              return this.reflectionMap.isUsingOfflineMipmaps();
            }
            if (this.envmap) {
              return this.envmap.isUsingOfflineMipmaps();
            }
            return false;
          }
        }, {
          key: "envmap",
          get: function get() {
            var isHDR = legacyCC.director.root.pipeline.pipelineSceneData.isHDR;
            if (isHDR) {
              return this._envmapHDR;
            } else {
              return this._envmapLDR;
            }
          },
          set: function set(val) {
            var root = legacyCC.director.root;
            var isHDR = root.pipeline.pipelineSceneData.isHDR;
            if (isHDR) {
              this.setEnvMaps(val, this._envmapLDR);
            } else {
              this.setEnvMaps(this._envmapHDR, val);
            }
          }
        }, {
          key: "diffuseMap",
          get: function get() {
            var isHDR = legacyCC.director.root.pipeline.pipelineSceneData.isHDR;
            if (isHDR) {
              return this._diffuseMapHDR;
            } else {
              return this._diffuseMapLDR;
            }
          },
          set: function set(val) {
            var isHDR = legacyCC.director.root.pipeline.pipelineSceneData.isHDR;
            if (isHDR) {
              this.setDiffuseMaps(val, this._diffuseMapLDR);
            } else {
              this.setDiffuseMaps(this._diffuseMapHDR, val);
            }
          }
        }, {
          key: "reflectionMap",
          get: function get() {
            var isHDR = legacyCC.director.root.pipeline.pipelineSceneData.isHDR;
            if (isHDR) {
              return this._reflectionHDR;
            } else {
              return this._reflectionLDR;
            }
          }
        }, {
          key: "editableMaterial",
          get: function get() {
            return this._editableMaterial;
          }
        }]);
        return Skybox;
      }();
      legacyCC.Skybox = Skybox;

      var _v4$1 = new Vec4();
      var FogType = Enum({
        LINEAR: 0,
        EXP: 1,
        EXP_SQUARED: 2,
        LAYERED: 3
      });
      var FOG_TYPE_NONE = FogType.LAYERED + 1;
      var Fog = function () {
        function Fog() {
          this._fogColor = new Color$1('#C8C8C8');
          this._colorArray = new Vec4(0.2, 0.2, 0.2, 1.0);
          this._enabled = false;
          this._accurate = false;
          this._type = 0;
          this._fogDensity = 0.3;
          this._fogStart = 0.5;
          this._fogEnd = 300;
          this._fogAtten = 5;
          this._fogTop = 1.5;
          this._fogRange = 1.2;
          this._activated = false;
        }
        var _proto = Fog.prototype;
        _proto.initialize = function initialize(fogInfo) {
          this._activated = false;
          this.fogColor = fogInfo.fogColor;
          this._enabled = fogInfo.enabled;
          this._type = this.enabled ? fogInfo.type : FOG_TYPE_NONE;
          this._accurate = fogInfo.accurate;
          this.fogDensity = fogInfo.fogDensity;
          this.fogStart = fogInfo.fogStart;
          this.fogEnd = fogInfo.fogEnd;
          this.fogAtten = fogInfo.fogAtten;
          this.fogTop = fogInfo.fogTop;
          this.fogRange = fogInfo.fogRange;
        };
        _proto.activate = function activate() {
          this._updatePipeline();
          this._activated = true;
        };
        _proto._updatePipeline = function _updatePipeline() {
          var root = legacyCC.director.root;
          var value = this.enabled ? this.type : FOG_TYPE_NONE;
          var accurateValue = this.accurate ? 1 : 0;
          var pipeline = root.pipeline;
          if (pipeline.macros.CC_USE_FOG === value && pipeline.macros.CC_USE_ACCURATE_FOG === accurateValue) {
            return;
          }
          pipeline.macros.CC_USE_FOG = value;
          pipeline.macros.CC_USE_ACCURATE_FOG = accurateValue;
          if (this._activated) {
            root.onGlobalPipelineStateChanged();
          }
        };
        _createClass(Fog, [{
          key: "enabled",
          get: function get() {
            return this._enabled;
          },
          set: function set(val) {
            this._enabled = val;
            if (!val) {
              this._type = FOG_TYPE_NONE;
              this._updatePipeline();
            } else {
              this.activate();
            }
          }
        }, {
          key: "accurate",
          get: function get() {
            return this._accurate;
          },
          set: function set(val) {
            this._accurate = val;
            this._updatePipeline();
          }
        }, {
          key: "fogColor",
          get: function get() {
            return this._fogColor;
          },
          set: function set(val) {
            this._fogColor.set(val);
            _v4$1.set(val.x, val.y, val.z, val.w);
            SRGBToLinear(this._colorArray, _v4$1);
          }
        }, {
          key: "type",
          get: function get() {
            return this._type;
          },
          set: function set(val) {
            this._type = this.enabled ? val : FOG_TYPE_NONE;
            if (this.enabled) this._updatePipeline();
          }
        }, {
          key: "fogDensity",
          get: function get() {
            return this._fogDensity;
          },
          set: function set(val) {
            this._fogDensity = val;
          }
        }, {
          key: "fogStart",
          get: function get() {
            return this._fogStart;
          },
          set: function set(val) {
            this._fogStart = val;
          }
        }, {
          key: "fogEnd",
          get: function get() {
            return this._fogEnd;
          },
          set: function set(val) {
            this._fogEnd = val;
          }
        }, {
          key: "fogAtten",
          get: function get() {
            return this._fogAtten;
          },
          set: function set(val) {
            this._fogAtten = val;
          }
        }, {
          key: "fogTop",
          get: function get() {
            return this._fogTop;
          },
          set: function set(val) {
            this._fogTop = val;
          }
        }, {
          key: "fogRange",
          get: function get() {
            return this._fogRange;
          },
          set: function set(val) {
            this._fogRange = val;
          }
        }, {
          key: "colorArray",
          get: function get() {
            return this._colorArray;
          }
        }]);
        return Fog;
      }();
      legacyCC.Fog = Fog;

      var ToneMappingType = Enum({
        DEFAULT: 0,
        LINEAR: 1
      });
      var PostSettings = function () {
        function PostSettings() {
          this._toneMappingType = ToneMappingType.DEFAULT;
          this._activated = false;
        }
        var _proto = PostSettings.prototype;
        _proto.initialize = function initialize(postSettingsInfo) {
          this._toneMappingType = postSettingsInfo.toneMappingType;
        };
        _proto.activate = function activate() {
          this._updatePipeline();
          this._activated = true;
        };
        _proto._updatePipeline = function _updatePipeline() {
          var root = legacyCC.director.root;
          var pipeline = root.pipeline;
          pipeline.macros.CC_TONE_MAPPING_TYPE = this._toneMappingType;
          if (this._activated) {
            root.onGlobalPipelineStateChanged();
          }
        };
        _createClass(PostSettings, [{
          key: "toneMappingType",
          get: function get() {
            return this._toneMappingType;
          },
          set: function set(val) {
            this._toneMappingType = val;
            this._updatePipeline();
          }
        }]);
        return PostSettings;
      }();

      var _dec$2N, _dec2$21, _dec3$1o, _dec4$_, _dec5$P, _class$2J, _class2$2u, _initializer$2e, _initializer2$1K, _initializer3$19, _initializer4$U, _initializer5$F, _initializer6$w, _dec6$z, _dec7$s, _dec8$k, _dec9$h, _dec10$c, _dec11$a, _dec12$a, _dec13$8, _dec14$7, _dec15$7, _dec16$6, _dec17$6, _dec18$5, _dec19$5, _dec20$5, _class4$v, _class5$w, _initializer7$q, _initializer8$p, _initializer9$n, _initializer10$l, _initializer11$i, _initializer12$g, _initializer13$f, _initializer14$d, _initializer15$a, _initializer16$a, _initializer17$9, _dec21$5, _dec22$5, _dec23$5, _dec24$5, _dec25$5, _dec26$5, _dec27$5, _dec28$5, _class7$b, _class8$a, _initializer18$8, _initializer19$7, _initializer20$6, _initializer21$6, _initializer22$5, _initializer23$4, _initializer24$4, _initializer25$4, _initializer26$4, _initializer27$3, _class9, _dec29$4, _dec30$3, _dec31$3, _dec32$2, _dec33$2, _class10$6, _class11$6, _initializer28$3, _initializer29$3, _initializer30$3, _initializer31$3, _initializer32$2, _initializer33$2, _initializer34$2, _dec34$2, _dec35$2, _class13$5, _class14$5, _initializer35$2, _initializer36$1, _initializer37$1, _initializer38$1, _dec36$2, _dec37$2, _dec38$2, _class16$2, _class17$3, _initializer39$1, _initializer40$1, _initializer41$1, _dec39$2, _dec40$1, _class19$2, _class20$4, _initializer42$1, _dec41$1, _dec42$1, _dec43$1, _dec44$1, _dec45$1, _dec46$1, _class22$2, _class23$3, _initializer43$1, _initializer44$1, _initializer45$1, _initializer46$1, _initializer47, _initializer48, _initializer49, _initializer50, _initializer51, _dec47$1, _dec48$1, _class25, _class26$1, _initializer52, _initializer53, _initializer54, _initializer55, _initializer56, _initializer57, _initializer58, _initializer59, _initializer60, _initializer61;
      var _up = new Vec3(0, 1, 0);
      var _v3$3 = new Vec3();
      var _v4 = new Vec4();
      var _col = new Color$1();
      var _qt$1 = new Quat();
      var normalizeHDRColor = function normalizeHDRColor(color) {
        var intensity = 1.0 / Math.max(Math.max(Math.max(color.x, color.y), color.z), 0.0001);
        if (intensity < 1.0) {
          color.x *= intensity;
          color.y *= intensity;
          color.z *= intensity;
        }
      };
      var AmbientInfo = exports('dG', (_dec$2N = ccclass$n('cc.AmbientInfo'), _dec2$21 = type$7(CCFloat), _dec3$1o = formerlySerializedAs$4('_skyColor'), _dec4$_ = formerlySerializedAs$4('_skyIllum'), _dec5$P = formerlySerializedAs$4('_groundAlbedo'), _dec$2N(_class$2J = (_class2$2u = function () {
        function AmbientInfo() {
          this._skyColorHDR = _initializer$2e && _initializer$2e();
          this._skyIllumHDR = _initializer2$1K && _initializer2$1K();
          this._groundAlbedoHDR = _initializer3$19 && _initializer3$19();
          this._skyColorLDR = _initializer4$U && _initializer4$U();
          this._skyIllumLDR = _initializer5$F && _initializer5$F();
          this._groundAlbedoLDR = _initializer6$w && _initializer6$w();
          this._resource = null;
        }
        var _proto = AmbientInfo.prototype;
        _proto.activate = function activate(resource) {
          this._resource = resource;
          this._resource.initialize(this);
        };
        _createClass(AmbientInfo, [{
          key: "skyColorHDR",
          get: function get() {
            return this._skyColorHDR;
          }
        }, {
          key: "groundAlbedoHDR",
          get: function get() {
            return this._groundAlbedoHDR;
          }
        }, {
          key: "skyIllumHDR",
          get: function get() {
            return this._skyIllumHDR;
          }
        }, {
          key: "skyColorLDR",
          get: function get() {
            return this._skyColorLDR;
          }
        }, {
          key: "groundAlbedoLDR",
          get: function get() {
            return this._groundAlbedoLDR;
          }
        }, {
          key: "skyIllumLDR",
          get: function get() {
            return this._skyIllumLDR;
          }
        }, {
          key: "skyLightingColor",
          get: function get() {
            var isHDR = legacyCC.director.root.pipeline.pipelineSceneData.isHDR;
            _v4.set(isHDR ? this._skyColorHDR : this._skyColorLDR);
            normalizeHDRColor(_v4);
            return _col.set(_v4.x * 255, _v4.y * 255, _v4.z * 255, 255);
          },
          set: function set(val) {
            _v4.set(val.x, val.y, val.z, val.w);
            if (legacyCC.director.root.pipeline.pipelineSceneData.isHDR) {
              this._skyColorHDR.set(_v4);
            } else {
              this._skyColorLDR.set(_v4);
            }
            if (this._resource) {
              this._resource.skyColor.set(_v4);
            }
          }
        }, {
          key: "skyColor",
          set: function set(val) {
            if (legacyCC.director.root.pipeline.pipelineSceneData.isHDR) {
              this._skyColorHDR.set(val);
            } else {
              this._skyColorLDR.set(val);
            }
            if (this._resource) {
              this._resource.skyColor.set(val);
            }
          }
        }, {
          key: "skyIllum",
          get: function get() {
            if (legacyCC.director.root.pipeline.pipelineSceneData.isHDR) {
              return this._skyIllumHDR;
            } else {
              return this._skyIllumLDR;
            }
          },
          set: function set(val) {
            if (legacyCC.director.root.pipeline.pipelineSceneData.isHDR) {
              this._skyIllumHDR = val;
            } else {
              this._skyIllumLDR = val;
            }
            if (this._resource) {
              this._resource.skyIllum = val;
            }
          }
        }, {
          key: "groundLightingColor",
          get: function get() {
            var isHDR = legacyCC.director.root.pipeline.pipelineSceneData.isHDR;
            _v4.set(isHDR ? this._groundAlbedoHDR : this._groundAlbedoLDR);
            normalizeHDRColor(_v4);
            return _col.set(_v4.x * 255, _v4.y * 255, _v4.z * 255, 255);
          },
          set: function set(val) {
            _v4.set(val.x, val.y, val.z, val.w);
            if (legacyCC.director.root.pipeline.pipelineSceneData.isHDR) {
              this._groundAlbedoHDR.set(_v4);
            } else {
              this._groundAlbedoLDR.set(_v4);
            }
            if (this._resource) {
              this._resource.groundAlbedo.set(_v4);
            }
          }
        }, {
          key: "groundAlbedo",
          set: function set(val) {
            if (legacyCC.director.root.pipeline.pipelineSceneData.isHDR) {
              this._groundAlbedoHDR.set(val);
            } else {
              this._groundAlbedoLDR.set(val);
            }
            if (this._resource) {
              this._resource.groundAlbedo.set(val);
            }
          }
        }]);
        return AmbientInfo;
      }(), (_applyDecoratedDescriptor(_class2$2u.prototype, "skyIllum", [_dec2$21], Object.getOwnPropertyDescriptor(_class2$2u.prototype, "skyIllum"), _class2$2u.prototype), _initializer$2e = applyDecoratedInitializer(_class2$2u.prototype, "_skyColorHDR", [serializable$j, _dec3$1o], function () {
        return new Vec4(0.2, 0.5, 0.8, 1.0);
      }), _initializer2$1K = applyDecoratedInitializer(_class2$2u.prototype, "_skyIllumHDR", [serializable$j, _dec4$_], function () {
        return Ambient.SKY_ILLUM;
      }), _initializer3$19 = applyDecoratedInitializer(_class2$2u.prototype, "_groundAlbedoHDR", [serializable$j, _dec5$P], function () {
        return new Vec4(0.2, 0.2, 0.2, 1.0);
      }), _initializer4$U = applyDecoratedInitializer(_class2$2u.prototype, "_skyColorLDR", [serializable$j], function () {
        return new Vec4(0.2, 0.5, 0.8, 1.0);
      }), _initializer5$F = applyDecoratedInitializer(_class2$2u.prototype, "_skyIllumLDR", [serializable$j], function () {
        return Ambient.SKY_ILLUM;
      }), _initializer6$w = applyDecoratedInitializer(_class2$2u.prototype, "_groundAlbedoLDR", [serializable$j], function () {
        return new Vec4(0.2, 0.2, 0.2, 1.0);
      })), _class2$2u)) || _class$2J));
      legacyCC.AmbientInfo = AmbientInfo;
      var SkyboxInfo = exports('dH', (_dec6$z = ccclass$n('cc.SkyboxInfo'), _dec7$s = type$7(EnvironmentLightingType), _dec8$k = type$7(TextureCube), _dec9$h = type$7(CCFloat), _dec10$c = type$7(TextureCube), _dec11$a = type$7(TextureCube), _dec12$a = type$7(Material), _dec13$8 = type$7(TextureCube), _dec14$7 = formerlySerializedAs$4('_envmap'), _dec15$7 = type$7(TextureCube), _dec16$6 = type$7(TextureCube), _dec17$6 = type$7(TextureCube), _dec18$5 = type$7(Material), _dec19$5 = type$7(TextureCube), _dec20$5 = type$7(TextureCube), _dec6$z(_class4$v = (_class5$w = function () {
        function SkyboxInfo() {
          this._envLightingType = _initializer7$q && _initializer7$q();
          this._envmapHDR = _initializer8$p && _initializer8$p();
          this._envmapLDR = _initializer9$n && _initializer9$n();
          this._diffuseMapHDR = _initializer10$l && _initializer10$l();
          this._diffuseMapLDR = _initializer11$i && _initializer11$i();
          this._enabled = _initializer12$g && _initializer12$g();
          this._useHDR = _initializer13$f && _initializer13$f();
          this._editableMaterial = _initializer14$d && _initializer14$d();
          this._reflectionHDR = _initializer15$a && _initializer15$a();
          this._reflectionLDR = _initializer16$a && _initializer16$a();
          this._rotationAngle = _initializer17$9 && _initializer17$9();
          this._resource = null;
        }
        var _proto2 = SkyboxInfo.prototype;
        _proto2.activate = function activate(resource) {
          this.envLightingType = this._envLightingType;
          this._resource = resource;
          this._resource.initialize(this);
          this._resource.setEnvMaps(this._envmapHDR, this._envmapLDR);
          this._resource.setDiffuseMaps(this._diffuseMapHDR, this._diffuseMapLDR);
          this._resource.setSkyboxMaterial(this._editableMaterial);
          this._resource.setReflectionMaps(this._reflectionHDR, this._reflectionLDR);
          this._resource.setRotationAngle(this._rotationAngle);
          this._resource.activate();
        };
        _proto2.updateEnvMap = function updateEnvMap(val) {
          if (!val) {
            this.applyDiffuseMap = false;
            this.useIBL = false;
            this.envLightingType = EnvironmentLightingType.HEMISPHERE_DIFFUSE;
            warnID(15001);
          }
          if (this._resource) {
            this._resource.setEnvMaps(this._envmapHDR, this._envmapLDR);
            this._resource.setDiffuseMaps(this._diffuseMapHDR, this._diffuseMapLDR);
            this._resource.setReflectionMaps(this._reflectionHDR, this._reflectionLDR);
            this._resource.useDiffuseMap = this.applyDiffuseMap;
            this._resource.envmap = val;
          }
        };
        _proto2.setMaterialProperty = function setMaterialProperty(name, val, passIdx) {
          if (!this._resource) return;
          if (this._resource.enabled && this._resource.editableMaterial) {
            this._resource.editableMaterial.setProperty(name, val, passIdx);
            this._resource.editableMaterial.passes.forEach(function (pass) {
              pass.update();
            });
          }
        };
        _createClass(SkyboxInfo, [{
          key: "applyDiffuseMap",
          get: function get() {
            if (EnvironmentLightingType.DIFFUSEMAP_WITH_REFLECTION === this._envLightingType) {
              return true;
            }
            return false;
          },
          set: function set(val) {
            if (this._resource) {
              this._resource.useDiffuseMap = val;
            }
          }
        }, {
          key: "enabled",
          get: function get() {
            return this._enabled;
          },
          set: function set(val) {
            if (this._enabled === val) return;
            this._enabled = val;
            if (this._resource) {
              this._resource.enabled = this._enabled;
            }
          }
        }, {
          key: "envLightingType",
          get: function get() {
            return this._envLightingType;
          },
          set: function set(val) {
            if (!this.envmap && EnvironmentLightingType.HEMISPHERE_DIFFUSE !== val) {
              this.useIBL = false;
              this.applyDiffuseMap = false;
              this._envLightingType = EnvironmentLightingType.HEMISPHERE_DIFFUSE;
              warnID(15001);
            } else {
              if (EnvironmentLightingType.HEMISPHERE_DIFFUSE === val) {
                this.useIBL = false;
                this.applyDiffuseMap = false;
              } else if (EnvironmentLightingType.AUTOGEN_HEMISPHERE_DIFFUSE_WITH_REFLECTION === val) {
                this.useIBL = true;
                this.applyDiffuseMap = false;
              } else if (EnvironmentLightingType.DIFFUSEMAP_WITH_REFLECTION === val) {
                this.useIBL = true;
                this.applyDiffuseMap = true;
              }
              this._envLightingType = val;
            }
          }
        }, {
          key: "useIBL",
          get: function get() {
            if (EnvironmentLightingType.HEMISPHERE_DIFFUSE !== this._envLightingType) {
              return true;
            }
            return false;
          },
          set: function set(val) {
            if (this._resource) {
              this._resource.useIBL = val;
            }
          }
        }, {
          key: "useHDR",
          get: function get() {
            legacyCC.director.root.pipeline.pipelineSceneData.isHDR = this._useHDR;
            return this._useHDR;
          },
          set: function set(val) {
            legacyCC.director.root.pipeline.pipelineSceneData.isHDR = val;
            this._useHDR = val;
            if (this._resource) {
              if (this.envLightingType === EnvironmentLightingType.DIFFUSEMAP_WITH_REFLECTION) {
                if (this.diffuseMap === null) {
                  this.envLightingType = EnvironmentLightingType.AUTOGEN_HEMISPHERE_DIFFUSE_WITH_REFLECTION;
                  warnID(15000);
                } else if (this.diffuseMap.isDefault) {
                  warnID(15002);
                }
              }
            }
            if (this._resource) {
              this._resource.useHDR = this._useHDR;
              this._resource.updateMaterialRenderInfo();
            }
          }
        }, {
          key: "envmap",
          get: function get() {
            var isHDR = legacyCC.director.root.pipeline.pipelineSceneData.isHDR;
            if (isHDR) {
              return this._envmapHDR;
            } else {
              return this._envmapLDR;
            }
          },
          set: function set(val) {
            var isHDR = legacyCC.director.root.pipeline.pipelineSceneData.isHDR;
            if (isHDR) {
              this._envmapHDR = val;
              this._reflectionHDR = null;
            } else {
              this._envmapLDR = val;
              this._reflectionLDR = null;
            }
            if (!val) {
              if (isHDR) {
                this._diffuseMapHDR = null;
              } else {
                this._diffuseMapLDR = null;
              }
              this.applyDiffuseMap = false;
              this.useIBL = false;
              this.envLightingType = EnvironmentLightingType.HEMISPHERE_DIFFUSE;
              warnID(15001);
            }
            if (this._resource) {
              this._resource.setEnvMaps(this._envmapHDR, this._envmapLDR);
              this._resource.setDiffuseMaps(this._diffuseMapHDR, this._diffuseMapLDR);
              this._resource.setReflectionMaps(this._reflectionHDR, this._reflectionLDR);
              this._resource.useDiffuseMap = this.applyDiffuseMap;
              this._resource.envmap = val;
            }
          }
        }, {
          key: "rotationAngle",
          get: function get() {
            return this._rotationAngle;
          },
          set: function set(val) {
            this._rotationAngle = val;
            if (this._resource) {
              this._resource.setRotationAngle(this._rotationAngle);
            }
          }
        }, {
          key: "diffuseMap",
          get: function get() {
            var isHDR = legacyCC.director.root.pipeline.pipelineSceneData.isHDR;
            if (isHDR) {
              return this._diffuseMapHDR;
            } else {
              return this._diffuseMapLDR;
            }
          },
          set: function set(val) {
            var isHDR = legacyCC.director.root.pipeline.pipelineSceneData.isHDR;
            if (isHDR) {
              this._diffuseMapHDR = val;
            } else {
              this._diffuseMapLDR = val;
            }
            if (this._resource) {
              this._resource.setDiffuseMaps(this._diffuseMapHDR, this._diffuseMapLDR);
            }
          }
        }, {
          key: "reflectionMap",
          get: function get() {
            var isHDR = legacyCC.director.root.pipeline.pipelineSceneData.isHDR;
            if (isHDR) {
              return this._reflectionHDR;
            } else {
              return this._reflectionLDR;
            }
          },
          set: function set(val) {
            var isHDR = legacyCC.director.root.pipeline.pipelineSceneData.isHDR;
            if (isHDR) {
              this._reflectionHDR = val;
            } else {
              this._reflectionLDR = val;
            }
            if (this._resource) {
              this._resource.setReflectionMaps(this._reflectionHDR, this._reflectionLDR);
            }
          }
        }, {
          key: "skyboxMaterial",
          get: function get() {
            return this._editableMaterial;
          },
          set: function set(val) {
            this._editableMaterial = val;
            if (this._resource) {
              this._resource.setSkyboxMaterial(this._editableMaterial);
            }
          }
        }]);
        return SkyboxInfo;
      }(), (_applyDecoratedDescriptor(_class5$w.prototype, "envLightingType", [_dec7$s], Object.getOwnPropertyDescriptor(_class5$w.prototype, "envLightingType"), _class5$w.prototype), _applyDecoratedDescriptor(_class5$w.prototype, "envmap", [_dec8$k], Object.getOwnPropertyDescriptor(_class5$w.prototype, "envmap"), _class5$w.prototype), _applyDecoratedDescriptor(_class5$w.prototype, "rotationAngle", [_dec9$h], Object.getOwnPropertyDescriptor(_class5$w.prototype, "rotationAngle"), _class5$w.prototype), _applyDecoratedDescriptor(_class5$w.prototype, "diffuseMap", [_dec10$c], Object.getOwnPropertyDescriptor(_class5$w.prototype, "diffuseMap"), _class5$w.prototype), _applyDecoratedDescriptor(_class5$w.prototype, "reflectionMap", [_dec11$a], Object.getOwnPropertyDescriptor(_class5$w.prototype, "reflectionMap"), _class5$w.prototype), _applyDecoratedDescriptor(_class5$w.prototype, "skyboxMaterial", [_dec12$a], Object.getOwnPropertyDescriptor(_class5$w.prototype, "skyboxMaterial"), _class5$w.prototype), _initializer7$q = applyDecoratedInitializer(_class5$w.prototype, "_envLightingType", [serializable$j], function () {
        return EnvironmentLightingType.HEMISPHERE_DIFFUSE;
      }), _initializer8$p = applyDecoratedInitializer(_class5$w.prototype, "_envmapHDR", [serializable$j, _dec13$8, _dec14$7], function () {
        return null;
      }), _initializer9$n = applyDecoratedInitializer(_class5$w.prototype, "_envmapLDR", [serializable$j, _dec15$7], function () {
        return null;
      }), _initializer10$l = applyDecoratedInitializer(_class5$w.prototype, "_diffuseMapHDR", [serializable$j, _dec16$6], function () {
        return null;
      }), _initializer11$i = applyDecoratedInitializer(_class5$w.prototype, "_diffuseMapLDR", [serializable$j, _dec17$6], function () {
        return null;
      }), _initializer12$g = applyDecoratedInitializer(_class5$w.prototype, "_enabled", [serializable$j], function () {
        return false;
      }), _initializer13$f = applyDecoratedInitializer(_class5$w.prototype, "_useHDR", [serializable$j], function () {
        return true;
      }), _initializer14$d = applyDecoratedInitializer(_class5$w.prototype, "_editableMaterial", [serializable$j, _dec18$5], function () {
        return null;
      }), _initializer15$a = applyDecoratedInitializer(_class5$w.prototype, "_reflectionHDR", [serializable$j, _dec19$5], function () {
        return null;
      }), _initializer16$a = applyDecoratedInitializer(_class5$w.prototype, "_reflectionLDR", [serializable$j, _dec20$5], function () {
        return null;
      }), _initializer17$9 = applyDecoratedInitializer(_class5$w.prototype, "_rotationAngle", [serializable$j], function () {
        return 0;
      })), _class5$w)) || _class4$v));
      legacyCC.SkyboxInfo = SkyboxInfo;
      var FogInfo = exports('dI', (_dec21$5 = ccclass$n('cc.FogInfo'), _dec22$5 = type$7(FogType), _dec23$5 = type$7(CCFloat), _dec24$5 = type$7(CCFloat), _dec25$5 = type$7(CCFloat), _dec26$5 = type$7(CCFloat), _dec27$5 = type$7(CCFloat), _dec28$5 = type$7(CCFloat), _dec21$5(_class7$b = (_class8$a = (_class9 = function () {
        function FogInfo() {
          this._type = _initializer18$8 && _initializer18$8();
          this._fogColor = _initializer19$7 && _initializer19$7();
          this._enabled = _initializer20$6 && _initializer20$6();
          this._fogDensity = _initializer21$6 && _initializer21$6();
          this._fogStart = _initializer22$5 && _initializer22$5();
          this._fogEnd = _initializer23$4 && _initializer23$4();
          this._fogAtten = _initializer24$4 && _initializer24$4();
          this._fogTop = _initializer25$4 && _initializer25$4();
          this._fogRange = _initializer26$4 && _initializer26$4();
          this._accurate = _initializer27$3 && _initializer27$3();
          this._resource = null;
        }
        var _proto3 = FogInfo.prototype;
        _proto3.activate = function activate(resource) {
          this._resource = resource;
          this._resource.initialize(this);
          this._resource.activate();
        };
        _createClass(FogInfo, [{
          key: "enabled",
          get: function get() {
            return this._enabled;
          },
          set: function set(val) {
            if (this._enabled === val) return;
            this._enabled = val;
            if (this._resource) {
              this._resource.enabled = val;
              if (val) {
                this._resource.type = this._type;
              }
            }
          }
        }, {
          key: "accurate",
          get: function get() {
            return this._accurate;
          },
          set: function set(val) {
            if (this._accurate === val) return;
            this._accurate = val;
            if (this._resource) {
              this._resource.accurate = val;
              if (val) {
                this._resource.type = this._type;
              }
            }
          }
        }, {
          key: "fogColor",
          get: function get() {
            return this._fogColor;
          },
          set: function set(val) {
            this._fogColor.set(val);
            if (this._resource) {
              this._resource.fogColor = this._fogColor;
            }
          }
        }, {
          key: "type",
          get: function get() {
            return this._type;
          },
          set: function set(val) {
            this._type = val;
            if (this._resource) {
              this._resource.type = val;
            }
          }
        }, {
          key: "fogDensity",
          get: function get() {
            return this._fogDensity;
          },
          set: function set(val) {
            this._fogDensity = val;
            if (this._resource) {
              this._resource.fogDensity = val;
            }
          }
        }, {
          key: "fogStart",
          get: function get() {
            return this._fogStart;
          },
          set: function set(val) {
            this._fogStart = val;
            if (this._resource) {
              this._resource.fogStart = val;
            }
          }
        }, {
          key: "fogEnd",
          get: function get() {
            return this._fogEnd;
          },
          set: function set(val) {
            this._fogEnd = val;
            if (this._resource) {
              this._resource.fogEnd = val;
            }
          }
        }, {
          key: "fogAtten",
          get: function get() {
            return this._fogAtten;
          },
          set: function set(val) {
            this._fogAtten = val;
            if (this._resource) {
              this._resource.fogAtten = val;
            }
          }
        }, {
          key: "fogTop",
          get: function get() {
            return this._fogTop;
          },
          set: function set(val) {
            this._fogTop = val;
            if (this._resource) {
              this._resource.fogTop = val;
            }
          }
        }, {
          key: "fogRange",
          get: function get() {
            return this._fogRange;
          },
          set: function set(val) {
            this._fogRange = val;
            if (this._resource) {
              this._resource.fogRange = val;
            }
          }
        }]);
        return FogInfo;
      }(), _class9.FogType = FogType, _class9), (_applyDecoratedDescriptor(_class8$a.prototype, "type", [_dec22$5], Object.getOwnPropertyDescriptor(_class8$a.prototype, "type"), _class8$a.prototype), _applyDecoratedDescriptor(_class8$a.prototype, "fogDensity", [_dec23$5], Object.getOwnPropertyDescriptor(_class8$a.prototype, "fogDensity"), _class8$a.prototype), _applyDecoratedDescriptor(_class8$a.prototype, "fogStart", [_dec24$5], Object.getOwnPropertyDescriptor(_class8$a.prototype, "fogStart"), _class8$a.prototype), _applyDecoratedDescriptor(_class8$a.prototype, "fogEnd", [_dec25$5], Object.getOwnPropertyDescriptor(_class8$a.prototype, "fogEnd"), _class8$a.prototype), _applyDecoratedDescriptor(_class8$a.prototype, "fogAtten", [_dec26$5], Object.getOwnPropertyDescriptor(_class8$a.prototype, "fogAtten"), _class8$a.prototype), _applyDecoratedDescriptor(_class8$a.prototype, "fogTop", [_dec27$5], Object.getOwnPropertyDescriptor(_class8$a.prototype, "fogTop"), _class8$a.prototype), _applyDecoratedDescriptor(_class8$a.prototype, "fogRange", [_dec28$5], Object.getOwnPropertyDescriptor(_class8$a.prototype, "fogRange"), _class8$a.prototype), _initializer18$8 = applyDecoratedInitializer(_class8$a.prototype, "_type", [serializable$j], function () {
        return FogType.LINEAR;
      }), _initializer19$7 = applyDecoratedInitializer(_class8$a.prototype, "_fogColor", [serializable$j], function () {
        return new Color$1('#C8C8C8');
      }), _initializer20$6 = applyDecoratedInitializer(_class8$a.prototype, "_enabled", [serializable$j], function () {
        return false;
      }), _initializer21$6 = applyDecoratedInitializer(_class8$a.prototype, "_fogDensity", [serializable$j], function () {
        return 0.3;
      }), _initializer22$5 = applyDecoratedInitializer(_class8$a.prototype, "_fogStart", [serializable$j], function () {
        return 0.5;
      }), _initializer23$4 = applyDecoratedInitializer(_class8$a.prototype, "_fogEnd", [serializable$j], function () {
        return 300;
      }), _initializer24$4 = applyDecoratedInitializer(_class8$a.prototype, "_fogAtten", [serializable$j], function () {
        return 5;
      }), _initializer25$4 = applyDecoratedInitializer(_class8$a.prototype, "_fogTop", [serializable$j], function () {
        return 1.5;
      }), _initializer26$4 = applyDecoratedInitializer(_class8$a.prototype, "_fogRange", [serializable$j], function () {
        return 1.2;
      }), _initializer27$3 = applyDecoratedInitializer(_class8$a.prototype, "_accurate", [serializable$j], function () {
        return false;
      })), _class8$a)) || _class7$b));
      var ShadowsInfo = exports('dJ', (_dec29$4 = ccclass$n('cc.ShadowsInfo'), _dec30$3 = type$7(ShadowType), _dec31$3 = type$7(CCFloat), _dec32$2 = type$7(CCInteger), _dec33$2 = type$7(ShadowSize), _dec29$4(_class10$6 = (_class11$6 = function () {
        function ShadowsInfo() {
          this._enabled = _initializer28$3 && _initializer28$3();
          this._type = _initializer29$3 && _initializer29$3();
          this._normal = _initializer30$3 && _initializer30$3();
          this._distance = _initializer31$3 && _initializer31$3();
          this._shadowColor = _initializer32$2 && _initializer32$2();
          this._maxReceived = _initializer33$2 && _initializer33$2();
          this._size = _initializer34$2 && _initializer34$2();
          this._resource = null;
        }
        var _proto4 = ShadowsInfo.prototype;
        _proto4.setPlaneFromNode = function setPlaneFromNode(node) {
          node.getWorldRotation(_qt$1);
          this.planeDirection = Vec3.transformQuat(_v3$3, _up, _qt$1);
          node.getWorldPosition(_v3$3);
          this.planeHeight = Vec3.dot(this._normal, _v3$3);
        };
        _proto4.activate = function activate(resource) {
          this._resource = resource;
          this._resource.initialize(this);
          this._resource.activate();
        };
        _createClass(ShadowsInfo, [{
          key: "enabled",
          get: function get() {
            return this._enabled;
          },
          set: function set(val) {
            if (this._enabled === val) return;
            this._enabled = val;
            if (this._resource) {
              this._resource.enabled = val;
              if (val) {
                this._resource.type = this._type;
              }
            }
          }
        }, {
          key: "type",
          get: function get() {
            return this._type;
          },
          set: function set(val) {
            this._type = val;
            if (this._resource) {
              this._resource.type = val;
            }
          }
        }, {
          key: "shadowColor",
          get: function get() {
            return this._shadowColor;
          },
          set: function set(val) {
            this._shadowColor.set(val);
            if (this._resource) {
              this._resource.shadowColor = val;
            }
          }
        }, {
          key: "planeDirection",
          get: function get() {
            return this._normal;
          },
          set: function set(val) {
            Vec3.copy(this._normal, val);
            if (this._resource) {
              this._resource.normal = val;
            }
          }
        }, {
          key: "planeHeight",
          get: function get() {
            return this._distance;
          },
          set: function set(val) {
            this._distance = val;
            if (this._resource) {
              this._resource.distance = val;
            }
          }
        }, {
          key: "maxReceived",
          get: function get() {
            return this._maxReceived;
          },
          set: function set(val) {
            this._maxReceived = val;
            if (this._resource) {
              this._resource.maxReceived = val;
            }
          }
        }, {
          key: "shadowMapSize",
          get: function get() {
            return this._size.x;
          },
          set: function set(value) {
            this._size.set(value, value);
            if (this._resource) {
              this._resource.size.set(value, value);
              this._resource.shadowMapDirty = true;
            }
          }
        }]);
        return ShadowsInfo;
      }(), (_applyDecoratedDescriptor(_class11$6.prototype, "type", [_dec30$3], Object.getOwnPropertyDescriptor(_class11$6.prototype, "type"), _class11$6.prototype), _applyDecoratedDescriptor(_class11$6.prototype, "planeHeight", [_dec31$3], Object.getOwnPropertyDescriptor(_class11$6.prototype, "planeHeight"), _class11$6.prototype), _applyDecoratedDescriptor(_class11$6.prototype, "maxReceived", [_dec32$2], Object.getOwnPropertyDescriptor(_class11$6.prototype, "maxReceived"), _class11$6.prototype), _applyDecoratedDescriptor(_class11$6.prototype, "shadowMapSize", [_dec33$2], Object.getOwnPropertyDescriptor(_class11$6.prototype, "shadowMapSize"), _class11$6.prototype), _initializer28$3 = applyDecoratedInitializer(_class11$6.prototype, "_enabled", [serializable$j], function () {
        return false;
      }), _initializer29$3 = applyDecoratedInitializer(_class11$6.prototype, "_type", [serializable$j], function () {
        return ShadowType.Planar;
      }), _initializer30$3 = applyDecoratedInitializer(_class11$6.prototype, "_normal", [serializable$j], function () {
        return new Vec3(0, 1, 0);
      }), _initializer31$3 = applyDecoratedInitializer(_class11$6.prototype, "_distance", [serializable$j], function () {
        return 0;
      }), _initializer32$2 = applyDecoratedInitializer(_class11$6.prototype, "_shadowColor", [serializable$j], function () {
        return new Color$1(0, 0, 0, 76);
      }), _initializer33$2 = applyDecoratedInitializer(_class11$6.prototype, "_maxReceived", [serializable$j], function () {
        return 4;
      }), _initializer34$2 = applyDecoratedInitializer(_class11$6.prototype, "_size", [serializable$j], function () {
        return new Vec2(1024, 1024);
      })), _class11$6)) || _class10$6));
      legacyCC.ShadowsInfo = ShadowsInfo;
      var DEFAULT_WORLD_MIN_POS = exports('dK', new Vec3(-1024.0, -1024.0, -1024.0));
      var DEFAULT_WORLD_MAX_POS = exports('dL', new Vec3(1024.0, 1024.0, 1024.0));
      var DEFAULT_OCTREE_DEPTH = exports('dM', 8);
      var OctreeInfo = exports('dN', (_dec34$2 = ccclass$n('cc.OctreeInfo'), _dec35$2 = type$7(CCInteger), _dec34$2(_class13$5 = (_class14$5 = function () {
        function OctreeInfo() {
          this._enabled = _initializer35$2 && _initializer35$2();
          this._minPos = _initializer36$1 && _initializer36$1();
          this._maxPos = _initializer37$1 && _initializer37$1();
          this._depth = _initializer38$1 && _initializer38$1();
          this._resource = null;
        }
        var _proto5 = OctreeInfo.prototype;
        _proto5.activate = function activate(resource) {
          this._resource = resource;
          this._resource.initialize(this);
        };
        _createClass(OctreeInfo, [{
          key: "enabled",
          get: function get() {
            return this._enabled;
          },
          set: function set(val) {
            if (this._enabled === val) return;
            this._enabled = val;
            if (this._resource) {
              this._resource.enabled = val;
            }
          }
        }, {
          key: "minPos",
          get: function get() {
            return this._minPos;
          },
          set: function set(val) {
            this._minPos = val;
            if (this._resource) {
              this._resource.minPos = val;
            }
          }
        }, {
          key: "maxPos",
          get: function get() {
            return this._maxPos;
          },
          set: function set(val) {
            this._maxPos = val;
            if (this._resource) {
              this._resource.maxPos = val;
            }
          }
        }, {
          key: "depth",
          get: function get() {
            return this._depth;
          },
          set: function set(val) {
            this._depth = val;
            if (this._resource) {
              this._resource.depth = val;
            }
          }
        }]);
        return OctreeInfo;
      }(), (_applyDecoratedDescriptor(_class14$5.prototype, "depth", [_dec35$2], Object.getOwnPropertyDescriptor(_class14$5.prototype, "depth"), _class14$5.prototype), _initializer35$2 = applyDecoratedInitializer(_class14$5.prototype, "_enabled", [serializable$j], function () {
        return false;
      }), _initializer36$1 = applyDecoratedInitializer(_class14$5.prototype, "_minPos", [serializable$j], function () {
        return new Vec3(DEFAULT_WORLD_MIN_POS);
      }), _initializer37$1 = applyDecoratedInitializer(_class14$5.prototype, "_maxPos", [serializable$j], function () {
        return new Vec3(DEFAULT_WORLD_MAX_POS);
      }), _initializer38$1 = applyDecoratedInitializer(_class14$5.prototype, "_depth", [serializable$j], function () {
        return DEFAULT_OCTREE_DEPTH;
      })), _class14$5)) || _class13$5));
      legacyCC.OctreeInfo = OctreeInfo;
      var SkinInfo = exports('dO', (_dec36$2 = ccclass$n('cc.SkinInfo'), _dec37$2 = type$7(CCFloat), _dec38$2 = type$7(CCFloat), _dec36$2(_class16$2 = (_class17$3 = function () {
        function SkinInfo() {
          this._enabled = _initializer39$1 && _initializer39$1();
          this._blurRadius = _initializer40$1 && _initializer40$1();
          this._sssIntensity = _initializer41$1 && _initializer41$1();
          this._resource = null;
        }
        var _proto6 = SkinInfo.prototype;
        _proto6.activate = function activate(resource) {
          this._resource = resource;
          this._resource.initialize(this);
        };
        _createClass(SkinInfo, [{
          key: "enabled",
          get: function get() {
            return this._enabled;
          },
          set: function set(val) {
            if (this._enabled === val) return;
            this._enabled = val;
            if (this._resource) {
              this._resource.enabled = val;
            }
          }
        }, {
          key: "blurRadius",
          get: function get() {
            return this._blurRadius;
          },
          set: function set(val) {
            this._blurRadius = val;
            if (this._resource) {
              this._resource.blurRadius = val;
            }
          }
        }, {
          key: "sssIntensity",
          get: function get() {
            return this._sssIntensity;
          },
          set: function set(val) {
            this._sssIntensity = val;
            if (this._resource) {
              this._resource.sssIntensity = val;
            }
          }
        }]);
        return SkinInfo;
      }(), (_applyDecoratedDescriptor(_class17$3.prototype, "blurRadius", [_dec37$2], Object.getOwnPropertyDescriptor(_class17$3.prototype, "blurRadius"), _class17$3.prototype), _applyDecoratedDescriptor(_class17$3.prototype, "sssIntensity", [_dec38$2], Object.getOwnPropertyDescriptor(_class17$3.prototype, "sssIntensity"), _class17$3.prototype), _initializer39$1 = applyDecoratedInitializer(_class17$3.prototype, "_enabled", [serializable$j], function () {
        return true;
      }), _initializer40$1 = applyDecoratedInitializer(_class17$3.prototype, "_blurRadius", [serializable$j], function () {
        return 0.01;
      }), _initializer41$1 = applyDecoratedInitializer(_class17$3.prototype, "_sssIntensity", [serializable$j], function () {
        return 3.0;
      })), _class17$3)) || _class16$2));
      legacyCC.SkinInfo = SkinInfo;
      var PostSettingsInfo = exports('dP', (_dec39$2 = ccclass$n('cc.PostSettingsInfo'), _dec40$1 = type$7(ToneMappingType), _dec39$2(_class19$2 = (_class20$4 = function () {
        function PostSettingsInfo() {
          this._toneMappingType = _initializer42$1 && _initializer42$1();
          this._resource = null;
        }
        var _proto7 = PostSettingsInfo.prototype;
        _proto7.activate = function activate(resource) {
          this._resource = resource;
          this._resource.initialize(this);
          this._resource.activate();
        };
        _createClass(PostSettingsInfo, [{
          key: "toneMappingType",
          get: function get() {
            return this._toneMappingType;
          },
          set: function set(val) {
            this._toneMappingType = val;
            if (this._resource) {
              this._resource.toneMappingType = val;
            }
          }
        }]);
        return PostSettingsInfo;
      }(), (_applyDecoratedDescriptor(_class20$4.prototype, "toneMappingType", [_dec40$1], Object.getOwnPropertyDescriptor(_class20$4.prototype, "toneMappingType"), _class20$4.prototype), _initializer42$1 = applyDecoratedInitializer(_class20$4.prototype, "_toneMappingType", [serializable$j], function () {
        return ToneMappingType.DEFAULT;
      })), _class20$4)) || _class19$2));
      legacyCC.PostSettingsInfo = PostSettingsInfo;
      var LightProbeInfo = exports('dQ', (_dec41$1 = ccclass$n('cc.LightProbeInfo'), _dec42$1 = type$7(CCFloat), _dec43$1 = type$7(CCInteger), _dec44$1 = type$7(CCInteger), _dec45$1 = type$7(CCFloat), _dec46$1 = type$7(CCFloat), _dec41$1(_class22$2 = (_class23$3 = function () {
        function LightProbeInfo() {
          this._giScale = _initializer43$1 && _initializer43$1();
          this._giSamples = _initializer44$1 && _initializer44$1();
          this._bounces = _initializer45$1 && _initializer45$1();
          this._reduceRinging = _initializer46$1 && _initializer46$1();
          this._showProbe = _initializer47 && _initializer47();
          this._showWireframe = _initializer48 && _initializer48();
          this._showConvex = _initializer49 && _initializer49();
          this._data = _initializer50 && _initializer50();
          this._lightProbeSphereVolume = _initializer51 && _initializer51();
          this._nodes = [];
          this._scene = null;
          this._resource = null;
        }
        var _proto8 = LightProbeInfo.prototype;
        _proto8.activate = function activate(scene, resource) {
          this._scene = scene;
          this._resource = resource;
          this._resource.initialize(this);
        };
        _proto8.onProbeBakeFinished = function onProbeBakeFinished() {
          this.onProbeBakingChanged(this._scene);
        };
        _proto8.onProbeBakeCleared = function onProbeBakeCleared() {
          this.clearSHCoefficients();
          this.onProbeBakingChanged(this._scene);
        };
        _proto8.onProbeBakingChanged = function onProbeBakingChanged(node) {
          if (!node) {
            return;
          }
          node.emit(NodeEventType.LIGHT_PROBE_BAKING_CHANGED);
          for (var i = 0; i < node.children.length; i++) {
            var child = node.children[i];
            this.onProbeBakingChanged(child);
          }
        };
        _proto8.clearSHCoefficients = function clearSHCoefficients() {
          if (!this._data) {
            return;
          }
          var probes = this._data.probes;
          for (var i = 0; i < probes.length; i++) {
            probes[i].coefficients.length = 0;
          }
          this.clearAllSHUBOs();
        };
        _proto8.isUniqueNode = function isUniqueNode() {
          return this._nodes.length === 1;
        };
        _proto8.addNode = function addNode(node) {
          if (!node) {
            return false;
          }
          for (var i = 0; i < this._nodes.length; i++) {
            if (this._nodes[i].node === node) {
              return false;
            }
          }
          this._nodes.push({
            node: node,
            probes: null
          });
          return true;
        };
        _proto8.removeNode = function removeNode(node) {
          if (!node) {
            return false;
          }
          var index = this._nodes.findIndex(function (element) {
            return element.node === node;
          });
          if (index === -1) {
            return false;
          }
          this._nodes.splice(index, 1);
          return true;
        };
        _proto8.syncData = function syncData(node, probes) {
          for (var i = 0; i < this._nodes.length; i++) {
            if (this._nodes[i].node === node) {
              this._nodes[i].probes = probes;
              return;
            }
          }
        };
        _proto8.update = function update(updateTet) {
          if (updateTet === void 0) {
            updateTet = true;
          }
          if (!legacyCC.internal.LightProbesData) {
            return;
          }
          if (!this._data) {
            this._data = new legacyCC.internal.LightProbesData();
            if (this._resource) {
              this._resource.data = this._data;
            }
          }
          var points = [];
          for (var i = 0; i < this._nodes.length; i++) {
            var node = this._nodes[i].node;
            var probes = this._nodes[i].probes;
            var worldPosition = node.worldPosition;
            if (!probes) {
              continue;
            }
            for (var j = 0; j < probes.length; j++) {
              var position = new Vec3(0, 0, 0);
              Vec3.add(position, probes[j], worldPosition);
              points.push(position);
            }
          }
          var pointCount = points.length;
          if (pointCount < 4) {
            this.resetAllTetraIndices();
            this._data.reset();
            return;
          }
          this._data.updateProbes(points);
          if (updateTet) {
            this.resetAllTetraIndices();
            this._data.updateTetrahedrons();
          }
        };
        _proto8.clearAllSHUBOs = function clearAllSHUBOs() {
          if (!this._scene) {
            return;
          }
          var renderScene = this._scene.renderScene;
          if (!renderScene) {
            return;
          }
          var models = renderScene.models;
          for (var i = 0; i < models.length; i++) {
            models[i].clearSHUBOs();
          }
        };
        _proto8.resetAllTetraIndices = function resetAllTetraIndices() {
          if (!this._scene) {
            return;
          }
          var renderScene = this._scene.renderScene;
          if (!renderScene) {
            return;
          }
          var models = renderScene.models;
          for (var i = 0; i < models.length; i++) {
            models[i].tetrahedronIndex = -1;
          }
        };
        _createClass(LightProbeInfo, [{
          key: "giScale",
          get: function get() {
            return this._giScale;
          },
          set: function set(val) {
            if (this._giScale === val) return;
            this._giScale = val;
            if (this._resource) {
              this._resource.giScale = val;
            }
          }
        }, {
          key: "giSamples",
          get: function get() {
            return this._giSamples;
          },
          set: function set(val) {
            if (this._giSamples === val) return;
            this._giSamples = val;
            if (this._resource) {
              this._resource.giSamples = val;
            }
          }
        }, {
          key: "bounces",
          get: function get() {
            return this._bounces;
          },
          set: function set(val) {
            if (this._bounces === val) return;
            this._bounces = val;
            if (this._resource) {
              this._resource.bounces = val;
            }
          }
        }, {
          key: "reduceRinging",
          get: function get() {
            return this._reduceRinging;
          },
          set: function set(val) {
            if (this._reduceRinging === val) return;
            this._reduceRinging = val;
            if (this._resource) {
              this._resource.reduceRinging = val;
            }
          }
        }, {
          key: "showProbe",
          get: function get() {
            return this._showProbe;
          },
          set: function set(val) {
            if (this._showProbe === val) return;
            this._showProbe = val;
            if (this._resource) {
              this._resource.showProbe = val;
            }
          }
        }, {
          key: "showWireframe",
          get: function get() {
            return this._showWireframe;
          },
          set: function set(val) {
            if (this._showWireframe === val) return;
            this._showWireframe = val;
            if (this._resource) {
              this._resource.showWireframe = val;
            }
          }
        }, {
          key: "showConvex",
          get: function get() {
            return this._showConvex;
          },
          set: function set(val) {
            if (this._showConvex === val) return;
            this._showConvex = val;
            if (this._resource) {
              this._resource.showConvex = val;
            }
          }
        }, {
          key: "data",
          get: function get() {
            return this._data;
          },
          set: function set(val) {
            if (this._data === val) return;
            this._data = val;
            if (this._resource) {
              this._resource.data = val;
            }
          }
        }, {
          key: "lightProbeSphereVolume",
          get: function get() {
            return this._lightProbeSphereVolume;
          },
          set: function set(val) {
            if (this._lightProbeSphereVolume === val) return;
            this._lightProbeSphereVolume = val;
            if (this._resource) {
              this._resource.lightProbeSphereVolume = val;
            }
          }
        }]);
        return LightProbeInfo;
      }(), (_applyDecoratedDescriptor(_class23$3.prototype, "giScale", [_dec42$1], Object.getOwnPropertyDescriptor(_class23$3.prototype, "giScale"), _class23$3.prototype), _applyDecoratedDescriptor(_class23$3.prototype, "giSamples", [_dec43$1], Object.getOwnPropertyDescriptor(_class23$3.prototype, "giSamples"), _class23$3.prototype), _applyDecoratedDescriptor(_class23$3.prototype, "bounces", [_dec44$1], Object.getOwnPropertyDescriptor(_class23$3.prototype, "bounces"), _class23$3.prototype), _applyDecoratedDescriptor(_class23$3.prototype, "reduceRinging", [_dec45$1], Object.getOwnPropertyDescriptor(_class23$3.prototype, "reduceRinging"), _class23$3.prototype), _applyDecoratedDescriptor(_class23$3.prototype, "lightProbeSphereVolume", [_dec46$1], Object.getOwnPropertyDescriptor(_class23$3.prototype, "lightProbeSphereVolume"), _class23$3.prototype), _initializer43$1 = applyDecoratedInitializer(_class23$3.prototype, "_giScale", [serializable$j], function () {
        return 1.0;
      }), _initializer44$1 = applyDecoratedInitializer(_class23$3.prototype, "_giSamples", [serializable$j], function () {
        return 1024;
      }), _initializer45$1 = applyDecoratedInitializer(_class23$3.prototype, "_bounces", [serializable$j], function () {
        return 2;
      }), _initializer46$1 = applyDecoratedInitializer(_class23$3.prototype, "_reduceRinging", [serializable$j], function () {
        return 0.0;
      }), _initializer47 = applyDecoratedInitializer(_class23$3.prototype, "_showProbe", [serializable$j], function () {
        return true;
      }), _initializer48 = applyDecoratedInitializer(_class23$3.prototype, "_showWireframe", [serializable$j], function () {
        return true;
      }), _initializer49 = applyDecoratedInitializer(_class23$3.prototype, "_showConvex", [serializable$j], function () {
        return false;
      }), _initializer50 = applyDecoratedInitializer(_class23$3.prototype, "_data", [serializable$j], function () {
        return null;
      }), _initializer51 = applyDecoratedInitializer(_class23$3.prototype, "_lightProbeSphereVolume", [serializable$j], function () {
        return 1.0;
      })), _class23$3)) || _class22$2));
      var SceneGlobals = exports('dR', (_dec47$1 = ccclass$n('cc.SceneGlobals'), _dec48$1 = type$7(SkyboxInfo), _dec47$1(_class25 = (_class26$1 = function () {
        function SceneGlobals() {
          this.ambient = _initializer52 && _initializer52();
          this.shadows = _initializer53 && _initializer53();
          this._skybox = _initializer54 && _initializer54();
          this.fog = _initializer55 && _initializer55();
          this.octree = _initializer56 && _initializer56();
          this.skin = _initializer57 && _initializer57();
          this.lightProbeInfo = _initializer58 && _initializer58();
          this.postSettings = _initializer59 && _initializer59();
          this.bakedWithStationaryMainLight = _initializer60 && _initializer60();
          this.bakedWithHighpLightmap = _initializer61 && _initializer61();
          this.disableLightmap = false;
        }
        var _proto9 = SceneGlobals.prototype;
        _proto9.activate = function activate(scene) {
          var sceneData = legacyCC.director.root.pipeline.pipelineSceneData;
          this.skybox.activate(sceneData.skybox);
          this.ambient.activate(sceneData.ambient);
          this.shadows.activate(sceneData.shadows);
          this.fog.activate(sceneData.fog);
          this.octree.activate(sceneData.octree);
          this.skin.activate(sceneData.skin);
          this.postSettings.activate(sceneData.postSettings);
          if (this.lightProbeInfo && sceneData.lightProbes) {
            this.lightProbeInfo.activate(scene, sceneData.lightProbes);
          }
          var root = legacyCC.director.root;
          root.onGlobalPipelineStateChanged();
        };
        _createClass(SceneGlobals, [{
          key: "skybox",
          get: function get() {
            return this._skybox;
          },
          set: function set(value) {
            this._skybox = value;
          }
        }]);
        return SceneGlobals;
      }(), (_initializer52 = applyDecoratedInitializer(_class26$1.prototype, "ambient", [serializable$j], function () {
        return new AmbientInfo();
      }), _initializer53 = applyDecoratedInitializer(_class26$1.prototype, "shadows", [serializable$j], function () {
        return new ShadowsInfo();
      }), _initializer54 = applyDecoratedInitializer(_class26$1.prototype, "_skybox", [serializable$j], function () {
        return new SkyboxInfo();
      }), _initializer55 = applyDecoratedInitializer(_class26$1.prototype, "fog", [serializable$j], function () {
        return new FogInfo();
      }), _applyDecoratedDescriptor(_class26$1.prototype, "skybox", [_dec48$1], Object.getOwnPropertyDescriptor(_class26$1.prototype, "skybox"), _class26$1.prototype), _initializer56 = applyDecoratedInitializer(_class26$1.prototype, "octree", [serializable$j], function () {
        return new OctreeInfo();
      }), _initializer57 = applyDecoratedInitializer(_class26$1.prototype, "skin", [serializable$j], function () {
        return new SkinInfo();
      }), _initializer58 = applyDecoratedInitializer(_class26$1.prototype, "lightProbeInfo", [serializable$j], function () {
        return new LightProbeInfo();
      }), _initializer59 = applyDecoratedInitializer(_class26$1.prototype, "postSettings", [serializable$j], function () {
        return new PostSettingsInfo();
      }), _initializer60 = applyDecoratedInitializer(_class26$1.prototype, "bakedWithStationaryMainLight", [serializable$j], function () {
        return false;
      }), _initializer61 = applyDecoratedInitializer(_class26$1.prototype, "bakedWithHighpLightmap", [serializable$j], function () {
        return false;
      })), _class26$1)) || _class25));
      legacyCC.SceneGlobals = SceneGlobals;

      var _dec$2M, _dec2$20, _class$2I, _class2$2t, _initializer$2d, _dec3$1n, _dec4$Z, _dec5$O, _dec6$y, _dec7$r, _dec8$j, _class4$u, _class5$v, _initializer2$1J, _initializer3$18, _initializer4$T, _initializer5$E, _initializer6$v, _dec9$g, _class7$a, _class8$9, _initializer7$p, _dec10$b, _dec11$9, _dec12$9, _class10$5, _class11$5, _initializer8$o, _initializer9$m, _initializer10$k, _dec13$7, _dec14$6, _dec15$6, _class13$4, _class14$4, _initializer11$h, _initializer12$f, _dec16$5, _dec17$5, _dec18$4, _class16$1, _class17$2, _initializer13$e, _initializer14$c, _dec19$4, _dec20$4, _dec21$4, _dec22$4, _dec23$4, _dec24$4, _class19$1, _class20$3, _initializer15$9, _initializer16$9, _initializer17$8, _initializer18$7, _initializer19$6, _initializer20$5, _dec25$4, _dec26$4, _dec27$4, _dec28$4, _class22$1, _class23$2, _initializer21$5, _initializer22$4, _initializer23$3, _initializer24$3, _initializer25$3, _initializer26$3;
      var TargetInfo = (_dec$2M = ccclass$n('cc.TargetInfo'), _dec2$20 = type$7([CCString]), _dec$2M(_class$2I = (_class2$2t = function TargetInfo() {
        this.localID = _initializer$2d && _initializer$2d();
      }, (_initializer$2d = applyDecoratedInitializer(_class2$2t.prototype, "localID", [serializable$j, _dec2$20], function () {
        return [];
      })), _class2$2t)) || _class$2I);
      var TargetOverrideInfo = (_dec3$1n = ccclass$n('cc.TargetOverrideInfo'), _dec4$Z = type$7(CCObject), _dec5$O = type$7(TargetInfo), _dec6$y = type$7([CCString]), _dec7$r = type$7(Node$1), _dec8$j = type$7(TargetInfo), _dec3$1n(_class4$u = (_class5$v = function TargetOverrideInfo() {
        this.source = _initializer2$1J && _initializer2$1J();
        this.sourceInfo = _initializer3$18 && _initializer3$18();
        this.propertyPath = _initializer4$T && _initializer4$T();
        this.target = _initializer5$E && _initializer5$E();
        this.targetInfo = _initializer6$v && _initializer6$v();
      }, (_initializer2$1J = applyDecoratedInitializer(_class5$v.prototype, "source", [serializable$j, _dec4$Z], function () {
        return null;
      }), _initializer3$18 = applyDecoratedInitializer(_class5$v.prototype, "sourceInfo", [serializable$j, _dec5$O], function () {
        return null;
      }), _initializer4$T = applyDecoratedInitializer(_class5$v.prototype, "propertyPath", [serializable$j, _dec6$y], function () {
        return [];
      }), _initializer5$E = applyDecoratedInitializer(_class5$v.prototype, "target", [serializable$j, _dec7$r], function () {
        return null;
      }), _initializer6$v = applyDecoratedInitializer(_class5$v.prototype, "targetInfo", [serializable$j, _dec8$j], function () {
        return null;
      })), _class5$v)) || _class4$u);
      var CompPrefabInfo = (_dec9$g = ccclass$n('cc.CompPrefabInfo'), _dec9$g(_class7$a = (_class8$9 = function CompPrefabInfo() {
        this.fileId = _initializer7$p && _initializer7$p();
      }, (_initializer7$p = applyDecoratedInitializer(_class8$9.prototype, "fileId", [serializable$j], function () {
        return '';
      })), _class8$9)) || _class7$a);
      var PropertyOverrideInfo = (_dec10$b = ccclass$n('CCPropertyOverrideInfo'), _dec11$9 = type$7(TargetInfo), _dec12$9 = type$7([CCString]), _dec10$b(_class10$5 = (_class11$5 = function () {
        function PropertyOverrideInfo() {
          this.targetInfo = _initializer8$o && _initializer8$o();
          this.propertyPath = _initializer9$m && _initializer9$m();
          this.value = _initializer10$k && _initializer10$k();
        }
        var _proto = PropertyOverrideInfo.prototype;
        _proto.isTarget = function isTarget(localID, propPath) {
        };
        return PropertyOverrideInfo;
      }(), (_initializer8$o = applyDecoratedInitializer(_class11$5.prototype, "targetInfo", [serializable$j, _dec11$9], function () {
        return null;
      }), _initializer9$m = applyDecoratedInitializer(_class11$5.prototype, "propertyPath", [serializable$j, _dec12$9], function () {
        return [];
      }), _initializer10$k = applyDecoratedInitializer(_class11$5.prototype, "value", [serializable$j], null)), _class11$5)) || _class10$5);
      var MountedChildrenInfo = (_dec13$7 = ccclass$n('cc.MountedChildrenInfo'), _dec14$6 = type$7(TargetInfo), _dec15$6 = type$7([Node$1]), _dec13$7(_class13$4 = (_class14$4 = function () {
        function MountedChildrenInfo() {
          this.targetInfo = _initializer11$h && _initializer11$h();
          this.nodes = _initializer12$f && _initializer12$f();
        }
        var _proto2 = MountedChildrenInfo.prototype;
        _proto2.isTarget = function isTarget(localID) {
        };
        return MountedChildrenInfo;
      }(), (_initializer11$h = applyDecoratedInitializer(_class14$4.prototype, "targetInfo", [serializable$j, _dec14$6], function () {
        return null;
      }), _initializer12$f = applyDecoratedInitializer(_class14$4.prototype, "nodes", [serializable$j, _dec15$6], function () {
        return [];
      })), _class14$4)) || _class13$4);
      var MountedComponentsInfo = (_dec16$5 = ccclass$n('cc.MountedComponentsInfo'), _dec17$5 = type$7(TargetInfo), _dec18$4 = type$7([Component]), _dec16$5(_class16$1 = (_class17$2 = function () {
        function MountedComponentsInfo() {
          this.targetInfo = _initializer13$e && _initializer13$e();
          this.components = _initializer14$c && _initializer14$c();
        }
        var _proto3 = MountedComponentsInfo.prototype;
        _proto3.isTarget = function isTarget(localID) {
        };
        return MountedComponentsInfo;
      }(), (_initializer13$e = applyDecoratedInitializer(_class17$2.prototype, "targetInfo", [serializable$j, _dec17$5], function () {
        return null;
      }), _initializer14$c = applyDecoratedInitializer(_class17$2.prototype, "components", [serializable$j, _dec18$4], function () {
        return [];
      })), _class17$2)) || _class16$1);
      var PrefabInstance = (_dec19$4 = ccclass$n('cc.PrefabInstance'), _dec20$4 = type$7(Node$1), _dec21$4 = type$7([MountedChildrenInfo]), _dec22$4 = type$7([MountedComponentsInfo]), _dec23$4 = type$7([PropertyOverrideInfo]), _dec24$4 = type$7([TargetInfo]), _dec19$4(_class19$1 = (_class20$3 = function () {
        function PrefabInstance() {
          this.fileId = _initializer15$9 && _initializer15$9();
          this.prefabRootNode = _initializer16$9 && _initializer16$9();
          this.mountedChildren = _initializer17$8 && _initializer17$8();
          this.mountedComponents = _initializer18$7 && _initializer18$7();
          this.propertyOverrides = _initializer19$6 && _initializer19$6();
          this.removedComponents = _initializer20$5 && _initializer20$5();
          this.targetMap = {};
          this.expanded = false;
        }
        var _proto4 = PrefabInstance.prototype;
        _proto4.findPropertyOverride = function findPropertyOverride(localID, propPath) {
        };
        _proto4.removePropertyOverride = function removePropertyOverride(localID, propPath) {
        };
        return PrefabInstance;
      }(), (_initializer15$9 = applyDecoratedInitializer(_class20$3.prototype, "fileId", [serializable$j], function () {
        return '';
      }), _initializer16$9 = applyDecoratedInitializer(_class20$3.prototype, "prefabRootNode", [serializable$j, _dec20$4], null), _initializer17$8 = applyDecoratedInitializer(_class20$3.prototype, "mountedChildren", [serializable$j, _dec21$4], function () {
        return [];
      }), _initializer18$7 = applyDecoratedInitializer(_class20$3.prototype, "mountedComponents", [serializable$j, _dec22$4], function () {
        return [];
      }), _initializer19$6 = applyDecoratedInitializer(_class20$3.prototype, "propertyOverrides", [serializable$j, _dec23$4], function () {
        return [];
      }), _initializer20$5 = applyDecoratedInitializer(_class20$3.prototype, "removedComponents", [serializable$j, _dec24$4], function () {
        return [];
      })), _class20$3)) || _class19$1);
      var PrefabInfo = (_dec25$4 = ccclass$n('cc.PrefabInfo'), _dec26$4 = type$7(Node$1), _dec27$4 = type$7(PrefabInstance), _dec28$4 = type$7([TargetOverrideInfo]), _dec25$4(_class22$1 = (_class23$2 = function PrefabInfo() {
        this.root = _initializer21$5 && _initializer21$5();
        this.asset = _initializer22$4 && _initializer22$4();
        this.fileId = _initializer23$3 && _initializer23$3();
        this.instance = _initializer24$3 && _initializer24$3();
        this.targetOverrides = _initializer25$3 && _initializer25$3();
        this.nestedPrefabInstanceRoots = _initializer26$3 && _initializer26$3();
      }, (_initializer21$5 = applyDecoratedInitializer(_class23$2.prototype, "root", [serializable$j, _dec26$4], null), _initializer22$4 = applyDecoratedInitializer(_class23$2.prototype, "asset", [serializable$j], null), _initializer23$3 = applyDecoratedInitializer(_class23$2.prototype, "fileId", [serializable$j], function () {
        return '';
      }), _initializer24$3 = applyDecoratedInitializer(_class23$2.prototype, "instance", [serializable$j, _dec27$4], null), _initializer25$3 = applyDecoratedInitializer(_class23$2.prototype, "targetOverrides", [serializable$j, _dec28$4], null), _initializer26$3 = applyDecoratedInitializer(_class23$2.prototype, "nestedPrefabInstanceRoots", [serializable$j], null)), _class23$2)) || _class22$1);
      legacyCC._PrefabInfo = PrefabInfo;

      function createNodeWithPrefab(node) {
        var prefabInfo = node === null || node === void 0 ? void 0 : node.prefab;
        if (!prefabInfo) {
          return;
        }
        var prefabInstance = prefabInfo.instance;
        if (!prefabInstance) {
          return;
        }
        if (!prefabInfo.asset) {
          {
            errorID(3701, node.name);
          }
          prefabInfo.instance = undefined;
          return;
        }
        var _objFlags = node._objFlags;
        var _parent = node.getParent();
        var _id = node.uuid;
        node[editorExtrasTag];
        legacyCC.game._isCloning = true;
        {
          prefabInfo.asset._doInstantiate(node);
        }
        legacyCC.game._isCloning = false;
        node._objFlags = _objFlags;
        node.modifyParent(_parent);
        node.id = _id;
        if (node.prefab) {
          node.prefab.instance = prefabInfo.instance;
        }
      }
      function generateTargetMap(node, targetMap, isRoot) {
        var _node$prefab;
        if (!targetMap) {
          return;
        }
        if (!node) {
          return;
        }
        var curTargetMap = targetMap;
        var prefabInstance = (_node$prefab = node.prefab) === null || _node$prefab === void 0 ? void 0 : _node$prefab.instance;
        if (!isRoot && prefabInstance) {
          targetMap[prefabInstance.fileId] = {};
          curTargetMap = targetMap[prefabInstance.fileId];
        }
        var prefabInfo = node.prefab;
        if (prefabInfo) {
          curTargetMap[prefabInfo.fileId] = node;
        }
        var components = node.components;
        for (var i = 0; i < components.length; i++) {
          var comp = components[i];
          if (comp.__prefab) {
            curTargetMap[comp.__prefab.fileId] = comp;
          }
        }
        for (var _i = 0; _i < node.children.length; _i++) {
          var childNode = node.children[_i];
          generateTargetMap(childNode, curTargetMap, false);
        }
      }
      function getTarget(localID, targetMap) {
        if (!localID) {
          return null;
        }
        var target = null;
        var targetIter = targetMap;
        for (var i = 0; i < localID.length; i++) {
          if (!targetIter) {
            return null;
          }
          targetIter = targetIter[localID[i]];
        }
        target = targetIter;
        return target;
      }
      function applyMountedChildren(node, mountedChildren, targetMap) {
        if (!mountedChildren) {
          return;
        }
        for (var i = 0; i < mountedChildren.length; i++) {
          var childInfo = mountedChildren[i];
          if (childInfo && childInfo.targetInfo) {
            var target = getTarget(childInfo.targetInfo.localID, targetMap);
            if (!target) {
              continue;
            }
            var curTargetMap = targetMap;
            var localID = childInfo.targetInfo.localID;
            if (localID.length > 0) {
              for (var _i2 = 0; _i2 < localID.length - 1; _i2++) {
                curTargetMap = curTargetMap[localID[_i2]];
              }
            }
            if (childInfo.nodes) {
              for (var _i3 = 0; _i3 < childInfo.nodes.length; _i3++) {
                var childNode = childInfo.nodes[_i3];
                if (!childNode || target.children.includes(childNode)) {
                  continue;
                }
                target.children.push(childNode);
                childNode.modifyParent(target);
                generateTargetMap(childNode, curTargetMap, false);
                childNode.siblingIndex = target.children.length - 1;
                expandPrefabInstanceNode(childNode, true);
              }
            }
          }
        }
      }
      function applyMountedComponents(node, mountedComponents, targetMap) {
        if (!mountedComponents) {
          return;
        }
        for (var i = 0; i < mountedComponents.length; i++) {
          var componentsInfo = mountedComponents[i];
          if (componentsInfo && componentsInfo.targetInfo) {
            var target = getTarget(componentsInfo.targetInfo.localID, targetMap);
            if (!target) {
              continue;
            }
            if (componentsInfo.components) {
              for (var _i4 = 0; _i4 < componentsInfo.components.length; _i4++) {
                var comp = componentsInfo.components[_i4];
                if (!comp) {
                  continue;
                }
                comp.node = target;
                target.getWritableComponents().push(comp);
              }
            }
          }
        }
      }
      function applyRemovedComponents(node, removedComponents, targetMap) {
        if (!removedComponents) {
          return;
        }
        for (var i = 0; i < removedComponents.length; i++) {
          var targetInfo = removedComponents[i];
          if (targetInfo) {
            var target = getTarget(targetInfo.localID, targetMap);
            if (!target || !target.node) {
              continue;
            }
            var index = target.node.components.indexOf(target);
            if (index >= 0) {
              target.node.getWritableComponents().splice(index, 1);
            }
          }
        }
      }
      function applyPropertyOverrides(node, propertyOverrides, targetMap) {
        if (propertyOverrides.length <= 0) {
          return;
        }
        var target = null;
        for (var i = 0; i < propertyOverrides.length; i++) {
          var propOverride = propertyOverrides[i];
          if (propOverride && propOverride.targetInfo) {
            var targetInfo = propOverride.targetInfo;
            target = getTarget(targetInfo.localID, targetMap);
            if (!target) {
              continue;
            }
            var targetPropOwner = target;
            var propertyPath = propOverride.propertyPath.slice();
            if (propertyPath.length > 0) {
              var targetPropName = propertyPath.pop();
              if (!targetPropName) {
                continue;
              }
              for (var _i5 = 0; _i5 < propertyPath.length; _i5++) {
                var propName = propertyPath[_i5];
                targetPropOwner = targetPropOwner[propName];
                if (!targetPropOwner) {
                  break;
                }
              }
              if (!targetPropOwner) {
                continue;
              }
              if (Array.isArray(targetPropOwner)) {
                if (targetPropName === 'length') {
                  targetPropOwner[targetPropName] = propOverride.value;
                } else {
                  var index = Number.parseInt(targetPropName);
                  if (Number.isInteger(index) && index < targetPropOwner.length) {
                    targetPropOwner[targetPropName] = propOverride.value;
                  }
                }
              } else if (targetPropOwner[targetPropName] instanceof ValueType) {
                targetPropOwner[targetPropName].set(propOverride.value);
              } else {
                targetPropOwner[targetPropName] = propOverride.value;
              }
            }
          }
        }
      }
      function applyTargetOverrides(node) {
        var _node$prefab2;
        var targetOverrides = (_node$prefab2 = node.prefab) === null || _node$prefab2 === void 0 ? void 0 : _node$prefab2.targetOverrides;
        if (targetOverrides) {
          for (var i = 0; i < targetOverrides.length; i++) {
            var _targetAsNode$prefab;
            var targetOverride = targetOverrides[i];
            var source = targetOverride.source;
            var sourceInfo = targetOverride.sourceInfo;
            if (sourceInfo) {
              var _src$prefab;
              var src = targetOverride.source;
              var sourceInstance = src === null || src === void 0 ? void 0 : (_src$prefab = src.prefab) === null || _src$prefab === void 0 ? void 0 : _src$prefab.instance;
              if (sourceInstance && sourceInstance.targetMap) {
                source = getTarget(sourceInfo.localID, sourceInstance.targetMap);
              }
            }
            if (!source) {
              continue;
            }
            var target = null;
            var targetInfo = targetOverride.targetInfo;
            if (!targetInfo) {
              continue;
            }
            var targetAsNode = targetOverride.target;
            var targetInstance = targetAsNode === null || targetAsNode === void 0 ? void 0 : (_targetAsNode$prefab = targetAsNode.prefab) === null || _targetAsNode$prefab === void 0 ? void 0 : _targetAsNode$prefab.instance;
            if (!targetInstance || !targetInstance.targetMap) {
              continue;
            }
            target = getTarget(targetInfo.localID, targetInstance.targetMap);
            if (!target) {
              continue;
            }
            var propertyPath = targetOverride.propertyPath.slice();
            var targetPropOwner = source;
            if (propertyPath.length > 0) {
              var targetPropName = propertyPath.pop();
              if (!targetPropName) {
                return;
              }
              for (var _i6 = 0; _i6 < propertyPath.length; _i6++) {
                var propName = propertyPath[_i6];
                targetPropOwner = targetPropOwner[propName];
                if (!targetPropOwner) {
                  break;
                }
              }
              if (!targetPropOwner) {
                continue;
              }
              targetPropOwner[targetPropName] = target;
            }
          }
        }
      }
      function expandPrefabInstanceNode(node, recursively) {
        var _node$prefab3;
        if (recursively === void 0) {
          recursively = false;
        }
        var prefabInstance = node === null || node === void 0 ? void 0 : (_node$prefab3 = node.prefab) === null || _node$prefab3 === void 0 ? void 0 : _node$prefab3.instance;
        if (prefabInstance && !prefabInstance.expanded) {
          createNodeWithPrefab(node);
          if (recursively) {
            if (node && node.children) {
              node.children.forEach(function (child) {
                expandPrefabInstanceNode(child, true);
              });
            }
          }
          var targetMap = {};
          prefabInstance.targetMap = targetMap;
          generateTargetMap(node, targetMap, true);
          applyMountedChildren(node, prefabInstance.mountedChildren, targetMap);
          applyRemovedComponents(node, prefabInstance.removedComponents, targetMap);
          applyMountedComponents(node, prefabInstance.mountedComponents, targetMap);
          applyPropertyOverrides(node, prefabInstance.propertyOverrides, targetMap);
          prefabInstance.expanded = true;
        } else if (recursively) {
          if (node && node.children) {
            node.children.forEach(function (child) {
              expandPrefabInstanceNode(child, true);
            });
          }
        }
      }
      function expandNestedPrefabInstanceNode(node) {
        var prefabInfo = node.prefab;
        if (prefabInfo && prefabInfo.nestedPrefabInstanceRoots) {
          prefabInfo.nestedPrefabInstanceRoots.forEach(function (instanceNode) {
            expandPrefabInstanceNode(instanceNode);
          });
        }
      }
      function applyNodeAndComponentId(prefabInstanceNode, rootId) {
        var components = prefabInstanceNode.components,
          children = prefabInstanceNode.children;
        for (var i = 0; i < components.length; i++) {
          var _comp$__prefab$fileId, _comp$__prefab;
          var comp = components[i];
          var fileID = (_comp$__prefab$fileId = (_comp$__prefab = comp.__prefab) === null || _comp$__prefab === void 0 ? void 0 : _comp$__prefab.fileId) !== null && _comp$__prefab$fileId !== void 0 ? _comp$__prefab$fileId : '';
          comp._id = "" + rootId + fileID;
        }
        for (var _i7 = 0; _i7 < children.length; _i7++) {
          var child = children[_i7];
          var prefabInfo = child.prefab;
          var fileId = prefabInfo !== null && prefabInfo !== void 0 && prefabInfo.instance ? prefabInfo.instance.fileId : prefabInfo === null || prefabInfo === void 0 ? void 0 : prefabInfo.fileId;
          if (!fileId) continue;
          child.id = "" + rootId + fileId;
          if (!(prefabInfo !== null && prefabInfo !== void 0 && prefabInfo.instance)) {
            applyNodeAndComponentId(child, rootId);
          }
        }
      }

      var utils$1 = /*#__PURE__*/Object.freeze({
        __proto__: null,
        createNodeWithPrefab: createNodeWithPrefab,
        generateTargetMap: generateTargetMap,
        getTarget: getTarget,
        applyMountedChildren: applyMountedChildren,
        applyMountedComponents: applyMountedComponents,
        applyRemovedComponents: applyRemovedComponents,
        applyPropertyOverrides: applyPropertyOverrides,
        applyTargetOverrides: applyTargetOverrides,
        expandPrefabInstanceNode: expandPrefabInstanceNode,
        expandNestedPrefabInstanceNode: expandNestedPrefabInstanceNode,
        applyNodeAndComponentId: applyNodeAndComponentId,
        TargetInfo: TargetInfo,
        TargetOverrideInfo: TargetOverrideInfo,
        CompPrefabInfo: CompPrefabInfo,
        PropertyOverrideInfo: PropertyOverrideInfo,
        MountedChildrenInfo: MountedChildrenInfo,
        MountedComponentsInfo: MountedComponentsInfo,
        PrefabInstance: PrefabInstance,
        PrefabInfo: PrefabInfo
      });

      var _dec$2L, _class$2H, _class2$2s, _initializer$2c, _initializer2$1I;
      var Scene = exports('dv', (_dec$2L = ccclass$n('cc.Scene'), _dec$2L(_class$2H = (_class2$2s = function (_Node) {
        _inheritsLoose(Scene, _Node);
        var _proto = Scene.prototype;
        _proto._updateScene = function _updateScene() {
          this._scene = this;
        };
        function Scene(name) {
          var _this;
          _this = _Node.call(this, name) || this;
          _this.autoReleaseAssets = _initializer$2c && _initializer$2c();
          _this._globals = _initializer2$1I && _initializer2$1I();
          _this.dependAssets = null;
          _this._renderScene = null;
          _this._inited = void 0;
          _this._prefabSyncedInLiveReload = false;
          _this._activeInHierarchy = false;
          if (legacyCC.director && legacyCC.director.root) {
            _this._renderScene = legacyCC.director.root.createScene({});
          }
          _this._inited = legacyCC.game ? !legacyCC.game._isCloning : true;
          return _this;
        }
        _proto.destroy = function destroy() {
          var success = CCObject.prototype.destroy.call(this);
          if (success) {
            var children = this._children;
            for (var i = 0; i < children.length; ++i) {
              children[i].active = false;
            }
          }
          if (this._renderScene) legacyCC.director.root.destroyScene(this._renderScene);
          this._active = false;
          this._activeInHierarchy = false;
          return success;
        };
        _proto.addComponent = function addComponent() {
          throw new Error(getError(3822));
        };
        _proto._onHierarchyChanged = function _onHierarchyChanged() {};
        _proto._onPostActivated = function _onPostActivated(active) {};
        _proto._onBatchCreated = function _onBatchCreated(dontSyncChildPrefab) {
          var len = this._children.length;
          for (var i = 0; i < len; ++i) {
            this._children[i]._siblingIndex = i;
            this._children[i]._onBatchCreated(dontSyncChildPrefab);
          }
        };
        _proto.updateWorldTransform = function updateWorldTransform() {};
        _proto._instantiate = function _instantiate() {};
        _proto._load = function _load() {
          if (!this._inited) {
            expandNestedPrefabInstanceNode(this);
            applyTargetOverrides(this);
            this._onBatchCreated(EDITOR );
            this._inited = true;
          }
          this.walk(Node$1._setScene);
        };
        _proto._activate = function _activate(active) {
          if (active === void 0) {
            active = true;
          }
          legacyCC.director._nodeActivator.activateNode(this, active);
          {
            this._globals.activate(this);
          }
        };
        _createClass(Scene, [{
          key: "renderScene",
          get: function get() {
            return this._renderScene;
          }
        }, {
          key: "globals",
          get: function get() {
            return this._globals;
          }
        }]);
        return Scene;
      }(Node$1), (_initializer$2c = applyDecoratedInitializer(_class2$2s.prototype, "autoReleaseAssets", [serializable$j], function () {
        return false;
      }), _initializer2$1I = applyDecoratedInitializer(_class2$2s.prototype, "_globals", [serializable$j], function () {
        return new SceneGlobals();
      })), _class2$2s)) || _class$2H));
      legacyCC.Scene = Scene;

      var _dec$2K, _class$2G, _class2$2r, _initializer$2b;
      var SceneAsset = exports('e5', (_dec$2K = ccclass$n('cc.SceneAsset'), _dec$2K(_class$2G = (_class2$2r = function (_Asset) {
        _inheritsLoose(SceneAsset, _Asset);
        function SceneAsset() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Asset.call.apply(_Asset, [this].concat(args)) || this;
          _this.scene = _initializer$2b && _initializer$2b();
          return _this;
        }
        var _proto = SceneAsset.prototype;
        _proto.initDefault = function initDefault(uuid) {
          _Asset.prototype.initDefault.call(this, uuid);
          this.scene = new Scene('New Scene');
        };
        _proto.validate = function validate() {
          return !!this.scene;
        };
        return SceneAsset;
      }(Asset), (_initializer$2b = applyDecoratedInitializer(_class2$2r.prototype, "scene", [serializable$j], function () {
        return null;
      })), _class2$2r)) || _class$2G));
      legacyCC.SceneAsset = SceneAsset;

      var RenderingDebugViewType = {
        NONE: 0,
        SINGLE: 1,
        COMPOSITE_AND_MISC: 2
      };
      var DebugViewSingleType = {
        NONE: 0,
        VERTEX_COLOR: 1,
        VERTEX_NORMAL: 2,
        VERTEX_TANGENT: 3,
        WORLD_POS: 4,
        VERTEX_MIRROR: 5,
        FACE_SIDE: 6,
        UV0: 7,
        UV1: 8,
        UV_LIGHTMAP: 9,
        PROJ_DEPTH: 10,
        LINEAR_DEPTH: 11,
        FRAGMENT_NORMAL: 12,
        FRAGMENT_TANGENT: 13,
        FRAGMENT_BINORMAL: 14,
        BASE_COLOR: 15,
        DIFFUSE_COLOR: 16,
        SPECULAR_COLOR: 17,
        TRANSPARENCY: 18,
        METALLIC: 19,
        ROUGHNESS: 20,
        SPECULAR_INTENSITY: 21,
        IOR: 22,
        DIRECT_DIFFUSE: 23,
        DIRECT_SPECULAR: 24,
        DIRECT_ALL: 25,
        ENV_DIFFUSE: 26,
        ENV_SPECULAR: 27,
        ENV_ALL: 28,
        EMISSIVE: 29,
        LIGHT_MAP: 30,
        SHADOW: 31,
        AO: 32,
        FRESNEL: 33,
        DIRECT_TRANSMIT_DIFFUSE: 34,
        DIRECT_TRANSMIT_SPECULAR: 35,
        ENV_TRANSMIT_DIFFUSE: 36,
        ENV_TRANSMIT_SPECULAR: 37,
        TRANSMIT_ALL: 38,
        DIRECT_TRT: 39,
        ENV_TRT: 40,
        TRT_ALL: 41,
        FOG: 42
      };
      var DebugViewCompositeType = {
        DIRECT_DIFFUSE: 0,
        DIRECT_SPECULAR: 1,
        ENV_DIFFUSE: 2,
        ENV_SPECULAR: 3,
        EMISSIVE: 4,
        LIGHT_MAP: 5,
        SHADOW: 6,
        AO: 7,
        NORMAL_MAP: 8,
        FOG: 9,
        TONE_MAPPING: 10,
        GAMMA_CORRECTION: 11,
        FRESNEL: 12,
        TRANSMIT_DIFFUSE: 13,
        TRANSMIT_SPECULAR: 14,
        TRT: 15,
        TT: 16,
        MAX_BIT_COUNT: 17
      };
      var DebugView = exports('dn', function () {
        function DebugView() {
          this._singleMode = DebugViewSingleType.NONE;
          this._compositeModeValue = 0;
          this._lightingWithAlbedo = true;
          this._csmLayerColoration = false;
          this._activate();
        }
        var _proto = DebugView.prototype;
        _proto.isCompositeModeEnabled = function isCompositeModeEnabled(val) {
          var mode = this._compositeModeValue & 1 << val;
          return mode !== 0;
        };
        _proto.enableCompositeMode = function enableCompositeMode(val, enable) {
          this._enableCompositeMode(val, enable);
          this._updatePipeline();
        };
        _proto.enableAllCompositeMode = function enableAllCompositeMode(enable) {
          this._enableAllCompositeMode(enable);
          this._updatePipeline();
        };
        _proto.isEnabled = function isEnabled() {
          return this._getType() !== RenderingDebugViewType.NONE;
        };
        _proto.reset = function reset() {
          this._activate();
          this._updatePipeline();
        };
        _proto._activate = function _activate() {
          this._singleMode = DebugViewSingleType.NONE;
          this._enableAllCompositeMode(true);
          this._lightingWithAlbedo = true;
          this._csmLayerColoration = false;
        };
        _proto._updatePipeline = function _updatePipeline() {
          var root = legacyCC.director.root;
          var pipeline = root.pipeline;
          var useDebugView = this._getType();
          if (pipeline.macros.CC_USE_DEBUG_VIEW !== useDebugView) {
            pipeline.macros.CC_USE_DEBUG_VIEW = useDebugView;
            root.onGlobalPipelineStateChanged();
          }
        };
        _proto._enableCompositeMode = function _enableCompositeMode(val, enable) {
          if (enable) {
            this._compositeModeValue |= 1 << val;
          } else {
            this._compositeModeValue &= ~(1 << val);
          }
        };
        _proto._enableAllCompositeMode = function _enableAllCompositeMode(enable) {
          for (var i = 0; i < DebugViewCompositeType.MAX_BIT_COUNT; i++) {
            if (enable) {
              this._compositeModeValue |= 1 << i;
            } else {
              this._compositeModeValue &= ~(1 << i);
            }
          }
        };
        _proto._getType = function _getType() {
          if (this._singleMode !== DebugViewSingleType.NONE) {
            return RenderingDebugViewType.SINGLE;
          } else if (this._lightingWithAlbedo !== true || this._csmLayerColoration !== false) {
            return RenderingDebugViewType.COMPOSITE_AND_MISC;
          } else {
            for (var i = 0; i < DebugViewCompositeType.MAX_BIT_COUNT; i++) {
              if (!this.isCompositeModeEnabled(i)) {
                return RenderingDebugViewType.COMPOSITE_AND_MISC;
              }
            }
          }
          return RenderingDebugViewType.NONE;
        };
        _createClass(DebugView, [{
          key: "singleMode",
          get: function get() {
            return this._singleMode;
          },
          set: function set(val) {
            this._singleMode = val;
            this._updatePipeline();
          }
        }, {
          key: "lightingWithAlbedo",
          get: function get() {
            return this._lightingWithAlbedo;
          },
          set: function set(val) {
            this._lightingWithAlbedo = val;
            this._updatePipeline();
          }
        }, {
          key: "csmLayerColoration",
          get: function get() {
            return this._csmLayerColoration;
          },
          set: function set(val) {
            this._csmLayerColoration = val;
            this._updatePipeline();
          }
        }, {
          key: "debugViewType",
          get: function get() {
            return this._getType();
          }
        }]);
        return DebugView;
      }());

      var _rangedDirLightBoundingBox$2 = new AABB(0.0, 0.0, 0.0, 0.5, 0.5, 0.5);
      var _tmpBoundingBox$2 = new AABB();
      var AntiAliasing$1;
      (function (AntiAliasing) {
        AntiAliasing[AntiAliasing["NONE"] = 0] = "NONE";
        AntiAliasing[AntiAliasing["FXAA"] = 1] = "FXAA";
        AntiAliasing[AntiAliasing["FXAAHQ"] = 2] = "FXAAHQ";
      })(AntiAliasing$1 || (AntiAliasing$1 = {}));
      function getRTFormatBeforeToneMapping(ppl) {
        var useFloatOutput = ppl.getMacroBool('CC_USE_FLOAT_OUTPUT');
        return ppl.pipelineSceneData.isHDR && useFloatOutput && supportsRGBA16HalfFloatTexture(ppl.device) ? Format.RGBA16F : Format.RGBA8;
      }
      function validPunctualLightsCulling(pipeline, camera) {
        var sceneData = pipeline.pipelineSceneData;
        var validPunctualLights = sceneData.validPunctualLights;
        validPunctualLights.length = 0;
        var _sphere = Sphere.create(0, 0, 0, 1);
        var _ref = camera.scene,
          spotLights = _ref.spotLights;
        for (var i = 0; i < spotLights.length; i++) {
          var light = spotLights[i];
          if (light.baked && !camera.node.scene.globals.disableLightmap) {
            continue;
          }
          Sphere.set(_sphere, light.position.x, light.position.y, light.position.z, light.range);
          if (intersect.sphereFrustum(_sphere, camera.frustum)) {
            validPunctualLights.push(light);
          }
        }
        var _ref2 = camera.scene,
          sphereLights = _ref2.sphereLights;
        for (var _i = 0; _i < sphereLights.length; _i++) {
          var _light = sphereLights[_i];
          if (_light.baked && !camera.node.scene.globals.disableLightmap) {
            continue;
          }
          Sphere.set(_sphere, _light.position.x, _light.position.y, _light.position.z, _light.range);
          if (intersect.sphereFrustum(_sphere, camera.frustum)) {
            validPunctualLights.push(_light);
          }
        }
        var _ref3 = camera.scene,
          pointLights = _ref3.pointLights;
        for (var _i2 = 0; _i2 < pointLights.length; _i2++) {
          var _light2 = pointLights[_i2];
          if (_light2.baked) {
            continue;
          }
          Sphere.set(_sphere, _light2.position.x, _light2.position.y, _light2.position.z, _light2.range);
          if (intersect.sphereFrustum(_sphere, camera.frustum)) {
            validPunctualLights.push(_light2);
          }
        }
        var _ref4 = camera.scene,
          rangedDirLights = _ref4.rangedDirLights;
        for (var _i3 = 0; _i3 < rangedDirLights.length; _i3++) {
          var _light3 = rangedDirLights[_i3];
          AABB.transform(_tmpBoundingBox$2, _rangedDirLightBoundingBox$2, _light3.node.getWorldMatrix());
          if (intersect.aabbFrustum(_tmpBoundingBox$2, camera.frustum)) {
            validPunctualLights.push(_light3);
          }
        }
        sceneData.validPunctualLights = validPunctualLights;
      }
      var _cameras = [];
      function getCameraUniqueID(camera) {
        if (!_cameras.includes(camera)) {
          _cameras.push(camera);
        }
        return _cameras.indexOf(camera);
      }
      function getLoadOpOfClearFlag(clearFlag, attachment) {
        var loadOp = LoadOp.CLEAR;
        if (!(clearFlag & ClearFlagBit.COLOR) && attachment === AttachmentType.RENDER_TARGET) {
          if (clearFlag & SKYBOX_FLAG) {
            loadOp = LoadOp.CLEAR;
          } else {
            loadOp = LoadOp.LOAD;
          }
        }
        if ((clearFlag & ClearFlagBit.DEPTH_STENCIL) !== ClearFlagBit.DEPTH_STENCIL && attachment === AttachmentType.DEPTH_STENCIL) {
          if (!(clearFlag & ClearFlagBit.DEPTH)) loadOp = LoadOp.LOAD;
          if (!(clearFlag & ClearFlagBit.STENCIL)) loadOp = LoadOp.LOAD;
        }
        return loadOp;
      }
      function getRenderArea(camera, width, height, light, level, out) {
        if (light === void 0) {
          light = null;
        }
        if (level === void 0) {
          level = 0;
        }
        if (out === void 0) {
          out = undefined;
        }
        out = out || new Rect();
        var vp = camera ? camera.viewport : new Rect(0, 0, 1, 1);
        var w = width;
        var h = height;
        out.x = vp.x * w;
        out.y = vp.y * h;
        out.width = vp.width * w;
        out.height = vp.height * h;
        if (light) {
          switch (light.type) {
            case LightType.DIRECTIONAL:
              {
                var mainLight = light;
                if (mainLight.shadowFixedArea || mainLight.csmLevel === CSMLevel.LEVEL_1) {
                  out.x = 0;
                  out.y = 0;
                  out.width = w;
                  out.height = h;
                } else {
                  var screenSpaceSignY = legacyCC.director.root.device.capabilities.screenSpaceSignY;
                  out.x = level % 2 * 0.5 * w;
                  if (screenSpaceSignY > 0) {
                    out.y = (1 - Math.floor(level / 2)) * 0.5 * h;
                  } else {
                    out.y = Math.floor(level / 2) * 0.5 * h;
                  }
                  out.width = 0.5 * w;
                  out.height = 0.5 * h;
                }
                break;
              }
            case LightType.SPOT:
              {
                out.x = 0;
                out.y = 0;
                out.width = w;
                out.height = h;
                break;
              }
          }
        }
        return out;
      }
      var PostInfo = function () {
        var _proto3 = PostInfo.prototype;
        _proto3._init = function _init() {
          this.postMaterial = new Material();
          this.postMaterial.name = 'builtin-post-process-material';
          this.postMaterial.initialize({
            effectName: 'pipeline/post-process',
            defines: {
              ANTIALIAS_TYPE: this.antiAliasing
            }
          });
          for (var i = 0; i < this.postMaterial.passes.length; ++i) {
            this.postMaterial.passes[i].tryCompile();
          }
        };
        function PostInfo(antiAliasing) {
          if (antiAliasing === void 0) {
            antiAliasing = AntiAliasing$1.NONE;
          }
          this.antiAliasing = AntiAliasing$1.NONE;
          this.antiAliasing = antiAliasing;
          this._init();
        }
        return PostInfo;
      }();
      var ShadowInfo = function () {
        function ShadowInfo() {
          this.shadowEnabled = false;
          this.mainLightShadowNames = new Array();
          this.spotLightShadowNames = new Array();
          this.validLights = [];
        }
        var _proto4 = ShadowInfo.prototype;
        _proto4.reset = function reset() {
          this.shadowEnabled = false;
          this.mainLightShadowNames.length = 0;
          this.spotLightShadowNames.length = 0;
          this.validLights.length = 0;
        };
        return ShadowInfo;
      }();
      new ShadowInfo();
      var GBufferInfo = function GBufferInfo() {
        this.color = void 0;
        this.normal = void 0;
        this.emissive = void 0;
        this.ds = void 0;
      };
      var LightingInfo = function () {
        var _proto5 = LightingInfo.prototype;
        _proto5._init = function _init() {
          this.deferredLightingMaterial = new Material();
          this.deferredLightingMaterial.name = 'builtin-deferred-material';
          this.deferredLightingMaterial.initialize({
            effectName: 'pipeline/deferred-lighting',
            defines: {
              CC_ENABLE_CLUSTERED_LIGHT_CULLING: this.enableCluster,
              CC_RECEIVE_SHADOW: 1
            }
          });
          for (var i = 0; i < this.deferredLightingMaterial.passes.length; ++i) {
            this.deferredLightingMaterial.passes[i].tryCompile();
          }
        };
        function LightingInfo(clusterEn) {
          this.enableCluster = void 0;
          this.enableCluster = clusterEn ? 1 : 0;
          this._init();
        }
        return LightingInfo;
      }();
      function getDescBinding(descId, descData) {
        var layoutData = descData;
        for (var _iterator5 = _createForOfIteratorHelperLoose(layoutData.descriptorSetLayoutData.descriptorBlocks), _step5; !(_step5 = _iterator5()).done;) {
          var block = _step5.value;
          for (var i = 0; i !== block.descriptors.length; ++i) {
            if (descId === block.descriptors[i].descriptorID) {
              return block.offset + i;
            }
          }
        }
        return -1;
      }
      function getDescBindingFromName(bindingName) {
        var pipeline = legacyCC.director.root.pipeline;
        var layoutGraph = pipeline.layoutGraph;
        var vertIds = layoutGraph.vertices();
        var descId = layoutGraph.attributeIndex.get(bindingName);
        var currDesData;
        for (var _iterator6 = _createForOfIteratorHelperLoose(vertIds), _step6; !(_step6 = _iterator6()).done;) {
          var i = _step6.value;
          var layout = layoutGraph.getLayout(i);
          for (var _iterator7 = _createForOfIteratorHelperLoose(layout.descriptorSets), _step7; !(_step7 = _iterator7()).done;) {
            var _step7$value = _step7.value;
              _step7$value[0];
              var descData = _step7$value[1];
            var layoutData = descData.descriptorSetLayoutData;
            var blocks = layoutData.descriptorBlocks;
            for (var _iterator8 = _createForOfIteratorHelperLoose(blocks), _step8; !(_step8 = _iterator8()).done;) {
              var b = _step8.value;
              for (var _iterator9 = _createForOfIteratorHelperLoose(b.descriptors), _step9; !(_step9 = _iterator9()).done;) {
                var ds = _step9.value;
                if (ds.descriptorID === descId) {
                  currDesData = descData;
                  return getDescBinding(descId, currDesData);
                }
              }
            }
          }
        }
        return -1;
      }
      var layouts = new Map();
      function getDescriptorSetDataFromLayout(layoutName) {
        var descLayout = layouts.get(layoutName);
        if (descLayout) {
          return descLayout;
        }
        var webPip = legacyCC.director.root.pipeline;
        var stageId = webPip.layoutGraph.locateChild(webPip.layoutGraph.nullVertex(), layoutName);
        assert(stageId !== 0xFFFFFFFF);
        var layout = webPip.layoutGraph.getLayout(stageId);
        var layoutData = layout.descriptorSets.get(UpdateFrequency.PER_PASS);
        layouts.set(layoutName, layoutData);
        return layoutData;
      }
      var _varianceArray = [0.0484, 0.187, 0.567, 1.99, 7.41];
      var _strengthParameterArray = [0.100, 0.118, 0.113, 0.358, 0.078];
      var _vec3Temp = new Vec3();
      var _vec3Temp2 = new Vec3();
      var _vec4Temp = new Vec4();
      var _vec4Temp2 = new Vec4();
      var COPY_INPUT_DS_PASS_INDEX = 0;
      var SSSS_BLUR_X_PASS_INDEX = 1;
      var SSSS_BLUR_Y_PASS_INDEX = 2;
      var EXPONENT = 2.0;
      var I_SAMPLES_COUNT = 25;
      (function () {
        var _proto6 = SSSSBlurData.prototype;
        _proto6._gaussian = function _gaussian(out, variance, r) {
          var xx = r / (0.001 + this._v3SSSSFallOff.x);
          out.x = Math.exp(-(xx * xx) / (2.0 * variance)) / (2.0 * 3.14 * variance);
          var yy = r / (0.001 + this._v3SSSSFallOff.y);
          out.y = Math.exp(-(yy * yy) / (2.0 * variance)) / (2.0 * 3.14 * variance);
          var zz = r / (0.001 + this._v3SSSSFallOff.z);
          out.z = Math.exp(-(zz * zz) / (2.0 * variance)) / (2.0 * 3.14 * variance);
        };
        _proto6._profile = function _profile(out, val) {
          for (var i = 0; i < 5; i++) {
            this._gaussian(_vec3Temp2, _varianceArray[i], val);
            _vec3Temp2.multiplyScalar(_strengthParameterArray[i]);
            out.add(_vec3Temp2);
          }
        };
        _proto6._updateSampleCount = function _updateSampleCount() {
          var strength = this._v3SSSSStrength;
          var nSamples = I_SAMPLES_COUNT;
          var range = 3.0 ;
          var step = 2.0 * range / (nSamples - 1);
          for (var i = 0; i < nSamples; i++) {
            var o = -range + i * step;
            var sign = o < 0.0 ? -1.0 : 1.0;
            this._kernel[i].w = range * sign * Math.abs(Math.pow(o, EXPONENT)) / Math.pow(range, EXPONENT);
          }
          for (var _i5 = 0; _i5 < nSamples; _i5++) {
            var w0 = _i5 > 0 ? Math.abs(this._kernel[_i5].w - this._kernel[_i5 - 1].w) : 0.0;
            var w1 = _i5 < nSamples - 1 ? Math.abs(this._kernel[_i5].w - this._kernel[_i5 + 1].w) : 0.0;
            var area = (w0 + w1) / 2.0;
            _vec3Temp.set(0);
            this._profile(_vec3Temp, this._kernel[_i5].w);
            _vec3Temp.multiplyScalar(area);
            this._kernel[_i5].x = _vec3Temp.x;
            this._kernel[_i5].y = _vec3Temp.y;
            this._kernel[_i5].z = _vec3Temp.z;
          }
          var remainder = nSamples % 2;
          _vec4Temp.set(this._kernel[(nSamples - remainder) / 2]);
          for (var _i6 = (nSamples - remainder) / 2; _i6 > 0; _i6--) {
            _vec4Temp2.set(this._kernel[_i6 - 1]);
            this._kernel[_i6].set(_vec4Temp2);
          }
          this._kernel[0].set(_vec4Temp);
          _vec3Temp.set(0.0);
          for (var _i7 = 0; _i7 < nSamples; _i7++) {
            _vec3Temp.add3f(this._kernel[_i7].x, this._kernel[_i7].y, this._kernel[_i7].z);
          }
          for (var _i8 = 0; _i8 < nSamples; _i8++) {
            this._kernel[_i8].x /= _vec3Temp.x;
            this._kernel[_i8].y /= _vec3Temp.y;
            this._kernel[_i8].z /= _vec3Temp.z;
          }
          this._kernel[0].x = (1.0 - strength.x) * 1.0 + strength.x * this._kernel[0].x;
          this._kernel[0].y = (1.0 - strength.y) * 1.0 + strength.y * this._kernel[0].y;
          this._kernel[0].z = (1.0 - strength.z) * 1.0 + strength.z * this._kernel[0].z;
          for (var _i9 = 1; _i9 < nSamples; _i9++) {
            this._kernel[_i9].x *= strength.x;
            this._kernel[_i9].y *= strength.y;
            this._kernel[_i9].z *= strength.z;
          }
        };
        _proto6._updateBlurPass = function _updateBlurPass() {
          if (!this.ssssBlurMaterial) return;
          var copyInputDSPass = this.ssssBlurMaterial.passes[COPY_INPUT_DS_PASS_INDEX];
          copyInputDSPass.beginChangeStatesSilently();
          copyInputDSPass.tryCompile();
          copyInputDSPass.endChangeStatesSilently();
          var ssssBlurXPass = this.ssssBlurMaterial.passes[SSSS_BLUR_X_PASS_INDEX];
          ssssBlurXPass.beginChangeStatesSilently();
          ssssBlurXPass.tryCompile();
          ssssBlurXPass.endChangeStatesSilently();
          var ssssBlurYPass = this.ssssBlurMaterial.passes[SSSS_BLUR_Y_PASS_INDEX];
          ssssBlurYPass.beginChangeStatesSilently();
          ssssBlurYPass.tryCompile();
          ssssBlurYPass.endChangeStatesSilently();
        };
        _proto6._init = function _init() {
          if (this.ssssBlurMaterial) return;
          this.ssssBlurMaterial = new Material();
          this.ssssBlurMaterial._uuid = 'builtin-ssssBlur-material';
          this.ssssBlurMaterial.initialize({
            effectName: 'pipeline/ssss-blur'
          });
          for (var i = 0; i < this.ssssBlurMaterial.passes.length; ++i) {
            this.ssssBlurMaterial.passes[i].tryCompile();
          }
          this._updateBlurPass();
          for (var _i10 = 0; _i10 < I_SAMPLES_COUNT; _i10++) {
            this._kernel[_i10] = new Vec4();
          }
          this._updateSampleCount();
        };
        function SSSSBlurData() {
          this.ssssFov = 45.0 / 57.3;
          this.ssssWidth = 0.01;
          this.boundingBox = 0.4;
          this.ssssScale = 3.0;
          this._v3SSSSStrength = new Vec3(0.48, 0.41, 0.28);
          this._v3SSSSFallOff = new Vec3(1.0, 0.37, 0.3);
          this._kernel = [];
          this._init();
        }
        _createClass(SSSSBlurData, [{
          key: "ssssStrength",
          get: function get() {
            return this._v3SSSSStrength;
          },
          set: function set(val) {
            this._v3SSSSStrength = val;
            this._updateSampleCount();
          }
        }, {
          key: "ssssFallOff",
          get: function get() {
            return this._v3SSSSFallOff;
          },
          set: function set(val) {
            this._v3SSSSFallOff = val;
            this._updateSampleCount();
          }
        }, {
          key: "kernel",
          get: function get() {
            return this._kernel;
          }
        }]);
        return SSSSBlurData;
      })();
      (function () {
        var _proto8 = HBAOParams.prototype;
        _proto8._init = function _init() {
          if (this.hbaoMaterial) return;
          this.hbaoMaterial = new Material();
          this.hbaoMaterial.name = 'builtin-hbao-material';
          this.hbaoMaterial.initialize({
            effectName: 'pipeline/post-process/hbao'
          });
          for (var i = 0; i < this.hbaoMaterial.passes.length; ++i) {
            this.hbaoMaterial.passes[i].tryCompile();
          }
          var width = 4;
          var height = 4;
          var pixelFormat = Texture2D.PixelFormat.RGBA8888;
          var arrayBuffer = new Uint8Array(width * height * 4);
          for (var _i11 = 0; _i11 < this._randomDirAndJitter.length; _i11++) {
            arrayBuffer[_i11] = this._randomDirAndJitter[_i11];
          }
          var image = new ImageAsset({
            width: width,
            height: height,
            _data: arrayBuffer,
            _compressed: false,
            format: pixelFormat
          });
          this.randomTexture = new Texture2D();
          this.randomTexture.setFilters(Texture2D.Filter.NEAREST, Texture2D.Filter.NEAREST);
          this.randomTexture.setMipFilter(Texture2D.Filter.NONE);
          this.randomTexture.setWrapMode(Texture2D.WrapMode.REPEAT, Texture2D.WrapMode.REPEAT, Texture2D.WrapMode.REPEAT);
          this.randomTexture.image = image;
          this.hbaoMaterial.setProperty('RandomTex', this.randomTexture, 0);
        };
        _proto8.update = function update() {
          var HALF_KERNEL_RADIUS = 4;
          var INV_LN2 = 1.44269504;
          var SQRT_LN2 = 0.8325546;
          var gR = this._radiusScale * this._sceneScale;
          var gR2 = gR * gR;
          var gNegInvR2 = -1.0 / gR2;
          var gMaxRadiusPixels = 0.1 * Math.min(this._depthTexFullResolution.x, this._depthTexFullResolution.y);
          this._radiusParam.set(gR, gR2, gNegInvR2, gMaxRadiusPixels);
          var vec2 = new Vec2(this._depthTexResolution.y / this._depthTexResolution.x, 1.0);
          var gFocalLen = new Vec2(vec2.x / Math.tan(this._cameraFov * 0.5), vec2.y / Math.tan(this._cameraFov * 0.5));
          var gTanAngleBias = Math.tan(toRadian(this._angleBiasDegree));
          var gStrength = this._aoStrength;
          this._miscParam.set(gFocalLen.x, gFocalLen.y, gTanAngleBias, gStrength);
          var gUVToViewA = new Vec2(2.0 / gFocalLen.x, -2.0 / gFocalLen.y);
          var gUVToViewB = new Vec2(-1.0 / gFocalLen.x, 1.0 / gFocalLen.y);
          this._uvDepthToEyePosParams.set(gUVToViewA.x, gUVToViewA.y, gUVToViewB.x, gUVToViewB.y);
          var BlurSigma = (HALF_KERNEL_RADIUS + 1.0) * 0.5;
          var gBlurFallOff = INV_LN2 / (2.0 * BlurSigma * BlurSigma);
          var gBlurDepthThreshold = 2.0 * SQRT_LN2 * (this._sceneScale / this._blurSharpness);
          this._blurParam.set(gBlurFallOff, gBlurDepthThreshold, this._blurSharpness / 8.0, this._aoSaturation);
        };
        function HBAOParams() {
          this._uvDepthToEyePosParams = new Vec4();
          this._radiusParam = new Vec4();
          this._miscParam = new Vec4();
          this._blurParam = new Vec4();
          this._depthTexFullResolution = new Vec2(1024);
          this._depthTexResolution = new Vec2(1024);
          this._sceneScale = 1.0;
          this._cameraFov = toRadian(45.0);
          this._radiusScale = 1.0;
          this._angleBiasDegree = 10.0;
          this._aoStrength = 1.0;
          this._blurSharpness = 8;
          this._aoSaturation = 1.0;
          this._randomDirAndJitter = [238, 91, 87, 255, 251, 44, 119, 255, 247, 64, 250, 255, 232, 5, 225, 255, 253, 177, 140, 255, 250, 51, 84, 255, 243, 76, 97, 255, 252, 36, 232, 255, 235, 100, 24, 255, 252, 36, 158, 255, 254, 20, 142, 255, 245, 135, 124, 255, 251, 43, 121, 255, 253, 31, 145, 255, 235, 98, 160, 255, 240, 146, 198, 255];
          this._init();
          this.update();
        }
        _createClass(HBAOParams, [{
          key: "uvDepthToEyePosParams",
          get: function get() {
            return this._uvDepthToEyePosParams;
          }
        }, {
          key: "radiusParam",
          get: function get() {
            return this._radiusParam;
          }
        }, {
          key: "miscParam",
          get: function get() {
            return this._miscParam;
          }
        }, {
          key: "blurParam",
          get: function get() {
            return this._blurParam;
          }
        }, {
          key: "depthTexFullResolution",
          set: function set(val) {
            this._depthTexFullResolution.set(val);
          }
        }, {
          key: "depthTexResolution",
          set: function set(val) {
            this._depthTexResolution.set(val);
          }
        }, {
          key: "sceneScale",
          set: function set(val) {
            this._sceneScale = val;
          }
        }, {
          key: "cameraFov",
          set: function set(val) {
            this._cameraFov = val;
          }
        }, {
          key: "radiusScale",
          set: function set(val) {
            this._radiusScale = val;
          }
        }, {
          key: "angleBiasDegree",
          set: function set(val) {
            this._angleBiasDegree = val;
          }
        }, {
          key: "aoStrength",
          set: function set(val) {
            this._aoStrength = val;
          }
        }, {
          key: "blurSharpness",
          set: function set(val) {
            this._blurSharpness = val;
          }
        }, {
          key: "aoSaturation",
          set: function set(val) {
            this._aoSaturation = val;
          }
        }]);
        return HBAOParams;
      })();
      new Vec2();
      var MAX_LIGHTS_PER_CLUSTER = 100;
      var CLUSTERS_X = 16;
      var CLUSTERS_Y = 8;
      var CLUSTERS_Z = 24;
      var CLUSTER_COUNT = CLUSTERS_X * CLUSTERS_Y * CLUSTERS_Z;
      var ClusterLightData = function () {
        var _proto9 = ClusterLightData.prototype;
        _proto9._initMaterial = function _initMaterial(id, effect) {
          var mat = new Material();
          mat.name = id;
          mat.initialize({
            effectName: effect
          });
          for (var i = 0; i < mat.passes.length; ++i) {
            mat.passes[i].tryCompile();
          }
          return mat;
        };
        _proto9._init = function _init() {
          this.clusterBuildCS = this._initMaterial('builtin-cluster-build-cs-material', 'pipeline/cluster-build');
          this.clusterLightCullingCS = this._initMaterial('builtin-cluster-culling-cs-material', 'pipeline/cluster-culling');
          this.dispatchX = CLUSTERS_X / this.clusters_x_threads;
          this.dispatchY = CLUSTERS_Y / this.clusters_y_threads;
          this.dispatchZ = CLUSTERS_Z / this.clusters_z_threads;
        };
        function ClusterLightData() {
          this.clusters_x_threads = 16;
          this.clusters_y_threads = 8;
          this.clusters_z_threads = 1;
          this.dispatchX = 1;
          this.dispatchY = 1;
          this.dispatchZ = 1;
          this._init();
        }
        return ClusterLightData;
      }();
      var _clusterLightData = null;
      function buildLightClusterBuildPass(camera, clusterData, ppl) {
        var cameraID = getCameraUniqueID(camera);
        var clusterBufferName = "clusterBuffer" + cameraID;
        var clusterBufferSize = CLUSTER_COUNT * 2 * 4 * 4;
        if (!ppl.containsResource(clusterBufferName)) {
          ppl.addStorageBuffer(clusterBufferName, Format.UNKNOWN, clusterBufferSize, ResourceResidency.MANAGED);
        }
        ppl.updateStorageBuffer(clusterBufferName, clusterBufferSize);
        var clusterPass = ppl.addComputePass('cluster-build-cs');
        clusterPass.addStorageBuffer(clusterBufferName, AccessType.WRITE, 'b_clustersBuffer');
        clusterPass.addQueue().addDispatch(clusterData.dispatchX, clusterData.dispatchY, clusterData.dispatchZ, clusterData.clusterBuildCS, 0);
        var width = camera.width * ppl.pipelineSceneData.shadingScale;
        var height = camera.height * ppl.pipelineSceneData.shadingScale;
        clusterPass.setVec4('cc_nearFar', new Vec4(camera.nearClip, camera.farClip, camera.getClipSpaceMinz(), 0));
        clusterPass.setVec4('cc_viewPort', new Vec4(0, 0, width, height));
        clusterPass.setVec4('cc_workGroup', new Vec4(CLUSTERS_X, CLUSTERS_Y, CLUSTERS_Z, 0));
        clusterPass.setMat4('cc_matView', camera.matView);
        clusterPass.setMat4('cc_matProjInv', camera.matProjInv);
      }
      function buildLightClusterCullingPass(camera, clusterData, ppl) {
        var cameraID = getCameraUniqueID(camera);
        var clusterBufferName = "clusterBuffer" + cameraID;
        var clusterLightBufferName = "clusterLightBuffer" + cameraID;
        var clusterGlobalIndexBufferName = "globalIndexBuffer" + cameraID;
        var clusterLightIndicesBufferName = "clusterLightIndicesBuffer" + cameraID;
        var clusterLightGridBufferName = "clusterLightGridBuffer" + cameraID;
        var lightIndexBufferSize = MAX_LIGHTS_PER_CLUSTER * CLUSTER_COUNT * 4;
        var lightGridBufferSize = CLUSTER_COUNT * 4 * 4;
        if (!ppl.containsResource(clusterLightIndicesBufferName)) {
          ppl.addStorageBuffer(clusterLightIndicesBufferName, Format.UNKNOWN, lightIndexBufferSize, ResourceResidency.MANAGED);
        }
        if (!ppl.containsResource(clusterLightGridBufferName)) {
          ppl.addStorageBuffer(clusterLightGridBufferName, Format.UNKNOWN, lightGridBufferSize, ResourceResidency.MANAGED);
        }
        var clusterPass = ppl.addComputePass('cluster-culling-cs');
        clusterPass.addStorageBuffer(clusterLightBufferName, AccessType.READ, 'b_ccLightsBuffer');
        clusterPass.addStorageBuffer(clusterBufferName, AccessType.READ, 'b_clustersBuffer');
        clusterPass.addStorageBuffer(clusterLightIndicesBufferName, AccessType.WRITE, 'b_clusterLightIndicesBuffer');
        clusterPass.addStorageBuffer(clusterLightGridBufferName, AccessType.WRITE, 'b_clusterLightGridBuffer');
        clusterPass.addStorageBuffer(clusterGlobalIndexBufferName, AccessType.WRITE, 'b_globalIndexBuffer');
        clusterPass.addQueue().addDispatch(clusterData.dispatchX, clusterData.dispatchY, clusterData.dispatchZ, clusterData.clusterLightCullingCS, 0);
        var width = camera.width * ppl.pipelineSceneData.shadingScale;
        var height = camera.height * ppl.pipelineSceneData.shadingScale;
        clusterPass.setVec4('cc_nearFar', new Vec4(camera.nearClip, camera.farClip, camera.getClipSpaceMinz(), 0));
        clusterPass.setVec4('cc_viewPort', new Vec4(width, height, width, height));
        clusterPass.setVec4('cc_workGroup', new Vec4(CLUSTERS_X, CLUSTERS_Y, CLUSTERS_Z, 0));
        clusterPass.setMat4('cc_matView', camera.matView);
        clusterPass.setMat4('cc_matProjInv', camera.matProjInv);
      }
      function buildLightBuffer(size, floatPerLight, camera, pipeline) {
        var buffer = new ArrayBuffer(size);
        var view = new Float32Array(buffer);
        var data = pipeline.pipelineSceneData;
        var lightMeterScale = 10000.0;
        var exposure = camera.exposure;
        var index = 0;
        for (var _iterator17 = _createForOfIteratorHelperLoose(data.validPunctualLights), _step17; !(_step17 = _iterator17()).done;) {
          var light = _step17.value;
          var offset = index * floatPerLight;
          var positionOffset = offset + 0;
          var colorOffset = offset + 4;
          var sizeRangeAngleOffset = offset + 8;
          var directionOffset = offset + 12;
          var boundSizeOffset = offset + 16;
          var luminanceHDR = 0;
          var luminanceLDR = 0;
          var position = void 0;
          if (light.type === LightType.POINT) {
            var point = light;
            position = point.position;
            luminanceLDR = point.luminanceLDR;
            luminanceHDR = point.luminanceHDR;
            view[sizeRangeAngleOffset] = 0;
            view[sizeRangeAngleOffset + 1] = point.range;
            view[sizeRangeAngleOffset + 2] = 0;
            view[sizeRangeAngleOffset + 3] = 0;
          } else if (light.type === LightType.SPHERE) {
            var sphere = light;
            position = sphere.position;
            luminanceLDR = sphere.luminanceLDR;
            luminanceHDR = sphere.luminanceHDR;
            view[sizeRangeAngleOffset] = sphere.size;
            view[sizeRangeAngleOffset + 1] = sphere.range;
            view[sizeRangeAngleOffset + 2] = 0;
            view[sizeRangeAngleOffset + 3] = 0;
          } else if (light.type === LightType.SPOT) {
            var spot = light;
            position = spot.position;
            luminanceLDR = spot.luminanceLDR;
            luminanceHDR = spot.luminanceHDR;
            view[sizeRangeAngleOffset] = spot.size;
            view[sizeRangeAngleOffset + 1] = spot.range;
            view[sizeRangeAngleOffset + 2] = spot.spotAngle;
            view[sizeRangeAngleOffset + 3] = 0;
            var dir = spot.direction;
            view[directionOffset] = dir.x;
            view[directionOffset + 1] = dir.y;
            view[directionOffset + 2] = dir.z;
            view[directionOffset + 3] = 0;
          } else if (light.type === LightType.RANGED_DIRECTIONAL) {
            var directional = light;
            position = directional.position;
            luminanceLDR = directional.illuminanceLDR;
            luminanceHDR = directional.illuminanceHDR;
            var right = directional.right;
            view[sizeRangeAngleOffset] = right.x;
            view[sizeRangeAngleOffset + 1] = right.y;
            view[sizeRangeAngleOffset + 2] = right.z;
            view[sizeRangeAngleOffset + 3] = 0;
            var _dir = directional.direction;
            view[directionOffset] = _dir.x;
            view[directionOffset + 1] = _dir.y;
            view[directionOffset + 2] = _dir.z;
            view[directionOffset + 3] = 0;
            var scale = directional.scale;
            view[boundSizeOffset] = scale.x * 0.5;
            view[boundSizeOffset + 1] = scale.y * 0.5;
            view[boundSizeOffset + 2] = scale.z * 0.5;
            view[boundSizeOffset + 3] = 0;
          }
          view[positionOffset] = position.x;
          view[positionOffset + 1] = position.y;
          view[positionOffset + 2] = position.z;
          view[positionOffset + 3] = light.type;
          var color = light.color;
          if (light.useColorTemperature) {
            var tempRGB = light.colorTemperatureRGB;
            view[colorOffset] = color.x * tempRGB.x;
            view[colorOffset + 1] = color.y * tempRGB.y;
            view[colorOffset + 2] = color.z * tempRGB.z;
          } else {
            view[colorOffset] = color.x;
            view[colorOffset + 1] = color.y;
            view[colorOffset + 2] = color.z;
          }
          view[colorOffset + 3] = data.isHDR ? luminanceHDR * exposure * lightMeterScale : luminanceLDR;
          index++;
        }
        view[3 * 4 + 3] = data.validPunctualLights.length;
        return buffer;
      }
      function buildClusterLightData(camera, pipeline) {
        validPunctualLightsCulling(pipeline, camera);
        var data = pipeline.pipelineSceneData;
        var validLightCountForBuffer = nextPow2(Math.max(data.validPunctualLights.length, 1));
        var lightBufferFloatNum = 20;
        var clusterLightBufferSize = validLightCountForBuffer * 4 * lightBufferFloatNum;
        var cameraID = getCameraUniqueID(camera);
        var clusterLightBufferName = "clusterLightBuffer" + cameraID;
        var clusterGlobalIndexBufferName = "globalIndexBuffer" + cameraID;
        var ppl = pipeline;
        if (!ppl.containsResource(clusterGlobalIndexBufferName)) {
          ppl.addStorageBuffer(clusterGlobalIndexBufferName, Format.UNKNOWN, 4, ResourceResidency.PERSISTENT);
        }
        if (!ppl.containsResource(clusterLightBufferName)) {
          ppl.addStorageBuffer(clusterLightBufferName, Format.UNKNOWN, clusterLightBufferSize, ResourceResidency.PERSISTENT);
        }
        ppl.updateStorageBuffer(clusterLightBufferName, clusterLightBufferSize);
        var buffer = buildLightBuffer(clusterLightBufferSize, lightBufferFloatNum, camera, pipeline);
        var globalIndexBuffer = new ArrayBuffer(4);
        var globalIndexBufferView = new Uint32Array(globalIndexBuffer);
        globalIndexBufferView[0] = 0;
        var uploadPair1 = new UploadPair(new Uint8Array(buffer), clusterLightBufferName);
        var uploadPair2 = new UploadPair(new Uint8Array(globalIndexBuffer), clusterGlobalIndexBufferName);
        ppl.addUploadPass([uploadPair1, uploadPair2]);
      }
      function buildClusterPasses(camera, pipeline) {
        buildClusterLightData(camera, pipeline);
        var ppl = pipeline;
        if (!_clusterLightData) _clusterLightData = new ClusterLightData();
        buildLightClusterBuildPass(camera, _clusterLightData, ppl);
        buildLightClusterCullingPass(camera, _clusterLightData, ppl);
      }

      var _samplerLinearInfo = new SamplerInfo(Filter$1.LINEAR, Filter$1.LINEAR, Filter$1.NONE, Address.CLAMP, Address.CLAMP, Address.CLAMP);
      var _samplerPointInfo = new SamplerInfo(Filter$1.POINT, Filter$1.POINT, Filter$1.NONE, Address.CLAMP, Address.CLAMP, Address.CLAMP);
      var GlobalDSManager = function () {
        function GlobalDSManager(device) {
          this._device = void 0;
          this._descriptorSetMap = new Map();
          this._globalDescriptorSet = void 0;
          this._descriptorSetLayout = void 0;
          this._linearSampler = void 0;
          this._pointSampler = void 0;
          this._device = device;
          this._linearSampler = this._device.getSampler(_samplerLinearInfo);
          this._pointSampler = this._device.getSampler(_samplerPointInfo);
          var layoutInfo = new DescriptorSetLayoutInfo(globalDescriptorSetLayout.bindings);
          this._descriptorSetLayout = this._device.createDescriptorSetLayout(layoutInfo);
          this._globalDescriptorSet = this._device.createDescriptorSet(new DescriptorSetInfo(this._descriptorSetLayout));
        }
        var _proto = GlobalDSManager.prototype;
        _proto.regenLayout = function regenLayout() {
          var layoutInfo = new DescriptorSetLayoutInfo(globalDescriptorSetLayout.bindings);
          this._descriptorSetLayout = this._device.createDescriptorSetLayout(layoutInfo);
          this._globalDescriptorSet = this._device.createDescriptorSet(new DescriptorSetInfo(this._descriptorSetLayout));
        };
        _proto.bindBuffer = function bindBuffer(binding, buffer) {
          this._globalDescriptorSet.bindBuffer(binding, buffer);
          var it = this._descriptorSetMap.values();
          var res = it.next();
          while (!res.done) {
            var descriptorSet = res.value;
            descriptorSet.bindBuffer(binding, buffer);
            res = it.next();
          }
        };
        _proto.bindSampler = function bindSampler(binding, sampler) {
          this._globalDescriptorSet.bindSampler(binding, sampler);
          var it = this._descriptorSetMap.values();
          var res = it.next();
          while (!res.done) {
            var descriptorSet = res.value;
            descriptorSet.bindSampler(binding, sampler);
            res = it.next();
          }
        };
        _proto.bindTexture = function bindTexture(binding, texture) {
          this._globalDescriptorSet.bindTexture(binding, texture);
          var it = this._descriptorSetMap.values();
          var res = it.next();
          while (!res.done) {
            var descriptorSet = res.value;
            descriptorSet.bindTexture(binding, texture);
            res = it.next();
          }
        };
        _proto.update = function update() {
          this._globalDescriptorSet.update();
          var it = this._descriptorSetMap.values();
          var res = it.next();
          while (!res.done) {
            var descriptorSet = res.value;
            descriptorSet.update();
            res = it.next();
          }
        };
        _proto.getOrCreateDescriptorSet = function getOrCreateDescriptorSet(light) {
          var device = this._device;
          if (!this._descriptorSetMap.has(light)) {
            var globalDescriptorSet = isEnableEffect() ? getDescriptorSetDataFromLayout('default').descriptorSet : this._globalDescriptorSet;
            var descriptorSet = device.createDescriptorSet(new DescriptorSetInfo(isEnableEffect() ? getDescriptorSetDataFromLayout('default').descriptorSetLayout : this._descriptorSetLayout));
            this._descriptorSetMap.set(light, descriptorSet);
            for (var i = PipelineGlobalBindings.UBO_GLOBAL; i < PipelineGlobalBindings.COUNT; i++) {
              descriptorSet.bindBuffer(i, globalDescriptorSet.getBuffer(i));
              descriptorSet.bindSampler(i, globalDescriptorSet.getSampler(i));
              descriptorSet.bindTexture(i, globalDescriptorSet.getTexture(i));
            }
            var shadowUBO = device.createBuffer(new BufferInfo(BufferUsageBit.UNIFORM | BufferUsageBit.TRANSFER_DST, MemoryUsageBit.HOST | MemoryUsageBit.DEVICE, UBOShadow.SIZE, UBOShadow.SIZE));
            var binding = isEnableEffect() ? getDescBindingFromName('CCShadow') : UBOShadow.BINDING;
            descriptorSet.bindBuffer(binding, shadowUBO);
            descriptorSet.update();
          }
          return this._descriptorSetMap.get(light);
        };
        _proto.destroy = function destroy() {
          this._descriptorSetLayout.destroy();
        };
        _createClass(GlobalDSManager, [{
          key: "descriptorSetMap",
          get: function get() {
            return this._descriptorSetMap;
          }
        }, {
          key: "linearSampler",
          get: function get() {
            return this._linearSampler;
          }
        }, {
          key: "pointSampler",
          get: function get() {
            return this._pointSampler;
          }
        }, {
          key: "descriptorSetLayout",
          get: function get() {
            return this._descriptorSetLayout;
          }
        }, {
          key: "globalDescriptorSet",
          get: function get() {
            return this._globalDescriptorSet;
          },
          set: function set(val) {
            this._globalDescriptorSet = val;
          }
        }]);
        return GlobalDSManager;
      }();

      var _matShadowView$2 = new Mat4();
      var _matShadowProj$1 = new Mat4();
      var _matShadowViewProj$2 = new Mat4();
      var _vec4ShadowInfo = new Vec4();
      var _lightDir = new Vec4(0.0, 0.0, 1.0, 0.0);
      var _tempVec3$3 = new Vec3();
      var PipelineUBO = function () {
        function PipelineUBO() {
          this._globalUBO = new Float32Array(UBOGlobal.COUNT);
          this._cameraUBO = new Float32Array(UBOCamera.COUNT);
          this._shadowUBO = new Float32Array(UBOShadow.COUNT);
          this._csmUBO = new Float32Array(UBOCSM.COUNT);
        }
        PipelineUBO.updateGlobalUBOView = function updateGlobalUBOView(window, bufferView) {
          var director = legacyCC.director;
          var root = director.root;
          var fv = bufferView;
          var shadingWidth = Math.floor(window.width);
          var shadingHeight = Math.floor(window.height);
          fv[UBOGlobal.TIME_OFFSET] = root.cumulativeTime;
          fv[UBOGlobal.TIME_OFFSET + 1] = root.frameTime;
          fv[UBOGlobal.TIME_OFFSET + 2] = director.getTotalFrames();
          fv[UBOGlobal.TIME_OFFSET + 3] = root.cumulativeTime - Math.floor(root.frameTime);
          fv[UBOGlobal.SCREEN_SIZE_OFFSET] = shadingWidth;
          fv[UBOGlobal.SCREEN_SIZE_OFFSET + 1] = shadingHeight;
          fv[UBOGlobal.SCREEN_SIZE_OFFSET + 2] = 1.0 / shadingWidth;
          fv[UBOGlobal.SCREEN_SIZE_OFFSET + 3] = 1.0 / shadingHeight;
          fv[UBOGlobal.NATIVE_SIZE_OFFSET] = shadingWidth;
          fv[UBOGlobal.NATIVE_SIZE_OFFSET + 1] = shadingHeight;
          fv[UBOGlobal.NATIVE_SIZE_OFFSET + 2] = 1.0 / fv[UBOGlobal.NATIVE_SIZE_OFFSET];
          fv[UBOGlobal.NATIVE_SIZE_OFFSET + 3] = 1.0 / fv[UBOGlobal.NATIVE_SIZE_OFFSET + 1];
          if (legacyCC.internal.reflectionProbeManager) {
            fv[UBOGlobal.PROBE_INFO_OFFSET] = legacyCC.internal.reflectionProbeManager.getMaxProbeId() + 1;
          }
          var debugView = root.debugView;
          for (var i = 0; i <= 3; i++) {
            fv[UBOGlobal.DEBUG_VIEW_MODE_OFFSET + i] = 0.0;
          }
          if (debugView.isEnabled()) {
            fv[UBOGlobal.DEBUG_VIEW_MODE_OFFSET] = debugView.singleMode;
            for (var _i = DebugViewCompositeType.DIRECT_DIFFUSE; _i < DebugViewCompositeType.MAX_BIT_COUNT; _i++) {
              var offset = _i >> 3;
              var bit = _i % 8;
              fv[UBOGlobal.DEBUG_VIEW_MODE_OFFSET + 1 + offset] += (debugView.isCompositeModeEnabled(_i) ? 1.0 : 0.0) * Math.pow(10.0, bit);
            }
            fv[UBOGlobal.DEBUG_VIEW_MODE_OFFSET + 3] += (debugView.lightingWithAlbedo ? 1.0 : 0.0) * Math.pow(10.0, 6.0);
            fv[UBOGlobal.DEBUG_VIEW_MODE_OFFSET + 3] += (debugView.csmLayerColoration ? 1.0 : 0.0) * Math.pow(10.0, 7.0);
          }
        };
        PipelineUBO.updateCameraUBOView = function updateCameraUBOView(pipeline, bufferView, camera) {
          var _skybox$envmap;
          var scene = camera.scene ? camera.scene : legacyCC.director.getScene().renderScene;
          var mainLight = scene.mainLight;
          var sceneData = pipeline.pipelineSceneData;
          var ambient = sceneData.ambient;
          var skybox = sceneData.skybox;
          var fog = sceneData.fog;
          var shadowInfo = sceneData.shadows;
          var cv = bufferView;
          var exposure = camera.exposure;
          var isHDR = sceneData.isHDR;
          cv[UBOCamera.SCREEN_SCALE_OFFSET] = sceneData.shadingScale;
          cv[UBOCamera.SCREEN_SCALE_OFFSET + 1] = sceneData.shadingScale;
          cv[UBOCamera.SCREEN_SCALE_OFFSET + 2] = 1.0 / cv[UBOCamera.SCREEN_SCALE_OFFSET];
          cv[UBOCamera.SCREEN_SCALE_OFFSET + 3] = 1.0 / cv[UBOCamera.SCREEN_SCALE_OFFSET + 1];
          cv[UBOCamera.EXPOSURE_OFFSET] = exposure;
          cv[UBOCamera.EXPOSURE_OFFSET + 1] = 1.0 / exposure;
          cv[UBOCamera.EXPOSURE_OFFSET + 2] = isHDR ? 1.0 : 0.0;
          cv[UBOCamera.EXPOSURE_OFFSET + 3] = 1.0 / Camera$1.standardExposureValue;
          if (mainLight) {
            var shadowEnable = mainLight.shadowEnabled && shadowInfo.type === ShadowType.ShadowMap ? 1.0 : 0.0;
            var mainLightDir = mainLight.direction;
            _lightDir.set(mainLightDir.x, mainLightDir.y, mainLightDir.z, shadowEnable);
            Vec4.toArray(cv, _lightDir, UBOCamera.MAIN_LIT_DIR_OFFSET);
            Vec3.toArray(cv, mainLight.color, UBOCamera.MAIN_LIT_COLOR_OFFSET);
            if (mainLight.useColorTemperature) {
              var _colorTempRGB = mainLight.colorTemperatureRGB;
              cv[UBOCamera.MAIN_LIT_COLOR_OFFSET] *= _colorTempRGB.x;
              cv[UBOCamera.MAIN_LIT_COLOR_OFFSET + 1] *= _colorTempRGB.y;
              cv[UBOCamera.MAIN_LIT_COLOR_OFFSET + 2] *= _colorTempRGB.z;
            }
            if (isHDR) {
              cv[UBOCamera.MAIN_LIT_COLOR_OFFSET + 3] = mainLight.illuminance * exposure;
            } else {
              cv[UBOCamera.MAIN_LIT_COLOR_OFFSET + 3] = mainLight.illuminance;
            }
          } else {
            _lightDir.set(0, 0, 1, 0);
            Vec4.toArray(cv, _lightDir, UBOCamera.MAIN_LIT_DIR_OFFSET);
            Vec4.toArray(cv, Vec4.ZERO, UBOCamera.MAIN_LIT_COLOR_OFFSET);
          }
          var skyColor = ambient.skyColor;
          if (isHDR) {
            skyColor.w = ambient.skyIllum * exposure;
          } else {
            skyColor.w = ambient.skyIllum;
          }
          cv[UBOCamera.AMBIENT_SKY_OFFSET + 0] = skyColor.x;
          cv[UBOCamera.AMBIENT_SKY_OFFSET + 1] = skyColor.y;
          cv[UBOCamera.AMBIENT_SKY_OFFSET + 2] = skyColor.z;
          cv[UBOCamera.AMBIENT_SKY_OFFSET + 3] = skyColor.w;
          cv[UBOCamera.AMBIENT_GROUND_OFFSET + 0] = ambient.groundAlbedo.x;
          cv[UBOCamera.AMBIENT_GROUND_OFFSET + 1] = ambient.groundAlbedo.y;
          cv[UBOCamera.AMBIENT_GROUND_OFFSET + 2] = ambient.groundAlbedo.z;
          cv[UBOCamera.AMBIENT_GROUND_OFFSET + 3] = skybox.envmap ? (_skybox$envmap = skybox.envmap) === null || _skybox$envmap === void 0 ? void 0 : _skybox$envmap.mipmapLevel : 1.0;
          Mat4.toArray(cv, camera.matView, UBOCamera.MAT_VIEW_OFFSET);
          Mat4.toArray(cv, camera.node.worldMatrix, UBOCamera.MAT_VIEW_INV_OFFSET);
          Vec3.toArray(cv, camera.position, UBOCamera.CAMERA_POS_OFFSET);
          Mat4.toArray(cv, camera.matProj, UBOCamera.MAT_PROJ_OFFSET);
          Mat4.toArray(cv, camera.matProjInv, UBOCamera.MAT_PROJ_INV_OFFSET);
          Mat4.toArray(cv, camera.matViewProj, UBOCamera.MAT_VIEW_PROJ_OFFSET);
          Mat4.toArray(cv, camera.matViewProjInv, UBOCamera.MAT_VIEW_PROJ_INV_OFFSET);
          cv[UBOCamera.CAMERA_POS_OFFSET + 3] = this.getCombineSignY();
          cv[UBOCamera.SURFACE_TRANSFORM_OFFSET] = camera.surfaceTransform;
          cv[UBOCamera.SURFACE_TRANSFORM_OFFSET + 1] = camera.cameraUsage;
          cv[UBOCamera.SURFACE_TRANSFORM_OFFSET + 2] = Math.cos(toRadian(sceneData.skybox.getRotationAngle()));
          cv[UBOCamera.SURFACE_TRANSFORM_OFFSET + 3] = Math.sin(toRadian(sceneData.skybox.getRotationAngle()));
          var colorTempRGB = fog.colorArray;
          cv[UBOCamera.GLOBAL_FOG_COLOR_OFFSET] = colorTempRGB.x;
          cv[UBOCamera.GLOBAL_FOG_COLOR_OFFSET + 1] = colorTempRGB.y;
          cv[UBOCamera.GLOBAL_FOG_COLOR_OFFSET + 2] = colorTempRGB.z;
          cv[UBOCamera.GLOBAL_FOG_COLOR_OFFSET + 3] = colorTempRGB.z;
          cv[UBOCamera.GLOBAL_FOG_BASE_OFFSET] = fog.fogStart;
          cv[UBOCamera.GLOBAL_FOG_BASE_OFFSET + 1] = fog.fogEnd;
          cv[UBOCamera.GLOBAL_FOG_BASE_OFFSET + 2] = fog.fogDensity;
          cv[UBOCamera.GLOBAL_FOG_ADD_OFFSET] = fog.fogTop;
          cv[UBOCamera.GLOBAL_FOG_ADD_OFFSET + 1] = fog.fogRange;
          cv[UBOCamera.GLOBAL_FOG_ADD_OFFSET + 2] = fog.fogAtten;
          cv[UBOCamera.NEAR_FAR_OFFSET] = camera.nearClip;
          cv[UBOCamera.NEAR_FAR_OFFSET + 1] = camera.farClip;
          cv[UBOCamera.NEAR_FAR_OFFSET + 2] = camera.getClipSpaceMinz();
          cv[UBOCamera.VIEW_PORT_OFFSET] = sceneData.shadingScale * camera.window.width * camera.viewport.x;
          cv[UBOCamera.VIEW_PORT_OFFSET + 1] = sceneData.shadingScale * camera.window.height * camera.viewport.y;
          cv[UBOCamera.VIEW_PORT_OFFSET + 2] = sceneData.shadingScale * camera.window.width * camera.viewport.z;
          cv[UBOCamera.VIEW_PORT_OFFSET + 3] = sceneData.shadingScale * camera.window.height * camera.viewport.w;
        };
        PipelineUBO.getPCFRadius = function getPCFRadius(shadowInfo, mainLight) {
          var shadowMapSize = shadowInfo.size.x;
          switch (mainLight.shadowPcf) {
            case PCFType.HARD:
              return 0.0;
            case PCFType.SOFT:
              return 1.0 / (shadowMapSize * 0.5);
            case PCFType.SOFT_2X:
              return 2.0 / (shadowMapSize * 0.5);
            case PCFType.SOFT_4X:
              return 3.0 / (shadowMapSize * 0.5);
          }
          return 0.0;
        };
        PipelineUBO.updatePlanarNormalAndDistance = function updatePlanarNormalAndDistance(shadowInfo, shadowUBO) {
          Vec3.normalize(_tempVec3$3, shadowInfo.normal);
          shadowUBO[UBOShadow.PLANAR_NORMAL_DISTANCE_INFO_OFFSET + 0] = _tempVec3$3.x;
          shadowUBO[UBOShadow.PLANAR_NORMAL_DISTANCE_INFO_OFFSET + 1] = _tempVec3$3.y;
          shadowUBO[UBOShadow.PLANAR_NORMAL_DISTANCE_INFO_OFFSET + 2] = _tempVec3$3.z;
          shadowUBO[UBOShadow.PLANAR_NORMAL_DISTANCE_INFO_OFFSET + 3] = -shadowInfo.distance;
        };
        PipelineUBO.updateShadowUBOView = function updateShadowUBOView(pipeline, shadowBufferView, csmBufferView, camera) {
          var device = pipeline.device;
          var mainLight = camera.scene.mainLight;
          var sceneData = pipeline.pipelineSceneData;
          var shadowInfo = sceneData.shadows;
          var csmLayers = sceneData.csmLayers;
          var sv = shadowBufferView;
          var cv = csmBufferView;
          var csmSupported = sceneData.csmSupported;
          var packing = supportsR32FloatTexture(device) ? 0.0 : 1.0;
          if (mainLight && shadowInfo.enabled) {
            if (shadowInfo.type === ShadowType.ShadowMap) {
              if (mainLight.shadowEnabled) {
                if (mainLight.shadowFixedArea || mainLight.csmLevel === CSMLevel.LEVEL_1 || !csmSupported) {
                  var matShadowView = csmLayers.specialLayer.matShadowView;
                  var matShadowProj = csmLayers.specialLayer.matShadowProj;
                  var matShadowViewProj = csmLayers.specialLayer.matShadowViewProj;
                  var near = 0.1;
                  var far = 0;
                  var levelCount = 0;
                  if (mainLight.shadowFixedArea) {
                    near = mainLight.shadowNear;
                    far = mainLight.shadowFar;
                    levelCount = 0;
                  } else {
                    far = csmLayers.specialLayer.shadowCameraFar;
                    levelCount = 1;
                  }
                  Mat4.toArray(sv, matShadowView, UBOShadow.MAT_LIGHT_VIEW_OFFSET);
                  sv[UBOShadow.SHADOW_PROJ_DEPTH_INFO_OFFSET + 0] = matShadowProj.m10;
                  sv[UBOShadow.SHADOW_PROJ_DEPTH_INFO_OFFSET + 1] = matShadowProj.m14;
                  sv[UBOShadow.SHADOW_PROJ_DEPTH_INFO_OFFSET + 2] = matShadowProj.m11;
                  sv[UBOShadow.SHADOW_PROJ_DEPTH_INFO_OFFSET + 3] = matShadowProj.m15;
                  sv[UBOShadow.SHADOW_PROJ_INFO_OFFSET + 0] = matShadowProj.m00;
                  sv[UBOShadow.SHADOW_PROJ_INFO_OFFSET + 1] = matShadowProj.m05;
                  sv[UBOShadow.SHADOW_PROJ_INFO_OFFSET + 2] = 1.0 / matShadowProj.m00;
                  sv[UBOShadow.SHADOW_PROJ_INFO_OFFSET + 3] = 1.0 / matShadowProj.m05;
                  Mat4.toArray(sv, matShadowViewProj, UBOShadow.MAT_LIGHT_VIEW_PROJ_OFFSET);
                  _vec4ShadowInfo.set(near, far, 0, 1.0 - mainLight.shadowSaturation);
                  Vec4.toArray(sv, _vec4ShadowInfo, UBOShadow.SHADOW_NEAR_FAR_LINEAR_SATURATION_INFO_OFFSET);
                  _vec4ShadowInfo.set(LightType.DIRECTIONAL, packing, mainLight.shadowNormalBias, levelCount);
                  Vec4.toArray(sv, _vec4ShadowInfo, UBOShadow.SHADOW_LIGHT_PACKING_NBIAS_NULL_INFO_OFFSET);
                } else {
                  var layerThreshold = this.getPCFRadius(shadowInfo, mainLight);
                  for (var i = 0; i < mainLight.csmLevel; i++) {
                    var layer = csmLayers.layers[i];
                    var _matShadowView2 = layer.matShadowView;
                    _vec4ShadowInfo.set(_matShadowView2.m00, _matShadowView2.m04, _matShadowView2.m08, layerThreshold);
                    Vec4.toArray(cv, _vec4ShadowInfo, UBOCSM.CSM_VIEW_DIR_0_OFFSET + 4 * i);
                    _vec4ShadowInfo.set(_matShadowView2.m01, _matShadowView2.m05, _matShadowView2.m09, layer.splitCameraNear);
                    Vec4.toArray(cv, _vec4ShadowInfo, UBOCSM.CSM_VIEW_DIR_1_OFFSET + 4 * i);
                    _vec4ShadowInfo.set(_matShadowView2.m02, _matShadowView2.m06, _matShadowView2.m10, layer.splitCameraFar);
                    Vec4.toArray(cv, _vec4ShadowInfo, UBOCSM.CSM_VIEW_DIR_2_OFFSET + 4 * i);
                    var csmAtlas = layer.csmAtlas;
                    Vec4.toArray(cv, csmAtlas, UBOCSM.CSM_ATLAS_OFFSET + 4 * i);
                    var _matShadowViewProj2 = layer.matShadowViewProj;
                    Mat4.toArray(cv, _matShadowViewProj2, UBOCSM.MAT_CSM_VIEW_PROJ_OFFSET + 16 * i);
                    var _matShadowProj2 = layer.matShadowProj;
                    cv[UBOCSM.CSM_PROJ_DEPTH_INFO_OFFSET + 0 + 4 * i] = _matShadowProj2.m10;
                    cv[UBOCSM.CSM_PROJ_DEPTH_INFO_OFFSET + 1 + 4 * i] = _matShadowProj2.m14;
                    cv[UBOCSM.CSM_PROJ_DEPTH_INFO_OFFSET + 2 + 4 * i] = _matShadowProj2.m11;
                    cv[UBOCSM.CSM_PROJ_DEPTH_INFO_OFFSET + 3 + 4 * i] = _matShadowProj2.m15;
                    cv[UBOCSM.CSM_PROJ_INFO_OFFSET + 0 + 4 * i] = _matShadowProj2.m00;
                    cv[UBOCSM.CSM_PROJ_INFO_OFFSET + 1 + 4 * i] = _matShadowProj2.m05;
                    cv[UBOCSM.CSM_PROJ_INFO_OFFSET + 2 + 4 * i] = 1.0 / _matShadowProj2.m00;
                    cv[UBOCSM.CSM_PROJ_INFO_OFFSET + 3 + 4 * i] = 1.0 / _matShadowProj2.m05;
                  }
                  _vec4ShadowInfo.set(mainLight.csmTransitionRange, 0, 0, 0);
                  Vec4.toArray(cv, _vec4ShadowInfo, UBOCSM.CSM_SPLITS_INFO_OFFSET);
                  _vec4ShadowInfo.set(0.1, mainLight.shadowDistance, 0, 1.0 - mainLight.shadowSaturation);
                  Vec4.toArray(sv, _vec4ShadowInfo, UBOShadow.SHADOW_NEAR_FAR_LINEAR_SATURATION_INFO_OFFSET);
                  _vec4ShadowInfo.set(LightType.DIRECTIONAL, packing, mainLight.shadowNormalBias, mainLight.csmLevel);
                  Vec4.toArray(sv, _vec4ShadowInfo, UBOShadow.SHADOW_LIGHT_PACKING_NBIAS_NULL_INFO_OFFSET);
                }
                _vec4ShadowInfo.set(shadowInfo.size.x, shadowInfo.size.y, mainLight.shadowPcf, mainLight.shadowBias);
                Vec4.toArray(sv, _vec4ShadowInfo, UBOShadow.SHADOW_WIDTH_HEIGHT_PCF_BIAS_INFO_OFFSET);
              }
            } else {
              PipelineUBO.updatePlanarNormalAndDistance(shadowInfo, sv);
            }
            Color$1.toArray(sv, shadowInfo.shadowColor, UBOShadow.SHADOW_COLOR_OFFSET);
          }
        };
        PipelineUBO.updateShadowUBOLightView = function updateShadowUBOLightView(pipeline, shadowBufferView, light, level) {
          var device = pipeline.device;
          var sceneData = pipeline.pipelineSceneData;
          var shadowInfo = sceneData.shadows;
          var csmLayers = sceneData.csmLayers;
          var sv = shadowBufferView;
          var packing = supportsR32FloatTexture(device) ? 0.0 : 1.0;
          var cap = pipeline.device.capabilities;
          var csmSupported = sceneData.csmSupported;
          switch (light.type) {
            case LightType.DIRECTIONAL:
              {
                var mainLight = light;
                if (shadowInfo.enabled && mainLight && mainLight.shadowEnabled) {
                  if (shadowInfo.type === ShadowType.ShadowMap) {
                    var near = 0.1;
                    var far = 0;
                    var matShadowView;
                    var matShadowProj;
                    var matShadowViewProj;
                    var levelCount = 0;
                    if (mainLight.shadowFixedArea || mainLight.csmLevel === CSMLevel.LEVEL_1 || !csmSupported) {
                      matShadowView = csmLayers.specialLayer.matShadowView;
                      matShadowProj = csmLayers.specialLayer.matShadowProj;
                      matShadowViewProj = csmLayers.specialLayer.matShadowViewProj;
                      if (mainLight.shadowFixedArea) {
                        near = mainLight.shadowNear;
                        far = mainLight.shadowFar;
                        levelCount = 0;
                      } else {
                        near = 0.1;
                        far = csmLayers.specialLayer.shadowCameraFar;
                        levelCount = 1;
                      }
                      _vec4ShadowInfo.set(LightType.DIRECTIONAL, packing, mainLight.shadowNormalBias, 0);
                      Vec4.toArray(sv, _vec4ShadowInfo, UBOShadow.SHADOW_LIGHT_PACKING_NBIAS_NULL_INFO_OFFSET);
                    } else {
                      var layer = csmLayers.layers[level];
                      matShadowView = layer.matShadowView;
                      matShadowProj = layer.matShadowProj;
                      matShadowViewProj = layer.matShadowViewProj;
                      near = layer.splitCameraNear;
                      far = layer.splitCameraFar;
                      levelCount = mainLight.csmLevel;
                    }
                    Mat4.toArray(sv, matShadowView, UBOShadow.MAT_LIGHT_VIEW_OFFSET);
                    sv[UBOShadow.SHADOW_PROJ_DEPTH_INFO_OFFSET + 0] = matShadowProj.m10;
                    sv[UBOShadow.SHADOW_PROJ_DEPTH_INFO_OFFSET + 1] = matShadowProj.m14;
                    sv[UBOShadow.SHADOW_PROJ_DEPTH_INFO_OFFSET + 2] = matShadowProj.m11;
                    sv[UBOShadow.SHADOW_PROJ_DEPTH_INFO_OFFSET + 3] = matShadowProj.m15;
                    sv[UBOShadow.SHADOW_PROJ_INFO_OFFSET + 0] = matShadowProj.m00;
                    sv[UBOShadow.SHADOW_PROJ_INFO_OFFSET + 1] = matShadowProj.m05;
                    sv[UBOShadow.SHADOW_PROJ_INFO_OFFSET + 2] = 1.0 / matShadowProj.m00;
                    sv[UBOShadow.SHADOW_PROJ_INFO_OFFSET + 3] = 1.0 / matShadowProj.m05;
                    Mat4.toArray(sv, matShadowViewProj, UBOShadow.MAT_LIGHT_VIEW_PROJ_OFFSET);
                    _vec4ShadowInfo.set(near, far, 0, 1.0 - mainLight.shadowSaturation);
                    Vec4.toArray(sv, _vec4ShadowInfo, UBOShadow.SHADOW_NEAR_FAR_LINEAR_SATURATION_INFO_OFFSET);
                    _vec4ShadowInfo.set(LightType.DIRECTIONAL, packing, mainLight.shadowNormalBias, levelCount);
                    Vec4.toArray(sv, _vec4ShadowInfo, UBOShadow.SHADOW_LIGHT_PACKING_NBIAS_NULL_INFO_OFFSET);
                    _vec4ShadowInfo.set(shadowInfo.size.x, shadowInfo.size.y, mainLight.shadowPcf, mainLight.shadowBias);
                    Vec4.toArray(sv, _vec4ShadowInfo, UBOShadow.SHADOW_WIDTH_HEIGHT_PCF_BIAS_INFO_OFFSET);
                  }
                }
                break;
              }
            case LightType.SPOT:
              {
                var spotLight = light;
                if (shadowInfo.enabled && spotLight && spotLight.shadowEnabled) {
                  Mat4.invert(_matShadowView$2, light.node.getWorldMatrix());
                  Mat4.toArray(sv, _matShadowView$2, UBOShadow.MAT_LIGHT_VIEW_OFFSET);
                  Mat4.perspective(_matShadowProj$1, spotLight.angle, 1.0, 0.001, spotLight.range, true, cap.clipSpaceMinZ, cap.clipSpaceSignY, 0);
                  Mat4.multiply(_matShadowViewProj$2, _matShadowProj$1, _matShadowView$2);
                  Mat4.toArray(sv, _matShadowViewProj$2, UBOShadow.MAT_LIGHT_VIEW_PROJ_OFFSET);
                  _vec4ShadowInfo.set(0.01, light.range, 0.0, 0.0);
                  Vec4.toArray(sv, _vec4ShadowInfo, UBOShadow.SHADOW_NEAR_FAR_LINEAR_SATURATION_INFO_OFFSET);
                  _vec4ShadowInfo.set(shadowInfo.size.x, shadowInfo.size.y, spotLight.shadowPcf, spotLight.shadowBias);
                  Vec4.toArray(sv, _vec4ShadowInfo, UBOShadow.SHADOW_WIDTH_HEIGHT_PCF_BIAS_INFO_OFFSET);
                  _vec4ShadowInfo.set(LightType.SPOT, packing, spotLight.shadowNormalBias, 0.0);
                  Vec4.toArray(sv, _vec4ShadowInfo, UBOShadow.SHADOW_LIGHT_PACKING_NBIAS_NULL_INFO_OFFSET);
                }
                break;
              }
          }
          Color$1.toArray(sv, shadowInfo.shadowColor, UBOShadow.SHADOW_COLOR_OFFSET);
        };
        PipelineUBO.getCombineSignY = function getCombineSignY() {
          return PipelineUBO._combineSignY;
        };
        var _proto = PipelineUBO.prototype;
        _proto._initCombineSignY = function _initCombineSignY() {
          var device = this._device;
          PipelineUBO._combineSignY = device.capabilities.screenSpaceSignY * 0.5 + 0.5 << 1 | device.capabilities.clipSpaceSignY * 0.5 + 0.5;
        };
        _proto.activate = function activate(device, pipeline) {
          this._device = device;
          this._pipeline = pipeline;
          var ds = this._pipeline.descriptorSet;
          if (isEnableEffect()) {
            return;
          }
          this._initCombineSignY();
          var globalUBO = device.createBuffer(new BufferInfo(BufferUsageBit.UNIFORM | BufferUsageBit.TRANSFER_DST, MemoryUsageBit.HOST | MemoryUsageBit.DEVICE, UBOGlobal.SIZE, UBOGlobal.SIZE));
          ds.bindBuffer(UBOGlobal.BINDING, globalUBO);
          var cameraUBO = device.createBuffer(new BufferInfo(BufferUsageBit.UNIFORM | BufferUsageBit.TRANSFER_DST, MemoryUsageBit.HOST | MemoryUsageBit.DEVICE, UBOCamera.SIZE, UBOCamera.SIZE));
          ds.bindBuffer(UBOCamera.BINDING, cameraUBO);
          var shadowUBO = device.createBuffer(new BufferInfo(BufferUsageBit.UNIFORM | BufferUsageBit.TRANSFER_DST, MemoryUsageBit.HOST | MemoryUsageBit.DEVICE, UBOShadow.SIZE, UBOShadow.SIZE));
          var binding = isEnableEffect() ? getDescBindingFromName('CCShadow') : UBOShadow.BINDING;
          ds.bindBuffer(binding, shadowUBO);
          var csmUBO = device.createBuffer(new BufferInfo(BufferUsageBit.UNIFORM | BufferUsageBit.TRANSFER_DST, MemoryUsageBit.HOST | MemoryUsageBit.DEVICE, UBOCSM.SIZE, UBOCSM.SIZE));
          var csmBinding = isEnableEffect() ? getDescBindingFromName('CCCSM') : UBOCSM.BINDING;
          ds.bindBuffer(csmBinding, csmUBO);
        };
        _proto.updateGlobalUBO = function updateGlobalUBO(window) {
          var globalDSManager = this._pipeline.globalDSManager;
          var ds = this._pipeline.descriptorSet;
          var cmdBuffer = this._pipeline.commandBuffers;
          ds.update();
          PipelineUBO.updateGlobalUBOView(window, this._globalUBO);
          cmdBuffer[0].updateBuffer(ds.getBuffer(UBOGlobal.BINDING), this._globalUBO);
          globalDSManager.bindBuffer(UBOGlobal.BINDING, ds.getBuffer(UBOGlobal.BINDING));
          globalDSManager.update();
        };
        _proto.updateCameraUBO = function updateCameraUBO(camera) {
          var globalDSManager = this._pipeline.globalDSManager;
          var ds = this._pipeline.descriptorSet;
          var cmdBuffer = this._pipeline.commandBuffers;
          PipelineUBO.updateCameraUBOView(this._pipeline, this._cameraUBO, camera);
          cmdBuffer[0].updateBuffer(ds.getBuffer(UBOCamera.BINDING), this._cameraUBO);
          globalDSManager.bindBuffer(UBOCamera.BINDING, ds.getBuffer(UBOCamera.BINDING));
          globalDSManager.update();
        };
        _proto.updateShadowUBO = function updateShadowUBO(camera) {
          var sceneData = this._pipeline.pipelineSceneData;
          var shadowInfo = sceneData.shadows;
          if (!shadowInfo.enabled) return;
          var ds = this._pipeline.descriptorSet;
          var cmdBuffer = this._pipeline.commandBuffers;
          var shadowFrameBufferMap = sceneData.shadowFrameBufferMap;
          var mainLight = camera.scene.mainLight;
          if (mainLight && shadowFrameBufferMap.has(mainLight)) {
            ds.bindTexture(UNIFORM_SHADOWMAP_BINDING, shadowFrameBufferMap.get(mainLight).colorTextures[0]);
          }
          PipelineUBO.updateShadowUBOView(this._pipeline, this._shadowUBO, this._csmUBO, camera);
          ds.update();
          var binding = isEnableEffect() ? getDescBindingFromName('CCShadow') : UBOShadow.BINDING;
          cmdBuffer[0].updateBuffer(ds.getBuffer(binding), this._shadowUBO);
          var csmBinding = isEnableEffect() ? getDescBindingFromName('CCCSM') : UBOCSM.BINDING;
          cmdBuffer[0].updateBuffer(ds.getBuffer(csmBinding), this._csmUBO);
        };
        _proto.updateShadowUBOLight = function updateShadowUBOLight(globalDS, light, level) {
          if (level === void 0) {
            level = 0;
          }
          PipelineUBO.updateShadowUBOLightView(this._pipeline, this._shadowUBO, light, level);
          globalDS.bindTexture(UNIFORM_SHADOWMAP_BINDING, builtinResMgr.get('default-texture').getGFXTexture());
          globalDS.bindTexture(UNIFORM_SPOT_SHADOW_MAP_TEXTURE_BINDING, builtinResMgr.get('default-texture').getGFXTexture());
          globalDS.update();
          var binding = isEnableEffect() ? getDescBindingFromName('CCShadow') : UBOShadow.BINDING;
          this._pipeline.commandBuffers[0].updateBuffer(globalDS.getBuffer(binding), this._shadowUBO);
        };
        _proto.updateShadowUBORange = function updateShadowUBORange(offset, data) {
          if (data instanceof Mat4) {
            Mat4.toArray(this._shadowUBO, data, offset);
          } else if (data instanceof Color$1) {
            Color$1.toArray(this._shadowUBO, data, offset);
          }
        };
        _proto.destroy = function destroy() {};
        return PipelineUBO;
      }();
      PipelineUBO._combineSignY = 0;

      var _dec$2J, _class$2F, _class2$2q, _initializer$2a, _initializer2$1H, _initializer3$17;
      var RenderStage = exports('d5', (_dec$2J = ccclass$n('RenderStage'), _dec$2J(_class$2F = (_class2$2q = function () {
        function RenderStage() {
          this._name = _initializer$2a && _initializer$2a();
          this._priority = _initializer2$1H && _initializer2$1H();
          this._enabled = true;
          this._tag = _initializer3$17 && _initializer3$17();
          this._pipeline = void 0;
          this._flow = void 0;
        }
        var _proto = RenderStage.prototype;
        _proto.initialize = function initialize(info) {
          this._name = info.name;
          this._priority = info.priority;
          if (info.tag) {
            this._tag = info.tag;
          }
          return true;
        };
        _proto.activate = function activate(pipeline, flow) {
          this._pipeline = pipeline;
          this._flow = flow;
        };
        _createClass(RenderStage, [{
          key: "name",
          get: function get() {
            return this._name;
          }
        }, {
          key: "priority",
          get: function get() {
            return this._priority;
          }
        }, {
          key: "tag",
          get: function get() {
            return this._tag;
          }
        }, {
          key: "enabled",
          get: function get() {
            return this._enabled;
          },
          set: function set(val) {
            this._enabled = val;
          }
        }]);
        return RenderStage;
      }(), (_initializer$2a = applyDecoratedInitializer(_class2$2q.prototype, "_name", [serializable$j], function () {
        return '';
      }), _initializer2$1H = applyDecoratedInitializer(_class2$2q.prototype, "_priority", [serializable$j], function () {
        return 0;
      }), _initializer3$17 = applyDecoratedInitializer(_class2$2q.prototype, "_tag", [serializable$j], function () {
        return 0;
      })), _class2$2q)) || _class$2F));
      legacyCC.RenderStage = RenderStage;

      var _dec$2I, _dec2$1$, _class$2E, _class2$2p, _initializer$29, _initializer2$1G, _initializer3$16, _initializer4$S;
      var RenderFlow = exports('d4', (_dec$2I = ccclass$n('RenderFlow'), _dec2$1$ = type$7([RenderStage]), _dec$2I(_class$2E = (_class2$2p = function () {
        function RenderFlow() {
          this._name = _initializer$29 && _initializer$29();
          this._priority = _initializer2$1G && _initializer2$1G();
          this._tag = _initializer3$16 && _initializer3$16();
          this._stages = _initializer4$S && _initializer4$S();
          this._pipeline = void 0;
        }
        var _proto = RenderFlow.prototype;
        _proto.initialize = function initialize(info) {
          this._name = info.name;
          this._priority = info.priority;
          this._stages = info.stages;
          if (info.tag) {
            this._tag = info.tag;
          }
          return true;
        };
        _proto.activate = function activate(pipeline) {
          this._pipeline = pipeline;
          this._stages.sort(function (a, b) {
            return a.priority - b.priority;
          });
          for (var i = 0, len = this._stages.length; i < len; i++) {
            this._stages[i].activate(pipeline, this);
          }
        };
        _proto.render = function render(camera) {
          for (var i = 0, len = this._stages.length; i < len; i++) {
            if (this._stages[i].enabled) this._stages[i].render(camera);
          }
        };
        _proto.destroy = function destroy() {
          for (var i = 0, len = this._stages.length; i < len; i++) {
            this._stages[i].destroy();
          }
          this._stages.length = 0;
        };
        _createClass(RenderFlow, [{
          key: "name",
          get: function get() {
            return this._name;
          }
        }, {
          key: "priority",
          get: function get() {
            return this._priority;
          }
        }, {
          key: "tag",
          get: function get() {
            return this._tag;
          }
        }, {
          key: "stages",
          get: function get() {
            return this._stages;
          }
        }, {
          key: "pipeline",
          get: function get() {
            return this._pipeline;
          }
        }]);
        return RenderFlow;
      }(), (_initializer$29 = applyDecoratedInitializer(_class2$2p.prototype, "_name", [serializable$j], function () {
        return '';
      }), _initializer2$1G = applyDecoratedInitializer(_class2$2p.prototype, "_priority", [serializable$j], function () {
        return 0;
      }), _initializer3$16 = applyDecoratedInitializer(_class2$2p.prototype, "_tag", [serializable$j], function () {
        return 0;
      }), _initializer4$S = applyDecoratedInitializer(_class2$2p.prototype, "_stages", [_dec2$1$, serializable$j], function () {
        return [];
      })), _class2$2p)) || _class$2E));
      legacyCC.RenderFlow = RenderFlow;

      var PipelineEventType; exports('dm', PipelineEventType);
      (function (PipelineEventType) {
        PipelineEventType["RENDER_FRAME_BEGIN"] = "render-frame-begin";
        PipelineEventType["RENDER_FRAME_END"] = "render-frame-end";
        PipelineEventType["RENDER_CAMERA_BEGIN"] = "render-camera-begin";
        PipelineEventType["RENDER_CAMERA_END"] = "render-camera-end";
        PipelineEventType["ATTACHMENT_SCALE_CAHNGED"] = "attachment-scale-changed";
      })(PipelineEventType || (exports('dm', PipelineEventType = {})));
      var PipelineEventProcessor = exports('dl', function (_EventTarget) {
        _inheritsLoose(PipelineEventProcessor, _EventTarget);
        function PipelineEventProcessor() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _EventTarget.call.apply(_EventTarget, [this].concat(args)) || this;
          _this.eventTargetOn = _EventTarget.prototype.on;
          _this.eventTargetOnce = _EventTarget.prototype.once;
          return _this;
        }
        var _proto = PipelineEventProcessor.prototype;
        _proto.on = function on(type, callback, target, once) {
          return this.eventTargetOn(type, callback, target, once);
        };
        _proto.once = function once(type, callback, target) {
          return this.eventTargetOnce(type, callback, target);
        };
        return PipelineEventProcessor;
      }(EventTarget));

      var _dec$2H, _dec2$1_, _class4$t, _class5$u, _initializer$28, _initializer2$1F;
      var MAX_BLOOM_FILTER_PASS_NUM = 6;
      var tmpRect = new Rect();
      var tmpViewport = new Viewport();
      var BloomRenderData = function BloomRenderData() {
        this.renderPass = null;
        this.sampler = null;
        this.prefiterTex = null;
        this.downsampleTexs = [];
        this.upsampleTexs = [];
        this.combineTex = null;
        this.prefilterFramebuffer = null;
        this.downsampleFramebuffers = [];
        this.upsampleFramebuffers = [];
        this.combineFramebuffer = null;
      };
      var PipelineRenderData = function PipelineRenderData() {
        this.outputFrameBuffer = null;
        this.outputRenderTargets = [];
        this.outputDepth = null;
        this.sampler = null;
        this.bloom = null;
      };
      var PipelineInputAssemblerData = function PipelineInputAssemblerData() {
        this.quadIB = null;
        this.quadVB = null;
        this.quadIA = null;
      };
      function hashFrameBuffer(fbo) {
        var hash = 666;
        for (var _iterator = _createForOfIteratorHelperLoose(fbo.colorTextures), _step; !(_step = _iterator()).done;) {
          var color = _step.value;
          var _info = color === null || color === void 0 ? void 0 : color.info;
          var _hashStr = _info.type + "_" + _info.usage + "_" + _info.format + "_" + _info.width + "_" + _info.height + "_" + _info.flags + "_\n            " + _info.layerCount + "_" + _info.levelCount + "_" + _info.samples + "_" + _info.depth + "_" + _info.externalRes;
          hash = murmurhash2_32_gc(_hashStr, hash);
        }
        if (fbo.depthStencilTexture) {
          var info = fbo.depthStencilTexture.info;
          var hashStr = info.type + "_" + info.usage + "_" + info.format + "_" + info.width + "_" + info.height + "_" + info.flags + "_\n            " + info.layerCount + "_" + info.levelCount + "_" + info.samples + "_" + info.depth + "_" + info.externalRes;
          hash = murmurhash2_32_gc(hashStr, hash);
        }
        return hash;
      }
      var RenderPipeline = exports('d3', (_dec$2H = ccclass$n('cc.RenderPipeline'), _dec2$1_ = type$7([RenderFlow]), _dec$2H(_class4$t = (_class5$u = function (_Asset) {
        _inheritsLoose(RenderPipeline, _Asset);
        function RenderPipeline() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Asset.call.apply(_Asset, [this].concat(args)) || this;
          _this._tag = _initializer$28 && _initializer$28();
          _this._flows = _initializer2$1F && _initializer2$1F();
          _this._quadIB = null;
          _this._quadVBOnscreen = null;
          _this._quadVBOffscreen = null;
          _this._quadIAOnscreen = null;
          _this._quadIAOffscreen = null;
          _this._eventProcessor = new PipelineEventProcessor();
          _this._device = void 0;
          _this._globalDSManager = void 0;
          _this._descriptorSet = void 0;
          _this._commandBuffers = [];
          _this._pipelineUBO = new PipelineUBO();
          _this._macros = {};
          _this._constantMacros = '';
          _this._profiler = null;
          _this._geometryRenderer = null;
          _this._pipelineRenderData = null;
          _this._renderPasses = new Map();
          _this._width = 0;
          _this._height = 0;
          _this._lastUsedRenderArea = new Rect();
          _this._clusterEnabled = false;
          _this._bloomEnabled = false;
          return _this;
        }
        var _proto = RenderPipeline.prototype;
        _proto.getPipelineRenderData = function getPipelineRenderData() {
          return this._pipelineRenderData;
        };
        _proto.initialize = function initialize(info) {
          this._flows = info.flows;
          if (info.tag) {
            this._tag = info.tag;
          }
          return true;
        };
        _proto.createRenderPass = function createRenderPass(clearFlags, colorFmt, depthFmt) {
          var device = this._device;
          var colorAttachment = new ColorAttachment();
          var depthStencilAttachment = new DepthStencilAttachment();
          colorAttachment.format = colorFmt;
          depthStencilAttachment.format = depthFmt;
          depthStencilAttachment.stencilStoreOp = StoreOp.DISCARD;
          depthStencilAttachment.depthStoreOp = StoreOp.DISCARD;
          if (!(clearFlags & ClearFlagBit.COLOR)) {
            if (clearFlags & SKYBOX_FLAG) {
              colorAttachment.loadOp = LoadOp.CLEAR;
            } else {
              colorAttachment.loadOp = LoadOp.LOAD;
              colorAttachment.barrier = device.getGeneralBarrier(new GeneralBarrierInfo(AccessFlagBit.COLOR_ATTACHMENT_WRITE, AccessFlagBit.COLOR_ATTACHMENT_WRITE));
            }
          }
          if ((clearFlags & ClearFlagBit.DEPTH_STENCIL) !== ClearFlagBit.DEPTH_STENCIL) {
            if (!(clearFlags & ClearFlagBit.DEPTH)) depthStencilAttachment.depthLoadOp = LoadOp.LOAD;
            if (!(clearFlags & ClearFlagBit.STENCIL)) depthStencilAttachment.stencilLoadOp = LoadOp.LOAD;
          }
          depthStencilAttachment.barrier = device.getGeneralBarrier(new GeneralBarrierInfo(AccessFlagBit.DEPTH_STENCIL_ATTACHMENT_WRITE, AccessFlagBit.DEPTH_STENCIL_ATTACHMENT_WRITE));
          var renderPassInfo = new RenderPassInfo([colorAttachment], depthStencilAttachment);
          return device.createRenderPass(renderPassInfo);
        };
        _proto.getRenderPass = function getRenderPass(clearFlags, fbo) {
          var fbHash = hashFrameBuffer(fbo);
          var hash = murmurhash2_32_gc(fbHash + "_" + clearFlags, 666);
          var renderPass = this._renderPasses.get(hash);
          if (renderPass) {
            return renderPass;
          }
          renderPass = this.createRenderPass(clearFlags, fbo.colorTextures[0].format, fbo.depthStencilTexture.format);
          this._renderPasses.set(hash, renderPass);
          return renderPass;
        };
        _proto.newFramebufferByRatio = function newFramebufferByRatio(dyingFramebuffer) {
          var sceneData = this.pipelineSceneData;
          var width = this._width * sceneData.shadingScale;
          var height = this._height * sceneData.shadingScale;
          var colorTexArr = dyingFramebuffer.colorTextures;
          for (var i = 0; i < colorTexArr.length; i++) {
            colorTexArr[i].resize(width, height);
          }
          if (dyingFramebuffer.depthStencilTexture) {
            dyingFramebuffer.depthStencilTexture.resize(width, height);
          }
          var newFramebuffer = this._device.createFramebuffer(new FramebufferInfo(dyingFramebuffer.renderPass, colorTexArr, dyingFramebuffer.depthStencilTexture));
          dyingFramebuffer.destroy();
          return newFramebuffer;
        };
        _proto.generateRenderArea = function generateRenderArea(camera, out) {
          var vp = camera.viewport;
          var w = camera.window.width;
          var h = camera.window.height;
          out.x = vp.x * w;
          out.y = vp.y * h;
          out.width = vp.width * w;
          out.height = vp.height * h;
        };
        _proto.generateViewport = function generateViewport(camera, out) {
          this.generateRenderArea(camera, tmpRect);
          if (!out) out = tmpViewport;
          var shadingScale = this.pipelineSceneData.shadingScale;
          out.left = tmpRect.x * shadingScale;
          out.top = tmpRect.y * shadingScale;
          out.width = tmpRect.width * shadingScale;
          out.height = tmpRect.height * shadingScale;
          return out;
        };
        _proto.generateScissor = function generateScissor(camera, out) {
          if (!out) out = tmpRect;
          this.generateRenderArea(camera, out);
          var shadingScale = this.pipelineSceneData.shadingScale;
          out.x *= shadingScale;
          out.y *= shadingScale;
          out.width *= shadingScale;
          out.height *= shadingScale;
          return out;
        };
        _proto.getMacroString = function getMacroString(name) {
          var str = this._macros[name];
          if (str === undefined) {
            return '';
          }
          return str;
        };
        _proto.getMacroInt = function getMacroInt(name) {
          var value = this._macros[name];
          if (value === undefined) {
            return 0;
          }
          return value;
        };
        _proto.getMacroBool = function getMacroBool(name) {
          var value = this._macros[name];
          if (value === undefined) {
            return false;
          }
          return value;
        };
        _proto.setMacroString = function setMacroString(name, value) {
          this._macros[name] = value;
        };
        _proto.setMacroInt = function setMacroInt(name, value) {
          this._macros[name] = value;
        };
        _proto.setMacroBool = function setMacroBool(name, value) {
          this._macros[name] = value;
        };
        _proto.activate = function activate(swapchain) {
          this._device = deviceManager.gfxDevice;
          this._generateConstantMacros();
          this._globalDSManager = new GlobalDSManager(this._device);
          this._descriptorSet = this._globalDSManager.globalDescriptorSet;
          this._pipelineUBO.activate(this._device, this);
          this._macros.CC_USE_HDR = this._pipelineSceneData.isHDR;
          this._macros.CC_USE_DEBUG_VIEW = 0;
          this._generateConstantMacros();
          this._pipelineSceneData.activate(this._device);
          for (var i = 0; i < this._flows.length; i++) {
            this._flows[i].activate(this);
          }
          return true;
        };
        _proto._ensureEnoughSize = function _ensureEnoughSize(cameras) {};
        _proto.render = function render(cameras) {
          if (cameras.length === 0) {
            return;
          }
          this.updateGeometryRenderer(cameras);
          this._commandBuffers[0].begin();
          this.emit(PipelineEventType.RENDER_FRAME_BEGIN, cameras);
          this._ensureEnoughSize(cameras);
          decideProfilerCamera(cameras);
          for (var i = 0; i < cameras.length; i++) {
            var camera = cameras[i];
            if (camera.scene) {
              this.emit(PipelineEventType.RENDER_CAMERA_BEGIN, camera);
              validPunctualLightsCulling$1(this, camera);
              sceneCulling(this, camera);
              this._pipelineUBO.updateGlobalUBO(camera.window);
              this._pipelineUBO.updateCameraUBO(camera);
              for (var j = 0; j < this._flows.length; j++) {
                this._flows[j].render(camera);
              }
              this.emit(PipelineEventType.RENDER_CAMERA_END, camera);
            }
          }
          this.emit(PipelineEventType.RENDER_FRAME_END, cameras);
          this._commandBuffers[0].end();
          this._device.queue.submit(this._commandBuffers);
        };
        _proto._destroyQuadInputAssembler = function _destroyQuadInputAssembler() {
          if (this._quadIB) {
            this._quadIB.destroy();
            this._quadIB = null;
          }
          if (this._quadVBOnscreen) {
            this._quadVBOnscreen.destroy();
            this._quadVBOnscreen = null;
          }
          if (this._quadVBOffscreen) {
            this._quadVBOffscreen.destroy();
            this._quadVBOffscreen = null;
          }
          if (this._quadIAOnscreen) {
            this._quadIAOnscreen.destroy();
            this._quadIAOnscreen = null;
          }
          if (this._quadIAOffscreen) {
            this._quadIAOffscreen.destroy();
            this._quadIAOffscreen = null;
          }
        };
        _proto._destroyBloomData = function _destroyBloomData() {
          var _bloom$renderPass;
          var bloom = this._pipelineRenderData.bloom;
          if (bloom === null) return;
          if (bloom.prefiterTex) bloom.prefiterTex.destroy();
          if (bloom.prefilterFramebuffer) bloom.prefilterFramebuffer.destroy();
          for (var i = 0; i < bloom.downsampleTexs.length; ++i) {
            bloom.downsampleTexs[i].destroy();
            bloom.downsampleFramebuffers[i].destroy();
          }
          bloom.downsampleTexs.length = 0;
          bloom.downsampleFramebuffers.length = 0;
          for (var _i = 0; _i < bloom.upsampleTexs.length; ++_i) {
            bloom.upsampleTexs[_i].destroy();
            bloom.upsampleFramebuffers[_i].destroy();
          }
          bloom.upsampleTexs.length = 0;
          bloom.upsampleFramebuffers.length = 0;
          if (bloom.combineTex) bloom.combineTex.destroy();
          if (bloom.combineFramebuffer) bloom.combineFramebuffer.destroy();
          (_bloom$renderPass = bloom.renderPass) === null || _bloom$renderPass === void 0 ? void 0 : _bloom$renderPass.destroy();
          this._pipelineRenderData.bloom = null;
        };
        _proto._genQuadVertexData = function _genQuadVertexData(surfaceTransform, renderArea) {
          var vbData = new Float32Array(4 * 4);
          var minX = renderArea.x / this._width;
          var maxX = (renderArea.x + renderArea.width) / this._width;
          var minY = renderArea.y / this._height;
          var maxY = (renderArea.y + renderArea.height) / this._height;
          if (this.device.capabilities.screenSpaceSignY > 0) {
            var temp = maxY;
            maxY = minY;
            minY = temp;
          }
          var n = 0;
          switch (surfaceTransform) {
            case SurfaceTransform.IDENTITY:
              n = 0;
              vbData[n++] = -1.0;
              vbData[n++] = -1.0;
              vbData[n++] = minX;
              vbData[n++] = maxY;
              vbData[n++] = 1.0;
              vbData[n++] = -1.0;
              vbData[n++] = maxX;
              vbData[n++] = maxY;
              vbData[n++] = -1.0;
              vbData[n++] = 1.0;
              vbData[n++] = minX;
              vbData[n++] = minY;
              vbData[n++] = 1.0;
              vbData[n++] = 1.0;
              vbData[n++] = maxX;
              vbData[n++] = minY;
              break;
            case SurfaceTransform.ROTATE_90:
              n = 0;
              vbData[n++] = -1.0;
              vbData[n++] = -1.0;
              vbData[n++] = maxX;
              vbData[n++] = maxY;
              vbData[n++] = 1.0;
              vbData[n++] = -1.0;
              vbData[n++] = maxX;
              vbData[n++] = minY;
              vbData[n++] = -1.0;
              vbData[n++] = 1.0;
              vbData[n++] = minX;
              vbData[n++] = maxY;
              vbData[n++] = 1.0;
              vbData[n++] = 1.0;
              vbData[n++] = minX;
              vbData[n++] = minY;
              break;
            case SurfaceTransform.ROTATE_180:
              n = 0;
              vbData[n++] = -1.0;
              vbData[n++] = -1.0;
              vbData[n++] = minX;
              vbData[n++] = minY;
              vbData[n++] = 1.0;
              vbData[n++] = -1.0;
              vbData[n++] = maxX;
              vbData[n++] = minY;
              vbData[n++] = -1.0;
              vbData[n++] = 1.0;
              vbData[n++] = minX;
              vbData[n++] = maxY;
              vbData[n++] = 1.0;
              vbData[n++] = 1.0;
              vbData[n++] = maxX;
              vbData[n++] = maxY;
              break;
            case SurfaceTransform.ROTATE_270:
              n = 0;
              vbData[n++] = -1.0;
              vbData[n++] = -1.0;
              vbData[n++] = minX;
              vbData[n++] = minY;
              vbData[n++] = 1.0;
              vbData[n++] = -1.0;
              vbData[n++] = minX;
              vbData[n++] = maxY;
              vbData[n++] = -1.0;
              vbData[n++] = 1.0;
              vbData[n++] = maxX;
              vbData[n++] = minY;
              vbData[n++] = 1.0;
              vbData[n++] = 1.0;
              vbData[n++] = maxX;
              vbData[n++] = maxY;
              break;
          }
          return vbData;
        };
        _proto._createQuadInputAssembler = function _createQuadInputAssembler() {
          var inputAssemblerData = new PipelineInputAssemblerData();
          var vbStride = Float32Array.BYTES_PER_ELEMENT * 4;
          var vbSize = vbStride * 4;
          var quadVB = this._device.createBuffer(new BufferInfo(BufferUsageBit.VERTEX | BufferUsageBit.TRANSFER_DST, MemoryUsageBit.DEVICE | MemoryUsageBit.HOST, vbSize, vbStride));
          if (!quadVB) {
            return inputAssemblerData;
          }
          var ibStride = Uint8Array.BYTES_PER_ELEMENT;
          var ibSize = ibStride * 6;
          var quadIB = this._device.createBuffer(new BufferInfo(BufferUsageBit.INDEX | BufferUsageBit.TRANSFER_DST, MemoryUsageBit.DEVICE, ibSize, ibStride));
          if (!quadIB) {
            return inputAssemblerData;
          }
          var indices = new Uint8Array(6);
          indices[0] = 0;
          indices[1] = 1;
          indices[2] = 2;
          indices[3] = 1;
          indices[4] = 3;
          indices[5] = 2;
          quadIB.update(indices);
          var attributes = new Array(2);
          attributes[0] = new Attribute('a_position', Format.RG32F);
          attributes[1] = new Attribute('a_texCoord', Format.RG32F);
          var quadIA = this._device.createInputAssembler(new InputAssemblerInfo(attributes, [quadVB], quadIB));
          inputAssemblerData.quadIB = quadIB;
          inputAssemblerData.quadVB = quadVB;
          inputAssemblerData.quadIA = quadIA;
          return inputAssemblerData;
        };
        _proto.updateQuadVertexData = function updateQuadVertexData(renderArea, window) {
          var cachedArea = this._lastUsedRenderArea;
          if (cachedArea.x === renderArea.x && cachedArea.y === renderArea.y && cachedArea.width === renderArea.width && cachedArea.height === renderArea.height) {
            return;
          }
          var offData = this._genQuadVertexData(SurfaceTransform.IDENTITY, renderArea);
          this._quadVBOffscreen.update(offData);
          var onData = this._genQuadVertexData(window.swapchain && window.swapchain.surfaceTransform || SurfaceTransform.IDENTITY, renderArea);
          this._quadVBOnscreen.update(onData);
          cachedArea.copy(renderArea);
        };
        _proto.destroy = function destroy() {
          var _this$_globalDSManage, _this$_pipelineSceneD;
          for (var i = 0; i < this._flows.length; i++) {
            this._flows[i].destroy();
          }
          this._flows.length = 0;
          if (this._descriptorSet) {
            this._descriptorSet.destroy();
          }
          (_this$_globalDSManage = this._globalDSManager) === null || _this$_globalDSManage === void 0 ? void 0 : _this$_globalDSManage.destroy();
          for (var _i2 = 0; _i2 < this._commandBuffers.length; _i2++) {
            this._commandBuffers[_i2].destroy();
          }
          this._commandBuffers.length = 0;
          this._pipelineUBO.destroy();
          (_this$_pipelineSceneD = this._pipelineSceneData) === null || _this$_pipelineSceneD === void 0 ? void 0 : _this$_pipelineSceneD.destroy();
          return _Asset.prototype.destroy.call(this);
        };
        _proto.onGlobalPipelineStateChanged = function onGlobalPipelineStateChanged() {};
        _proto._generateConstantMacros = function _generateConstantMacros() {
          var str = '';
          str += "#define CC_DEVICE_SUPPORT_FLOAT_TEXTURE " + (this.device.getFormatFeatures(Format.RGBA32F) & (FormatFeatureBit.RENDER_TARGET | FormatFeatureBit.SAMPLED_TEXTURE) ? 1 : 0) + "\n";
          str += "#define CC_ENABLE_CLUSTERED_LIGHT_CULLING " + (this._clusterEnabled ? 1 : 0) + "\n";
          str += "#define CC_DEVICE_MAX_VERTEX_UNIFORM_VECTORS " + this.device.capabilities.maxVertexUniformVectors + "\n";
          str += "#define CC_DEVICE_MAX_FRAGMENT_UNIFORM_VECTORS " + this.device.capabilities.maxFragmentUniformVectors + "\n";
          str += "#define CC_DEVICE_CAN_BENEFIT_FROM_INPUT_ATTACHMENT " + (this.device.hasFeature(Feature.INPUT_ATTACHMENT_BENEFIT) ? 1 : 0) + "\n";
          str += "#define CC_PLATFORM_ANDROID_AND_WEBGL " + (systemInfo.os === OS.ANDROID && systemInfo.isBrowser ? 1 : 0) + "\n";
          str += "#define CC_ENABLE_WEBGL_HIGHP_STRUCT_VALUES " + (macro.ENABLE_WEBGL_HIGHP_STRUCT_VALUES ? 1 : 0) + "\n";
          var jointUniformCapacity = UBOSkinning.JOINT_UNIFORM_CAPACITY;
          str += "#define CC_JOINT_UNIFORM_CAPACITY " + jointUniformCapacity + "\n";
          this._constantMacros = str;
        };
        _proto.updateGeometryRenderer = function updateGeometryRenderer(cameras) {
          if (this._geometryRenderer) {
            return;
          }
          for (var i = 0; i < cameras.length; i++) {
            var camera = cameras[i];
            if (camera && camera.window && camera.window.swapchain) {
              camera.initGeometryRenderer();
              this._geometryRenderer = camera.geometryRenderer;
              return;
            }
          }
        };
        _proto.generateBloomRenderData = function generateBloomRenderData() {
          if (this._pipelineRenderData.bloom != null) return;
          var bloom = this._pipelineRenderData.bloom = new BloomRenderData();
          var device = this.device;
          var colorAttachment = new ColorAttachment();
          colorAttachment.format = Format.RGBA8;
          colorAttachment.loadOp = LoadOp.CLEAR;
          colorAttachment.storeOp = StoreOp.STORE;
          colorAttachment.barrier = device.getGeneralBarrier(new GeneralBarrierInfo(AccessFlagBit.NONE, AccessFlagBit.COLOR_ATTACHMENT_WRITE));
          bloom.renderPass = device.createRenderPass(new RenderPassInfo([colorAttachment]));
          var curWidth = this._width;
          var curHeight = this._height;
          bloom.prefiterTex = device.createTexture(new TextureInfo(TextureType.TEX2D, TextureUsageBit.COLOR_ATTACHMENT | TextureUsageBit.SAMPLED, Format.RGBA8, curWidth >> 1, curHeight >> 1));
          bloom.prefilterFramebuffer = device.createFramebuffer(new FramebufferInfo(bloom.renderPass, [bloom.prefiterTex]));
          curWidth >>= 1;
          curHeight >>= 1;
          for (var i = 0; i < MAX_BLOOM_FILTER_PASS_NUM; ++i) {
            bloom.downsampleTexs.push(device.createTexture(new TextureInfo(TextureType.TEX2D, TextureUsageBit.COLOR_ATTACHMENT | TextureUsageBit.SAMPLED, Format.RGBA8, curWidth >> 1, curHeight >> 1)));
            bloom.downsampleFramebuffers[i] = device.createFramebuffer(new FramebufferInfo(bloom.renderPass, [bloom.downsampleTexs[i]]));
            bloom.upsampleTexs.push(device.createTexture(new TextureInfo(TextureType.TEX2D, TextureUsageBit.COLOR_ATTACHMENT | TextureUsageBit.SAMPLED, Format.RGBA8, curWidth, curHeight)));
            bloom.upsampleFramebuffers[i] = device.createFramebuffer(new FramebufferInfo(bloom.renderPass, [bloom.upsampleTexs[i]]));
            curWidth >>= 1;
            curHeight >>= 1;
          }
          bloom.combineTex = device.createTexture(new TextureInfo(TextureType.TEX2D, TextureUsageBit.COLOR_ATTACHMENT | TextureUsageBit.SAMPLED, Format.RGBA8, this._width, this._height));
          bloom.combineFramebuffer = device.createFramebuffer(new FramebufferInfo(bloom.renderPass, [bloom.combineTex]));
          bloom.sampler = this.globalDSManager.linearSampler;
        };
        _proto.on = function on(type, callback, target, once) {
          return this._eventProcessor.on(type, callback, target, once);
        };
        _proto.once = function once(type, callback, target) {
          return this._eventProcessor.once(type, callback, target);
        };
        _proto.off = function off(type, callback, target) {
          this._eventProcessor.off(type, callback, target);
        };
        _proto.emit = function emit(type, arg0, arg1, arg2, arg3, arg4) {
          this._eventProcessor.emit(type, arg0, arg1, arg2, arg3, arg4);
        };
        _proto.targetOff = function targetOff(typeOrTarget) {
          this._eventProcessor.targetOff(typeOrTarget);
        };
        _proto.removeAll = function removeAll(typeOrTarget) {
          this._eventProcessor.removeAll(typeOrTarget);
        };
        _proto.hasEventListener = function hasEventListener(type, callback, target) {
          return this._eventProcessor.hasEventListener(type, callback, target);
        };
        _createClass(RenderPipeline, [{
          key: "tag",
          get: function get() {
            return this._tag;
          }
        }, {
          key: "flows",
          get: function get() {
            return this._flows;
          }
        }, {
          key: "quadIAOnscreen",
          get: function get() {
            return this._quadIAOnscreen;
          }
        }, {
          key: "quadIAOffscreen",
          get: function get() {
            return this._quadIAOffscreen;
          }
        }, {
          key: "constantMacros",
          get: function get() {
            return this._constantMacros;
          }
        }, {
          key: "macros",
          get: function get() {
            return this._macros;
          }
        }, {
          key: "device",
          get: function get() {
            return this._device;
          }
        }, {
          key: "globalDSManager",
          get: function get() {
            return this._globalDSManager;
          }
        }, {
          key: "descriptorSetLayout",
          get: function get() {
            return this._globalDSManager.descriptorSetLayout;
          }
        }, {
          key: "descriptorSet",
          get: function get() {
            return this._descriptorSet;
          }
        }, {
          key: "commandBuffers",
          get: function get() {
            return this._commandBuffers;
          }
        }, {
          key: "pipelineUBO",
          get: function get() {
            return this._pipelineUBO;
          }
        }, {
          key: "pipelineSceneData",
          get: function get() {
            return this._pipelineSceneData;
          }
        }, {
          key: "profiler",
          get: function get() {
            return this._profiler;
          },
          set: function set(value) {
            this._profiler = value;
          }
        }, {
          key: "geometryRenderer",
          get: function get() {
            return this._geometryRenderer;
          }
        }, {
          key: "clusterEnabled",
          get: function get() {
            return this._clusterEnabled;
          },
          set: function set(value) {
            this._clusterEnabled = value;
          }
        }, {
          key: "bloomEnabled",
          get: function get() {
            return this._bloomEnabled;
          },
          set: function set(value) {
            this._bloomEnabled = value;
          }
        }, {
          key: "shadingScale",
          get: function get() {
            return this._pipelineSceneData.shadingScale;
          },
          set: function set(val) {
            if (this._pipelineSceneData.shadingScale !== val) {
              this._pipelineSceneData.shadingScale = val;
              this.emit(PipelineEventType.ATTACHMENT_SCALE_CAHNGED, val);
            }
          }
        }]);
        return RenderPipeline;
      }(Asset), (_initializer$28 = applyDecoratedInitializer(_class5$u.prototype, "_tag", [serializable$j], function () {
        return 0;
      }), _initializer2$1F = applyDecoratedInitializer(_class5$u.prototype, "_flows", [_dec2$1_, serializable$j], function () {
        return [];
      })), _class5$u)) || _class4$t));
      legacyCC.RenderPipeline = RenderPipeline;

      var Octree = function () {
        function Octree() {
          this._enabled = false;
          this._minPos = new Vec3(0, 0, 0);
          this._maxPos = new Vec3(0, 0, 0);
          this._depth = 0;
        }
        var _proto = Octree.prototype;
        _proto.initialize = function initialize(octreeInfo) {
          this._enabled = octreeInfo.enabled;
          this._minPos = octreeInfo.minPos;
          this._maxPos = octreeInfo.maxPos;
          this._depth = octreeInfo.depth;
        };
        _createClass(Octree, [{
          key: "enabled",
          get: function get() {
            return this._enabled;
          },
          set: function set(val) {
            this._enabled = val;
          }
        }, {
          key: "minPos",
          get: function get() {
            return this._minPos;
          },
          set: function set(val) {
            this._minPos = val;
          }
        }, {
          key: "maxPos",
          get: function get() {
            return this._maxPos;
          },
          set: function set(val) {
            this._maxPos = val;
          }
        }, {
          key: "depth",
          get: function get() {
            return this._depth;
          },
          set: function set(val) {
            this._depth = val;
          }
        }]);
        return Octree;
      }();

      var _mat4Trans = new Mat4();
      var _matShadowTrans = new Mat4();
      var _matShadowView$1 = new Mat4();
      var _matShadowProj = new Mat4();
      var _matShadowViewProj$1 = new Mat4();
      var _matShadowViewProjArbitaryPos = new Mat4();
      var _matShadowViewProjArbitaryPosInv = new Mat4();
      var _focus = new Vec3(0, 0, 0);
      var _projPos = new Vec3();
      var _texelSize = new Vec2();
      var _projSnap = new Vec3();
      var _snap = new Vec3();
      var _maxVec3 = new Vec3(10000000, 10000000, 10000000);
      var _minVec3 = new Vec3(-10000000, -10000000, -10000000);
      var _shadowPos = new Vec3();
      var _maxLayerPosz = 0.0;
      var _maxLayerFarPlane = 0.0;
      var ShadowLayerVolume = function () {
        function ShadowLayerVolume(level) {
          this._shadowObjects = [];
          this._shadowCameraFar = 0;
          this._level = void 0;
          this._matShadowView = new Mat4();
          this._matShadowProj = new Mat4();
          this._matShadowViewProj = new Mat4();
          this._validFrustum = new Frustum();
          this._splitFrustum = new Frustum();
          this._lightViewFrustum = new Frustum();
          this._castLightViewBoundingBox = new AABB();
          this._level = level;
          this._validFrustum.accurate = true;
          this._splitFrustum.accurate = true;
          this._lightViewFrustum.accurate = true;
        }
        var _proto = ShadowLayerVolume.prototype;
        _proto.copyToValidFrustum = function copyToValidFrustum(validFrustum) {
          Frustum.copy(this._validFrustum, validFrustum);
        };
        _proto.calculateValidFrustumOrtho = function calculateValidFrustumOrtho(width, height, near, far, transform) {
          Frustum.createOrtho(this._validFrustum, width, height, near, far, transform);
        };
        _proto.calculateSplitFrustum = function calculateSplitFrustum(camera, m, start, end) {
          this._splitFrustum.split(start, end, camera.aspect, camera.fov, m);
        };
        _proto.destroy = function destroy() {
          this._shadowObjects.length = 0;
        };
        _proto.createMatrix = function createMatrix(dirLight, shadowMapWidth, onlyForCulling) {
          var device = legacyCC.director.root.device;
          var invisibleOcclusionRange = dirLight.shadowInvisibleOcclusionRange;
          Frustum.copy(this._lightViewFrustum, this._splitFrustum);
          Mat4.fromRT(_matShadowTrans, dirLight.node.rotation, _focus);
          Mat4.invert(_matShadowView$1, _matShadowTrans);
          var shadowViewArbitaryPos = _matShadowView$1.clone();
          this._lightViewFrustum.transform(_matShadowView$1);
          AABB.fromPoints(this._castLightViewBoundingBox, _maxVec3, _minVec3);
          this._castLightViewBoundingBox.mergeFrustum(this._lightViewFrustum);
          var orthoSizeWidth;
          var orthoSizeHeight;
          if (dirLight.csmOptimizationMode === CSMOptimizationMode.DisableRotationFix) {
            orthoSizeWidth = this._castLightViewBoundingBox.halfExtents.x * 2.0;
            orthoSizeHeight = this._castLightViewBoundingBox.halfExtents.y * 2.0;
          } else {
            orthoSizeWidth = orthoSizeHeight = Vec3.distance(this._lightViewFrustum.vertices[0], this._lightViewFrustum.vertices[6]);
          }
          var csmLevel = legacyCC.director.root.pipeline.pipelineSceneData.csmSupported ? dirLight.csmLevel : 1;
          if (csmLevel > 1 && dirLight.csmOptimizationMode === CSMOptimizationMode.RemoveDuplicates) {
            if (this._level >= csmLevel - 1) {
              _maxLayerFarPlane = this._castLightViewBoundingBox.halfExtents.z;
              _maxLayerPosz = this._castLightViewBoundingBox.center.z;
            } else {
              var alignFarPlaneDist = Math.abs(this._castLightViewBoundingBox.center.z - _maxLayerPosz) + _maxLayerFarPlane;
              this._castLightViewBoundingBox.halfExtents.z = Math.max(this._castLightViewBoundingBox.center.z, alignFarPlaneDist);
            }
          }
          var r = this._castLightViewBoundingBox.halfExtents.z;
          this._shadowCameraFar = r * 2 + invisibleOcclusionRange;
          var center = this._castLightViewBoundingBox.center;
          _shadowPos.set(center.x, center.y, center.z + r + invisibleOcclusionRange);
          Vec3.transformMat4(_shadowPos, _shadowPos, _matShadowTrans);
          Mat4.fromRT(_matShadowTrans, dirLight.node.rotation, _shadowPos);
          Mat4.invert(_matShadowView$1, _matShadowTrans);
          if (!onlyForCulling) {
            var halfOrthoSizeWidth = orthoSizeWidth * 0.5;
            var halfOrthoSizeHeight = orthoSizeHeight * 0.5;
            Mat4.ortho(_matShadowProj, -halfOrthoSizeWidth, halfOrthoSizeWidth, -halfOrthoSizeHeight, halfOrthoSizeHeight, 0.1, this._shadowCameraFar, device.capabilities.clipSpaceMinZ, device.capabilities.clipSpaceSignY);
            Mat4.multiply(_matShadowViewProjArbitaryPos, _matShadowProj, shadowViewArbitaryPos);
            Vec3.transformMat4(_projPos, _shadowPos, _matShadowViewProjArbitaryPos);
            var invActualSize = 2.0 / shadowMapWidth;
            _texelSize.set(invActualSize, invActualSize);
            var modX = _projPos.x % _texelSize.x;
            var modY = _projPos.y % _texelSize.y;
            _projSnap.set(_projPos.x - modX, _projPos.y - modY, _projPos.z);
            Mat4.invert(_matShadowViewProjArbitaryPosInv, _matShadowViewProjArbitaryPos);
            Vec3.transformMat4(_snap, _projSnap, _matShadowViewProjArbitaryPosInv);
            Mat4.fromRT(_matShadowTrans, dirLight.node.rotation, _snap);
            Mat4.invert(_matShadowView$1, _matShadowTrans);
            Mat4.multiply(_matShadowViewProj$1, _matShadowProj, _matShadowView$1);
            Mat4.copy(this._matShadowView, _matShadowView$1);
            Mat4.copy(this._matShadowProj, _matShadowProj);
            Mat4.copy(this._matShadowViewProj, _matShadowViewProj$1);
          }
          Frustum.createOrtho(this._validFrustum, orthoSizeWidth, orthoSizeHeight, 0.1, this._shadowCameraFar, _matShadowTrans);
        };
        _createClass(ShadowLayerVolume, [{
          key: "level",
          get: function get() {
            return this._level;
          }
        }, {
          key: "shadowObjects",
          get: function get() {
            return this._shadowObjects;
          }
        }, {
          key: "shadowCameraFar",
          get: function get() {
            return this._shadowCameraFar;
          },
          set: function set(val) {
            this._shadowCameraFar = val;
          }
        }, {
          key: "matShadowView",
          get: function get() {
            return this._matShadowView;
          },
          set: function set(val) {
            this._matShadowView = val;
          }
        }, {
          key: "matShadowProj",
          get: function get() {
            return this._matShadowProj;
          },
          set: function set(val) {
            this._matShadowProj = val;
          }
        }, {
          key: "matShadowViewProj",
          get: function get() {
            return this._matShadowViewProj;
          },
          set: function set(val) {
            this._matShadowViewProj = val;
          }
        }, {
          key: "validFrustum",
          get: function get() {
            return this._validFrustum;
          }
        }, {
          key: "splitFrustum",
          get: function get() {
            return this._splitFrustum;
          }
        }, {
          key: "lightViewFrustum",
          get: function get() {
            return this._lightViewFrustum;
          }
        }, {
          key: "castLightViewBoundingBox",
          get: function get() {
            return this._castLightViewBoundingBox;
          }
        }]);
        return ShadowLayerVolume;
      }();
      var CSMShadowLayer = function (_ShadowLayerVolume) {
        _inheritsLoose(CSMShadowLayer, _ShadowLayerVolume);
        function CSMShadowLayer(level) {
          var _this;
          _this = _ShadowLayerVolume.call(this, level) || this;
          _this._splitCameraNear = 0;
          _this._splitCameraFar = 0;
          _this._csmAtlas = new Vec4();
          _this._calculateAtlas(level);
          return _this;
        }
        var _proto2 = CSMShadowLayer.prototype;
        _proto2.destroy = function destroy() {
          _ShadowLayerVolume.prototype.destroy.call(this);
        };
        _proto2._calculateAtlas = function _calculateAtlas(level) {
          var clipSpaceSignY = legacyCC.director.root.device.capabilities.clipSpaceSignY;
          var x = level % 2 - 0.5;
          var y = (0.5 - Math.floor(level / 2)) * clipSpaceSignY;
          this._csmAtlas.set(0.5, 0.5, x, y);
        };
        _createClass(CSMShadowLayer, [{
          key: "splitCameraNear",
          get: function get() {
            return this._splitCameraNear;
          },
          set: function set(val) {
            this._splitCameraNear = val;
          }
        }, {
          key: "splitCameraFar",
          get: function get() {
            return this._splitCameraFar;
          },
          set: function set(val) {
            this._splitCameraFar = val;
          }
        }, {
          key: "csmAtlas",
          get: function get() {
            return this._csmAtlas;
          },
          set: function set(val) {
            this._csmAtlas = val;
          }
        }]);
        return CSMShadowLayer;
      }(ShadowLayerVolume);
      var CSMLayers = function () {
        function CSMLayers() {
          this._castShadowObjects = [];
          this._layerObjects = new CachedArray(64);
          this._layers = [];
          this._levelCount = 0;
          this._specialLayer = new ShadowLayerVolume(1);
          this._shadowDistance = 0;
          for (var i = 0; i < CSMLevel.LEVEL_4; i++) {
            this._layers[i] = new CSMShadowLayer(i);
          }
        }
        var _proto3 = CSMLayers.prototype;
        _proto3.update = function update(sceneData, camera) {
          var scene = camera.scene;
          var dirLight = scene.mainLight;
          if (dirLight === null) {
            return;
          }
          var shadowInfo = sceneData.shadows;
          var levelCount = legacyCC.director.root.pipeline.pipelineSceneData.csmSupported ? dirLight.csmLevel : 1;
          var shadowDistance = dirLight.shadowDistance;
          if (!shadowInfo.enabled || !dirLight.shadowEnabled) {
            return;
          }
          if (dirLight.shadowFixedArea) {
            this._updateFixedArea(dirLight);
          } else {
            if (dirLight.csmNeedUpdate || this._levelCount !== levelCount || this._shadowDistance !== shadowDistance) {
              this._splitFrustumLevels(dirLight);
              this._levelCount = levelCount;
              this._shadowDistance = shadowDistance;
            }
            this._calculateCSM(camera, dirLight, shadowInfo);
          }
        };
        _proto3.destroy = function destroy() {
          this._castShadowObjects.length = 0;
          for (var i = 0; i < this._layers.length; i++) {
            this._layers[i].destroy();
          }
          this._layers.length = 0;
        };
        _proto3._updateFixedArea = function _updateFixedArea(dirLight) {
          var device = legacyCC.director.root.device;
          var x = dirLight.shadowOrthoSize;
          var y = dirLight.shadowOrthoSize;
          var near = dirLight.shadowNear;
          var far = dirLight.shadowFar;
          Mat4.fromRT(_matShadowTrans, dirLight.node.getWorldRotation(), dirLight.node.getWorldPosition());
          Mat4.invert(_matShadowView$1, _matShadowTrans);
          Mat4.ortho(_matShadowProj, -x, x, -y, y, near, far, device.capabilities.clipSpaceMinZ, device.capabilities.clipSpaceSignY);
          Mat4.multiply(_matShadowViewProj$1, _matShadowProj, _matShadowView$1);
          this._specialLayer.matShadowView = _matShadowView$1;
          this._specialLayer.matShadowProj = _matShadowProj;
          this._specialLayer.matShadowViewProj = _matShadowViewProj$1;
          this._specialLayer.calculateValidFrustumOrtho(x * 2.0, y * 2.0, near, far, _matShadowTrans);
        };
        _proto3._splitFrustumLevels = function _splitFrustumLevels(dirLight) {
          var nd = 0.1;
          var fd = dirLight.shadowDistance;
          var ratio = fd / nd;
          var level = legacyCC.director.root.pipeline.pipelineSceneData.csmSupported ? dirLight.csmLevel : 1;
          var lambda = dirLight.csmLayerLambda;
          this._layers[0].splitCameraNear = nd;
          for (var i = 1; i < level; i++) {
            var si = i / level;
            var preNear = lambda * (nd * Math.pow(ratio, si)) + (1 - lambda) * (nd + (fd - nd) * si);
            var nextFar = preNear * 1.005;
            this._layers[i].splitCameraNear = preNear;
            this._layers[i - 1].splitCameraFar = nextFar;
          }
          this._layers[level - 1].splitCameraFar = fd;
          dirLight.csmNeedUpdate = false;
        };
        _proto3._calculateCSM = function _calculateCSM(camera, dirLight, shadowInfo) {
          var level = legacyCC.director.root.pipeline.pipelineSceneData.csmSupported ? dirLight.csmLevel : 1;
          var shadowMapWidth = level > 1 ? shadowInfo.size.x * 0.5 : shadowInfo.size.x;
          if (shadowMapWidth < 0.0) {
            return;
          }
          this._getCameraWorldMatrix(_mat4Trans, camera);
          for (var i = level - 1; i >= 0; i--) {
            var csmLayer = this._layers[i];
            var near = csmLayer.splitCameraNear;
            var far = csmLayer.splitCameraFar;
            csmLayer.calculateSplitFrustum(camera, _mat4Trans, near, far);
            csmLayer.createMatrix(dirLight, shadowMapWidth, false);
          }
          if (level === CSMLevel.LEVEL_1) {
            this._specialLayer.shadowCameraFar = this._layers[0].shadowCameraFar;
            Mat4.copy(this._specialLayer.matShadowView, this._layers[0].matShadowView);
            Mat4.copy(this._specialLayer.matShadowProj, this._layers[0].matShadowProj);
            Mat4.copy(this._specialLayer.matShadowViewProj, this._layers[0].matShadowViewProj);
            this._specialLayer.copyToValidFrustum(this._layers[0].validFrustum);
          } else {
            this._specialLayer.calculateSplitFrustum(camera, _mat4Trans, 0.1, dirLight.shadowDistance);
            this._specialLayer.createMatrix(dirLight, shadowMapWidth, true);
          }
        };
        _proto3._getCameraWorldMatrix = function _getCameraWorldMatrix(out, camera) {
          if (!camera.node) {
            return;
          }
          var cameraNode = camera.node;
          var position = cameraNode.getWorldPosition();
          var rotation = cameraNode.getWorldRotation();
          Mat4.fromRT(out, rotation, position);
        };
        _createClass(CSMLayers, [{
          key: "castShadowObjects",
          get: function get() {
            return this._castShadowObjects;
          }
        }, {
          key: "layerObjects",
          get: function get() {
            return this._layerObjects;
          }
        }, {
          key: "layers",
          get: function get() {
            return this._layers;
          }
        }, {
          key: "specialLayer",
          get: function get() {
            return this._specialLayer;
          }
        }]);
        return CSMLayers;
      }();

      var Skin = function () {
        function Skin() {
          this._enabled = true;
          this._blurRadius = 0.01;
          this._sssIntensity = 3.0;
        }
        var _proto = Skin.prototype;
        _proto.initialize = function initialize(skinInfo) {
          this._enabled = skinInfo.enabled;
          this._blurRadius = skinInfo.blurRadius;
          this._sssIntensity = skinInfo.sssIntensity;
        };
        _createClass(Skin, [{
          key: "enabled",
          get: function get() {
            return this._enabled;
          },
          set: function set(val) {
            this._enabled = val;
          }
        }, {
          key: "blurRadius",
          get: function get() {
            return this._blurRadius;
          },
          set: function set(val) {
            this._blurRadius = val;
          }
        }, {
          key: "sssIntensity",
          get: function get() {
            return this._sssIntensity;
          },
          set: function set(val) {
            this._sssIntensity = val;
          }
        }]);
        return Skin;
      }();

      var GEOMETRY_RENDERER_TECHNIQUE_COUNT = 6;
      var PipelineSceneData = exports('d6', function () {
        function PipelineSceneData() {
          this.fog = new Fog();
          this.ambient = new Ambient();
          this.skybox = new Skybox();
          this.shadows = new Shadows();
          this.csmLayers = new CSMLayers();
          this.octree = new Octree();
          this.skin = new Skin();
          this.postSettings = new PostSettings();
          this.lightProbes = legacyCC.internal.LightProbes ? new legacyCC.internal.LightProbes() : null;
          this.validPunctualLights = [];
          this.renderObjects = [];
          this.shadowFrameBufferMap = new Map();
          this._geometryRendererMaterials = [];
          this._geometryRendererPasses = [];
          this._geometryRendererShaders = [];
          this._occlusionQueryVertexBuffer = null;
          this._occlusionQueryIndicesBuffer = null;
          this._occlusionQueryInputAssembler = null;
          this._occlusionQueryMaterial = null;
          this._occlusionQueryShader = null;
          this._isHDR = true;
          this._shadingScale = 1.0;
          this._csmSupported = true;
          this._standardSkinMeshRenderer = null;
          this._standardSkinModel = null;
          this._skinMaterialModel = null;
          this._shadingScale = 1.0;
        }
        var _proto = PipelineSceneData.prototype;
        _proto.activate = function activate(device) {
          this._device = device;
          this.initGeometryRendererMaterials();
          this.initOcclusionQuery();
          return true;
        };
        _proto.initGeometryRendererMaterials = function initGeometryRendererMaterials() {
          var offset = 0;
          for (var tech = 0; tech < GEOMETRY_RENDERER_TECHNIQUE_COUNT; tech++) {
            this._geometryRendererMaterials[tech] = new Material();
            this._geometryRendererMaterials[tech]._uuid = "geometry-renderer-material-" + tech;
            this._geometryRendererMaterials[tech].initialize({
              effectName: 'internal/builtin-geometry-renderer',
              technique: tech
            });
            for (var pass = 0; pass < this._geometryRendererMaterials[tech].passes.length; ++pass) {
              this._geometryRendererPasses[offset] = this._geometryRendererMaterials[tech].passes[pass];
              this._geometryRendererShaders[offset] = this._geometryRendererMaterials[tech].passes[pass].getShaderVariant();
              offset++;
            }
          }
        };
        _proto.initOcclusionQuery = function initOcclusionQuery() {
          if (!this._occlusionQueryInputAssembler) {
            this._occlusionQueryInputAssembler = this._createOcclusionQueryIA();
          }
          if (!this._occlusionQueryMaterial) {
            var mat = new Material();
            mat._uuid = 'default-occlusion-query-material';
            mat.initialize({
              effectName: 'internal/builtin-occlusion-query'
            });
            this._occlusionQueryMaterial = mat;
            if (mat.passes.length > 0) {
              this._occlusionQueryShader = mat.passes[0].getShaderVariant();
            }
          }
        };
        _proto.getOcclusionQueryPass = function getOcclusionQueryPass() {
          if (this._occlusionQueryMaterial && this._occlusionQueryMaterial.passes.length > 0) {
            return this._occlusionQueryMaterial.passes[0];
          }
          return null;
        };
        _proto.updatePipelineSceneData = function updatePipelineSceneData() {};
        _proto.destroy = function destroy() {
          var _this$_occlusionQuery, _this$_occlusionQuery2, _this$_occlusionQuery3;
          this.shadows.destroy();
          this.csmLayers.destroy();
          this.validPunctualLights.length = 0;
          (_this$_occlusionQuery = this._occlusionQueryInputAssembler) === null || _this$_occlusionQuery === void 0 ? void 0 : _this$_occlusionQuery.destroy();
          this._occlusionQueryInputAssembler = null;
          (_this$_occlusionQuery2 = this._occlusionQueryVertexBuffer) === null || _this$_occlusionQuery2 === void 0 ? void 0 : _this$_occlusionQuery2.destroy();
          this._occlusionQueryVertexBuffer = null;
          (_this$_occlusionQuery3 = this._occlusionQueryIndicesBuffer) === null || _this$_occlusionQuery3 === void 0 ? void 0 : _this$_occlusionQuery3.destroy();
          this._occlusionQueryIndicesBuffer = null;
          this._standardSkinMeshRenderer = null;
          this._standardSkinModel = null;
          this._skinMaterialModel = null;
        };
        _proto._createOcclusionQueryIA = function _createOcclusionQueryIA() {
          var device = this._device;
          var vertices = new Float32Array([-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 vbStride = Float32Array.BYTES_PER_ELEMENT * 3;
          var vbSize = vbStride * 8;
          this._occlusionQueryVertexBuffer = device.createBuffer(new BufferInfo(BufferUsageBit.VERTEX | BufferUsageBit.TRANSFER_DST, MemoryUsageBit.DEVICE, vbSize, vbStride));
          this._occlusionQueryVertexBuffer.update(vertices);
          var indices = new Uint16Array([0, 2, 1, 1, 2, 3, 4, 5, 6, 5, 7, 6, 1, 3, 7, 1, 7, 5, 0, 4, 6, 0, 6, 2, 0, 1, 5, 0, 5, 4, 2, 6, 7, 2, 7, 3]);
          var ibStride = Uint16Array.BYTES_PER_ELEMENT;
          var ibSize = ibStride * 36;
          this._occlusionQueryIndicesBuffer = device.createBuffer(new BufferInfo(BufferUsageBit.INDEX | BufferUsageBit.TRANSFER_DST, MemoryUsageBit.DEVICE, ibSize, ibStride));
          this._occlusionQueryIndicesBuffer.update(indices);
          var attributes = [new Attribute('a_position', Format.RGB32F)];
          var info = new InputAssemblerInfo(attributes, [this._occlusionQueryVertexBuffer], this._occlusionQueryIndicesBuffer);
          var inputAssembler = device.createInputAssembler(info);
          return inputAssembler;
        };
        _createClass(PipelineSceneData, [{
          key: "isHDR",
          get: function get() {
            return this._isHDR;
          },
          set: function set(val) {
            this._isHDR = val;
          }
        }, {
          key: "shadingScale",
          get: function get() {
            return this._shadingScale;
          },
          set: function set(val) {
            this._shadingScale = val;
          }
        }, {
          key: "csmSupported",
          get: function get() {
            return this._csmSupported;
          },
          set: function set(val) {
            this._csmSupported = val;
          }
        }, {
          key: "standardSkinModel",
          get: function get() {
            return this._standardSkinModel;
          },
          set: function set(val) {
            this._standardSkinModel = val;
          }
        }, {
          key: "standardSkinMeshRenderer",
          get: function get() {
            return this._standardSkinMeshRenderer;
          },
          set: function set(val) {
            if (this._standardSkinMeshRenderer && this._standardSkinMeshRenderer !== val) {
              this._standardSkinMeshRenderer.clearGlobalStandardSkinObjectFlag();
            }
            this._standardSkinMeshRenderer = val;
            this.standardSkinModel = val ? val.model : null;
          }
        }, {
          key: "skinMaterialModel",
          get: function get() {
            return this._skinMaterialModel;
          },
          set: function set(val) {
            this._skinMaterialModel = val;
          }
        }, {
          key: "geometryRendererPasses",
          get: function get() {
            return this._geometryRendererPasses;
          }
        }, {
          key: "geometryRendererShaders",
          get: function get() {
            return this._geometryRendererShaders;
          }
        }]);
        return PipelineSceneData;
      }());

      var CommonStagePriority;
      (function (CommonStagePriority) {
        CommonStagePriority[CommonStagePriority["BLOOM"] = 18] = "BLOOM";
        CommonStagePriority[CommonStagePriority["POST_PROCESS"] = 19] = "POST_PROCESS";
        CommonStagePriority[CommonStagePriority["UI"] = 20] = "UI";
      })(CommonStagePriority || (CommonStagePriority = {}));
      var ForwardStagePriority;
      (function (ForwardStagePriority) {
        ForwardStagePriority[ForwardStagePriority["AR"] = 5] = "AR";
        ForwardStagePriority[ForwardStagePriority["FORWARD"] = 10] = "FORWARD";
      })(ForwardStagePriority || (ForwardStagePriority = {}));
      var ForwardFlowPriority;
      (function (ForwardFlowPriority) {
        ForwardFlowPriority[ForwardFlowPriority["SHADOW"] = 0] = "SHADOW";
        ForwardFlowPriority[ForwardFlowPriority["FORWARD"] = 1] = "FORWARD";
        ForwardFlowPriority[ForwardFlowPriority["UI"] = 10] = "UI";
      })(ForwardFlowPriority || (ForwardFlowPriority = {}));
      var DeferredStagePriority;
      (function (DeferredStagePriority) {
        DeferredStagePriority[DeferredStagePriority["GBUFFER"] = 10] = "GBUFFER";
        DeferredStagePriority[DeferredStagePriority["LIGHTING"] = 15] = "LIGHTING";
        DeferredStagePriority[DeferredStagePriority["TRANSPARENT"] = 18] = "TRANSPARENT";
      })(DeferredStagePriority || (DeferredStagePriority = {}));
      var DeferredFlowPriority;
      (function (DeferredFlowPriority) {
        DeferredFlowPriority[DeferredFlowPriority["SHADOW"] = 0] = "SHADOW";
        DeferredFlowPriority[DeferredFlowPriority["MAIN"] = 1] = "MAIN";
        DeferredFlowPriority[DeferredFlowPriority["UI"] = 10] = "UI";
      })(DeferredFlowPriority || (DeferredFlowPriority = {}));

      var _dec$2G, _dec2$1Z, _dec3$1m, _dec4$Y, _class$2D, _class2$2o, _initializer$27, _initializer2$1E, _initializer3$15, _initializer4$R, _initializer5$D, _initializer6$u, _dec5$N, _dec6$x, _class4$s, _class5$t, _initializer7$o, _initializer8$n, _dec7$q, _dec8$i, _class7$9, _class8$8, _initializer9$l, _initializer10$j, _dec9$f, _dec10$a, _dec11$8, _class10$4, _class11$4, _initializer11$g, _initializer12$e, _initializer13$d, _initializer14$b, _initializer15$8, _dec12$8, _dec13$6, _dec14$5, _dec15$5, _dec16$4, _dec17$4, _class13$3, _class14$3, _initializer16$8, _initializer17$7, _initializer18$6, _initializer19$5, _initializer20$4, _initializer21$4, _dec18$3, _dec19$3, _dec20$3, _dec21$3, _dec22$3, _dec23$3, _dec24$3, _dec25$3, _class16, _class17$1, _initializer22$3, _initializer23$2, _initializer24$2, _initializer25$2, _initializer26$2, _initializer27$2, _initializer28$2, _initializer29$2, _dec26$3, _dec27$3, _dec28$3, _class19, _class20$2, _initializer30$2, _initializer31$2, _initializer32$1, _dec29$3, _dec30$2, _dec31$2, _class22, _class23$1, _initializer33$1, _initializer34$1, _initializer35$1;
      ccenum(TextureType);
      ccenum(TextureUsageBit);
      ccenum(StoreOp);
      ccenum(LoadOp);
      ccenum(AccessFlagBit);
      ccenum(Format);
      var RenderFlowTag;
      (function (RenderFlowTag) {
        RenderFlowTag[RenderFlowTag["SCENE"] = 0] = "SCENE";
        RenderFlowTag[RenderFlowTag["POSTPROCESS"] = 1] = "POSTPROCESS";
        RenderFlowTag[RenderFlowTag["UI"] = 2] = "UI";
      })(RenderFlowTag || (RenderFlowTag = {}));
      ccenum(RenderFlowTag);
      (_dec$2G = ccclass$n('RenderTextureDesc'), _dec2$1Z = type$7(TextureType), _dec3$1m = type$7(TextureUsageBit), _dec4$Y = type$7(Format), _dec$2G(_class$2D = (_class2$2o = function RenderTextureDesc() {
        this.name = _initializer$27 && _initializer$27();
        this.type = _initializer2$1E && _initializer2$1E();
        this.usage = _initializer3$15 && _initializer3$15();
        this.format = _initializer4$R && _initializer4$R();
        this.width = _initializer5$D && _initializer5$D();
        this.height = _initializer6$u && _initializer6$u();
      }, (_initializer$27 = applyDecoratedInitializer(_class2$2o.prototype, "name", [serializable$j], function () {
        return '';
      }), _initializer2$1E = applyDecoratedInitializer(_class2$2o.prototype, "type", [_dec2$1Z], function () {
        return TextureType.TEX2D;
      }), _initializer3$15 = applyDecoratedInitializer(_class2$2o.prototype, "usage", [_dec3$1m], function () {
        return TextureUsageBit.COLOR_ATTACHMENT;
      }), _initializer4$R = applyDecoratedInitializer(_class2$2o.prototype, "format", [_dec4$Y], function () {
        return Format.UNKNOWN;
      }), _initializer5$D = applyDecoratedInitializer(_class2$2o.prototype, "width", [serializable$j], function () {
        return -1;
      }), _initializer6$u = applyDecoratedInitializer(_class2$2o.prototype, "height", [serializable$j], function () {
        return -1;
      })), _class2$2o)) || _class$2D);
      var RenderTextureConfig = (_dec5$N = ccclass$n('RenderTextureConfig'), _dec6$x = type$7(RenderTexture), _dec5$N(_class4$s = (_class5$t = function RenderTextureConfig() {
        this.name = _initializer7$o && _initializer7$o();
        this.texture = _initializer8$n && _initializer8$n();
      }, (_initializer7$o = applyDecoratedInitializer(_class5$t.prototype, "name", [serializable$j], function () {
        return '';
      }), _initializer8$n = applyDecoratedInitializer(_class5$t.prototype, "texture", [_dec6$x], function () {
        return null;
      })), _class5$t)) || _class4$s);
      (_dec7$q = ccclass$n('MaterialConfig'), _dec8$i = type$7(Material), _dec7$q(_class7$9 = (_class8$8 = function MaterialConfig() {
        this.name = _initializer9$l && _initializer9$l();
        this.material = _initializer10$j && _initializer10$j();
      }, (_initializer9$l = applyDecoratedInitializer(_class8$8.prototype, "name", [serializable$j], function () {
        return '';
      }), _initializer10$j = applyDecoratedInitializer(_class8$8.prototype, "material", [_dec8$i], function () {
        return null;
      })), _class8$8)) || _class7$9);
      (_dec9$f = ccclass$n('FrameBufferDesc'), _dec10$a = type$7([CCString]), _dec11$8 = type$7(RenderTexture), _dec9$f(_class10$4 = (_class11$4 = function FrameBufferDesc() {
        this.name = _initializer11$g && _initializer11$g();
        this.renderPass = _initializer12$e && _initializer12$e();
        this.colorTextures = _initializer13$d && _initializer13$d();
        this.depthStencilTexture = _initializer14$b && _initializer14$b();
        this.texture = _initializer15$8 && _initializer15$8();
      }, (_initializer11$g = applyDecoratedInitializer(_class11$4.prototype, "name", [serializable$j], function () {
        return '';
      }), _initializer12$e = applyDecoratedInitializer(_class11$4.prototype, "renderPass", [serializable$j], function () {
        return 0;
      }), _initializer13$d = applyDecoratedInitializer(_class11$4.prototype, "colorTextures", [_dec10$a], function () {
        return [];
      }), _initializer14$b = applyDecoratedInitializer(_class11$4.prototype, "depthStencilTexture", [serializable$j], function () {
        return '';
      }), _initializer15$8 = applyDecoratedInitializer(_class11$4.prototype, "texture", [_dec11$8], function () {
        return null;
      })), _class11$4)) || _class10$4);
      var ColorDesc = (_dec12$8 = ccclass$n('ColorDesc'), _dec13$6 = type$7(Format), _dec14$5 = type$7(LoadOp), _dec15$5 = type$7(StoreOp), _dec16$4 = type$7(AccessFlagBit), _dec17$4 = type$7(AccessFlagBit), _dec12$8(_class13$3 = (_class14$3 = function ColorDesc() {
        this.format = _initializer16$8 && _initializer16$8();
        this.loadOp = _initializer17$7 && _initializer17$7();
        this.storeOp = _initializer18$6 && _initializer18$6();
        this.sampleCount = _initializer19$5 && _initializer19$5();
        this.beginAccesses = _initializer20$4 && _initializer20$4();
        this.endAccesses = _initializer21$4 && _initializer21$4();
      }, (_initializer16$8 = applyDecoratedInitializer(_class14$3.prototype, "format", [_dec13$6], function () {
        return Format.UNKNOWN;
      }), _initializer17$7 = applyDecoratedInitializer(_class14$3.prototype, "loadOp", [_dec14$5], function () {
        return LoadOp.CLEAR;
      }), _initializer18$6 = applyDecoratedInitializer(_class14$3.prototype, "storeOp", [_dec15$5], function () {
        return StoreOp.STORE;
      }), _initializer19$5 = applyDecoratedInitializer(_class14$3.prototype, "sampleCount", [serializable$j], function () {
        return 1;
      }), _initializer20$4 = applyDecoratedInitializer(_class14$3.prototype, "beginAccesses", [_dec16$4], function () {
        return AccessFlagBit.NONE;
      }), _initializer21$4 = applyDecoratedInitializer(_class14$3.prototype, "endAccesses", [_dec17$4], function () {
        return AccessFlagBit.COLOR_ATTACHMENT_WRITE;
      })), _class14$3)) || _class13$3);
      var DepthStencilDesc = (_dec18$3 = ccclass$n('DepthStencilDesc'), _dec19$3 = type$7(Format), _dec20$3 = type$7(LoadOp), _dec21$3 = type$7(StoreOp), _dec22$3 = type$7(LoadOp), _dec23$3 = type$7(StoreOp), _dec24$3 = type$7(AccessFlagBit), _dec25$3 = type$7(AccessFlagBit), _dec18$3(_class16 = (_class17$1 = function DepthStencilDesc() {
        this.format = _initializer22$3 && _initializer22$3();
        this.depthLoadOp = _initializer23$2 && _initializer23$2();
        this.depthStoreOp = _initializer24$2 && _initializer24$2();
        this.stencilLoadOp = _initializer25$2 && _initializer25$2();
        this.stencilStoreOp = _initializer26$2 && _initializer26$2();
        this.sampleCount = _initializer27$2 && _initializer27$2();
        this.beginAccesses = _initializer28$2 && _initializer28$2();
        this.endAccesses = _initializer29$2 && _initializer29$2();
      }, (_initializer22$3 = applyDecoratedInitializer(_class17$1.prototype, "format", [_dec19$3], function () {
        return Format.UNKNOWN;
      }), _initializer23$2 = applyDecoratedInitializer(_class17$1.prototype, "depthLoadOp", [_dec20$3], function () {
        return LoadOp.CLEAR;
      }), _initializer24$2 = applyDecoratedInitializer(_class17$1.prototype, "depthStoreOp", [_dec21$3], function () {
        return StoreOp.STORE;
      }), _initializer25$2 = applyDecoratedInitializer(_class17$1.prototype, "stencilLoadOp", [_dec22$3], function () {
        return LoadOp.CLEAR;
      }), _initializer26$2 = applyDecoratedInitializer(_class17$1.prototype, "stencilStoreOp", [_dec23$3], function () {
        return StoreOp.STORE;
      }), _initializer27$2 = applyDecoratedInitializer(_class17$1.prototype, "sampleCount", [serializable$j], function () {
        return 1;
      }), _initializer28$2 = applyDecoratedInitializer(_class17$1.prototype, "beginAccesses", [_dec24$3], function () {
        return AccessFlagBit.NONE;
      }), _initializer29$2 = applyDecoratedInitializer(_class17$1.prototype, "endAccesses", [_dec25$3], function () {
        return AccessFlagBit.DEPTH_STENCIL_ATTACHMENT_WRITE;
      })), _class17$1)) || _class16);
      (_dec26$3 = ccclass$n('RenderPassDesc'), _dec27$3 = type$7([ColorDesc]), _dec28$3 = type$7(DepthStencilDesc), _dec26$3(_class19 = (_class20$2 = function RenderPassDesc() {
        this.index = _initializer30$2 && _initializer30$2();
        this.colorAttachments = _initializer31$2 && _initializer31$2();
        this.depthStencilAttachment = _initializer32$1 && _initializer32$1();
      }, (_initializer30$2 = applyDecoratedInitializer(_class20$2.prototype, "index", [serializable$j], function () {
        return -1;
      }), _initializer31$2 = applyDecoratedInitializer(_class20$2.prototype, "colorAttachments", [_dec27$3], function () {
        return [];
      }), _initializer32$1 = applyDecoratedInitializer(_class20$2.prototype, "depthStencilAttachment", [_dec28$3], function () {
        return new DepthStencilDesc();
      })), _class20$2)) || _class19);
      var RenderQueueSortMode;
      (function (RenderQueueSortMode) {
        RenderQueueSortMode[RenderQueueSortMode["FRONT_TO_BACK"] = 0] = "FRONT_TO_BACK";
        RenderQueueSortMode[RenderQueueSortMode["BACK_TO_FRONT"] = 1] = "BACK_TO_FRONT";
      })(RenderQueueSortMode || (RenderQueueSortMode = {}));
      ccenum(RenderQueueSortMode);
      var RenderQueueDesc = (_dec29$3 = ccclass$n('RenderQueueDesc'), _dec30$2 = type$7(RenderQueueSortMode), _dec31$2 = type$7([CCString]), _dec29$3(_class22 = (_class23$1 = function RenderQueueDesc() {
        this.isTransparent = _initializer33$1 && _initializer33$1();
        this.sortMode = _initializer34$1 && _initializer34$1();
        this.stages = _initializer35$1 && _initializer35$1();
      }, (_initializer33$1 = applyDecoratedInitializer(_class23$1.prototype, "isTransparent", [serializable$j], function () {
        return false;
      }), _initializer34$1 = applyDecoratedInitializer(_class23$1.prototype, "sortMode", [_dec30$2], function () {
        return RenderQueueSortMode.FRONT_TO_BACK;
      }), _initializer35$1 = applyDecoratedInitializer(_class23$1.prototype, "stages", [_dec31$2], function () {
        return [];
      })), _class23$1)) || _class22);

      function opaqueCompareFn(a, b) {
        return a.hash - b.hash || a.depth - b.depth || a.shaderId - b.shaderId;
      }
      function transparentCompareFn(a, b) {
        return a.priority - b.priority || a.hash - b.hash || b.depth - a.depth || a.shaderId - b.shaderId;
      }
      var RenderQueue$1 = function () {
        function RenderQueue(desc) {
          this.queue = void 0;
          this._passDesc = void 0;
          this._passPool = void 0;
          this._passDesc = desc;
          this._passPool = new RecyclePool(function () {
            return {
              priority: 0,
              hash: 0,
              depth: 0,
              shaderId: 0,
              subModel: null,
              passIdx: 0
            };
          }, 64);
          this.queue = new CachedArray(64, this._passDesc.sortFunc);
        }
        var _proto = RenderQueue.prototype;
        _proto.clear = function clear() {
          this.queue.clear();
          this._passPool.reset();
        };
        _proto.insertRenderPass = function insertRenderPass(renderObj, subModelIdx, passIdx) {
          var subModel = renderObj.model.subModels[subModelIdx];
          var pass = subModel.passes[passIdx];
          var shader = subModel.shaders[passIdx];
          var isTransparent = pass.blendState.targets[0].blend;
          if (isTransparent !== this._passDesc.isTransparent || !(pass.phase & this._passDesc.phases)) {
            return false;
          }
          var hash = 0 << 30 | pass.priority << 16 | subModel.priority << 8 | passIdx;
          var rp = this._passPool.add();
          rp.priority = renderObj.model.priority;
          rp.hash = hash;
          rp.depth = renderObj.depth || 0;
          rp.shaderId = shader.typedID;
          rp.subModel = subModel;
          rp.passIdx = passIdx;
          this.queue.push(rp);
          return true;
        };
        _proto.sort = function sort() {
          this.queue.sort();
        };
        _proto.recordCommandBuffer = function recordCommandBuffer(device, renderPass, cmdBuff) {
          for (var i = 0; i < this.queue.length; ++i) {
            var _this$queue$array$i = this.queue.array[i],
              subModel = _this$queue$array$i.subModel,
              passIdx = _this$queue$array$i.passIdx;
            var inputAssembler = subModel.inputAssembler;
            var pass = subModel.passes[passIdx];
            var shader = subModel.shaders[passIdx];
            var pso = PipelineStateManager.getOrCreatePipelineState(device, pass, shader, renderPass, inputAssembler);
            cmdBuff.bindPipelineState(pso);
            cmdBuff.bindDescriptorSet(SetIndex.MATERIAL, pass.descriptorSet);
            cmdBuff.bindDescriptorSet(SetIndex.LOCAL, subModel.descriptorSet);
            cmdBuff.bindInputAssembler(inputAssembler);
            cmdBuff.draw(inputAssembler);
          }
        };
        return RenderQueue;
      }();
      function convertRenderQueue(desc) {
        var phase = 0;
        for (var j = 0; j < desc.stages.length; j++) {
          phase |= getPhaseID(desc.stages[j]);
        }
        var sortFunc = opaqueCompareFn;
        switch (desc.sortMode) {
          case RenderQueueSortMode.BACK_TO_FRONT:
            sortFunc = transparentCompareFn;
            break;
          case RenderQueueSortMode.FRONT_TO_BACK:
            sortFunc = opaqueCompareFn;
            break;
        }
        return new RenderQueue$1({
          isTransparent: desc.isTransparent,
          phases: phase,
          sortFunc: sortFunc
        });
      }
      function renderQueueClearFunc(rq) {
        rq.clear();
      }
      function renderQueueSortFunc(rq) {
        rq.sort();
      }

      var RenderInstancedQueue = function () {
        function RenderInstancedQueue() {
          this.queue = new Set();
          this._renderQueue = [];
        }
        var _proto = RenderInstancedQueue.prototype;
        _proto.clear = function clear() {
          var it = this.queue.values();
          var res = it.next();
          while (!res.done) {
            res.value.clear();
            res = it.next();
          }
          this._renderQueue.length = 0;
          this.queue.clear();
        };
        _proto.sort = function sort() {
          var it = this.queue.values();
          var res = it.next();
          while (!res.done) {
            if (!res.value.pass.blendState.targets[0].blend) {
              this._renderQueue.push(res.value);
            }
            res = it.next();
          }
          it = this.queue.values();
          res = it.next();
          while (!res.done) {
            if (res.value.pass.blendState.targets[0].blend) {
              this._renderQueue.push(res.value);
            }
            res = it.next();
          }
        };
        _proto.uploadBuffers = function uploadBuffers(cmdBuff) {
          var it = this.queue.values();
          var res = it.next();
          while (!res.done) {
            if (res.value.hasPendingModels) res.value.uploadBuffers(cmdBuff);
            res = it.next();
          }
        };
        _proto.recordCommandBuffer = function recordCommandBuffer(device, renderPass, cmdBuff, descriptorSet, dynamicOffsets) {
          if (descriptorSet === void 0) {
            descriptorSet = null;
          }
          var it = this._renderQueue.length === 0 ? this.queue.values() : this._renderQueue[Symbol.iterator]();
          var res = it.next();
          while (!res.done) {
            var _res$value = res.value,
              instances = _res$value.instances,
              pass = _res$value.pass,
              hasPendingModels = _res$value.hasPendingModels;
            if (hasPendingModels) {
              cmdBuff.bindDescriptorSet(SetIndex.MATERIAL, pass.descriptorSet);
              var lastPSO = null;
              for (var b = 0; b < instances.length; ++b) {
                var instance = instances[b];
                if (!instance.count) {
                  continue;
                }
                var shader = instance.shader;
                var pso = PipelineStateManager.getOrCreatePipelineState(device, pass, shader, renderPass, instance.ia);
                if (lastPSO !== pso) {
                  cmdBuff.bindPipelineState(pso);
                  lastPSO = pso;
                }
                if (descriptorSet) cmdBuff.bindDescriptorSet(SetIndex.GLOBAL, descriptorSet);
                if (dynamicOffsets) {
                  cmdBuff.bindDescriptorSet(SetIndex.LOCAL, instance.descriptorSet, dynamicOffsets);
                } else {
                  cmdBuff.bindDescriptorSet(SetIndex.LOCAL, instance.descriptorSet, res.value.dynamicOffsets);
                }
                cmdBuff.bindInputAssembler(instance.ia);
                cmdBuff.draw(instance.ia);
              }
            }
            res = it.next();
          }
        };
        return RenderInstancedQueue;
      }();

      var _lightPassPool = new Pool(function () {
        return {
          subModel: null,
          passIdx: -1,
          dynamicOffsets: [],
          lights: []
        };
      }, 16);
      var _v3$2 = new Vec3();
      var _vec4Array = new Float32Array(4);
      var _dynamicOffsets = [];
      var _lightIndices = [];
      var _matShadowView = new Mat4();
      var _matShadowViewProj = new Mat4();
      var _rangedDirLightBoundingBox$1 = new AABB(0.0, 0.0, 0.0, 0.5, 0.5, 0.5);
      var _tmpBoundingBox$1 = new AABB();
      function cullSphereLight(light, model) {
        return !!(model.worldBounds && !intersect.aabbWithAABB(model.worldBounds, light.aabb));
      }
      function cullSpotLight(light, model) {
        return !!(model.worldBounds && (!intersect.aabbWithAABB(model.worldBounds, light.aabb) || !intersect.aabbFrustum(model.worldBounds, light.frustum)));
      }
      function cullPointLight(light, model) {
        return !!(model.worldBounds && !intersect.aabbWithAABB(model.worldBounds, light.aabb));
      }
      function cullRangedDirLight(light, model) {
        AABB.transform(_tmpBoundingBox$1, _rangedDirLightBoundingBox$1, light.node.getWorldMatrix());
        return !!(model.worldBounds && !intersect.aabbWithAABB(model.worldBounds, _tmpBoundingBox$1));
      }
      var phaseName = 'forward-add';
      var _phaseID$4 = getPhaseID(phaseName);
      var _lightPassIndices = [];
      function getLightPassIndices(subModels, lightPassIndices, passLayout) {
        if (passLayout === void 0) {
          passLayout = 'default';
        }
        var r = legacyCC.rendering;
        if (isEnableEffect()) {
          _phaseID$4 = r.getPhaseID(r.getPassID(passLayout), phaseName);
        }
        lightPassIndices.length = 0;
        var hasValidLightPass = false;
        for (var j = 0; j < subModels.length; j++) {
          var passes = subModels[j].passes;
          var lightPassIndex = -1;
          for (var k = 0; k < passes.length; k++) {
            if ((!r || !r.enableEffectImport) && passes[k].phase === _phaseID$4 || isEnableEffect() && passes[k].phaseID === _phaseID$4) {
              lightPassIndex = k;
              hasValidLightPass = true;
              break;
            }
          }
          lightPassIndices.push(lightPassIndex);
        }
        return hasValidLightPass;
      }
      var RenderAdditiveLightQueue = function () {
        function RenderAdditiveLightQueue(pipeline) {
          this._pipeline = void 0;
          this._device = void 0;
          this._lightPasses = [];
          this._instancedLightPassPool = _lightPassPool.alloc();
          this._shadowUBO = new Float32Array(UBOShadow.COUNT);
          this._lightBufferCount = 16;
          this._lightBufferStride = void 0;
          this._lightBufferElementCount = void 0;
          this._lightBuffer = void 0;
          this._firstLightBufferView = void 0;
          this._lightBufferData = void 0;
          this._instancedQueues = [];
          this._lightMeterScale = 10000.0;
          this._pipeline = pipeline;
          this._device = pipeline.device;
          var alignment = this._device.capabilities.uboOffsetAlignment;
          this._lightBufferStride = Math.ceil(UBOForwardLight.SIZE / alignment) * alignment;
          this._lightBufferElementCount = this._lightBufferStride / Float32Array.BYTES_PER_ELEMENT;
          this._lightBuffer = this._device.createBuffer(new BufferInfo(BufferUsageBit.UNIFORM | BufferUsageBit.TRANSFER_DST, MemoryUsageBit.HOST | MemoryUsageBit.DEVICE, this._lightBufferStride * this._lightBufferCount, this._lightBufferStride));
          this._firstLightBufferView = this._device.createBuffer(new BufferViewInfo(this._lightBuffer, 0, UBOForwardLight.SIZE));
          this._lightBufferData = new Float32Array(this._lightBufferElementCount * this._lightBufferCount);
        }
        var _proto = RenderAdditiveLightQueue.prototype;
        _proto.clear = function clear() {
          this._instancedQueues.forEach(function (instancedQueue) {
            instancedQueue.clear();
          });
          this._instancedQueues.length = 0;
          for (var i = 0; i < this._lightPasses.length; i++) {
            var lp = this._lightPasses[i];
            lp.dynamicOffsets.length = 0;
            lp.lights.length = 0;
          }
          _lightPassPool.freeArray(this._lightPasses);
          this._lightPasses.length = 0;
          this._instancedLightPassPool.dynamicOffsets.length = 0;
          this._instancedLightPassPool.lights.length = 0;
        };
        _proto.destroy = function destroy() {
          var descriptorSetMap = this._pipeline.globalDSManager.descriptorSetMap;
          var keys = descriptorSetMap.keys;
          for (var i = 0; i < keys.length; i++) {
            var key = keys[i];
            var descriptorSet = descriptorSetMap.get(key);
            if (descriptorSet) {
              var binding = isEnableEffect() ? getDescBindingFromName('CCShadow') : UBOShadow.BINDING;
              descriptorSet.getBuffer(binding).destroy();
              descriptorSet.getTexture(UNIFORM_SHADOWMAP_BINDING).destroy();
              descriptorSet.getTexture(UNIFORM_SPOT_SHADOW_MAP_TEXTURE_BINDING).destroy();
              descriptorSet.destroy();
            }
            descriptorSetMap["delete"](key);
          }
        };
        _proto._bindForwardAddLight = function _bindForwardAddLight(validPunctualLights, passLayout) {
          if (passLayout === void 0) {
            passLayout = 'default';
          }
          var renderObjects = this._pipeline.pipelineSceneData.renderObjects;
          for (var i = 0; i < renderObjects.length; i++) {
            var ro = renderObjects[i];
            var model = ro.model;
            var subModels = model.subModels;
            if (!getLightPassIndices(subModels, _lightPassIndices, passLayout)) {
              continue;
            }
            _lightIndices.length = 0;
            this._lightCulling(model, validPunctualLights);
            if (!_lightIndices.length && validPunctualLights.length > 0) {
              continue;
            }
            for (var j = 0; j < subModels.length; j++) {
              var lightPassIdx = _lightPassIndices[j];
              if (lightPassIdx < 0) {
                continue;
              }
              var subModel = subModels[j];
              var pass = subModel.passes[lightPassIdx];
              var isTransparent = subModel.passes[0].blendState.targets[0].blend;
              if (isTransparent) {
                continue;
              }
              isEnableEffect() ? getDescBindingFromName('CCForwardLight') : UBOForwardLight.BINDING;
              subModel.descriptorSet.bindBuffer(UBOForwardLight.BINDING, this._firstLightBufferView);
              subModel.descriptorSet.update();
              this._addRenderQueue(pass, subModel, model, lightPassIdx);
            }
          }
        };
        _proto.gatherLightPasses = function gatherLightPasses(camera, cmdBuff, passLayout) {
          if (passLayout === void 0) {
            passLayout = 'default';
          }
          this.clear();
          var validPunctualLights = this._pipeline.pipelineSceneData.validPunctualLights;
          if (!validPunctualLights.length) {
            this._bindForwardAddLight(validPunctualLights, passLayout);
            return;
          }
          this._updateUBOs(camera, cmdBuff);
          this._updateLightDescriptorSet(camera, cmdBuff);
          this._bindForwardAddLight(validPunctualLights, passLayout);
          for (var l = 0; l < validPunctualLights.length; l++) {
            var light = validPunctualLights[l];
            this._instancedLightPassPool.lights.push(light);
            this._instancedLightPassPool.dynamicOffsets.push(this._lightBufferStride * l);
          }
          this._instancedQueues.forEach(function (instancedQueue) {
            instancedQueue.uploadBuffers(cmdBuff);
          });
        };
        _proto.recordCommandBuffer = function recordCommandBuffer(device, renderPass, cmdBuff) {
          var globalDSManager = this._pipeline.globalDSManager;
          for (var j = 0; j < this._instancedQueues.length; ++j) {
            var light = this._instancedLightPassPool.lights[j];
            _dynamicOffsets[0] = this._instancedLightPassPool.dynamicOffsets[j];
            var descriptorSet = globalDSManager.getOrCreateDescriptorSet(light);
            this._instancedQueues[j].recordCommandBuffer(device, renderPass, cmdBuff, descriptorSet, _dynamicOffsets);
          }
          for (var i = 0; i < this._lightPasses.length; i++) {
            var _this$_lightPasses$i = this._lightPasses[i],
              subModel = _this$_lightPasses$i.subModel,
              passIdx = _this$_lightPasses$i.passIdx,
              dynamicOffsets = _this$_lightPasses$i.dynamicOffsets,
              lights = _this$_lightPasses$i.lights;
            var pass = subModel.passes[passIdx];
            var shader = subModel.shaders[passIdx];
            var ia = subModel.inputAssembler;
            var pso = PipelineStateManager.getOrCreatePipelineState(device, pass, shader, renderPass, ia);
            var matDS = pass.descriptorSet;
            var localDS = subModel.descriptorSet;
            cmdBuff.bindPipelineState(pso);
            cmdBuff.bindDescriptorSet(SetIndex.MATERIAL, matDS);
            cmdBuff.bindInputAssembler(ia);
            for (var _j = 0; _j < dynamicOffsets.length; ++_j) {
              var _light = lights[_j];
              var _descriptorSet = globalDSManager.getOrCreateDescriptorSet(_light);
              _dynamicOffsets[0] = dynamicOffsets[_j];
              cmdBuff.bindDescriptorSet(SetIndex.GLOBAL, _descriptorSet);
              cmdBuff.bindDescriptorSet(SetIndex.LOCAL, localDS, _dynamicOffsets);
              cmdBuff.draw(ia);
            }
          }
        };
        _proto._lightCulling = function _lightCulling(model, validPunctualLights) {
          var isCulled = false;
          for (var l = 0; l < validPunctualLights.length; l++) {
            var light = validPunctualLights[l];
            switch (light.type) {
              case LightType.SPHERE:
                isCulled = cullSphereLight(light, model);
                break;
              case LightType.SPOT:
                isCulled = cullSpotLight(light, model);
                break;
              case LightType.POINT:
                isCulled = cullPointLight(light, model);
                break;
              case LightType.RANGED_DIRECTIONAL:
                isCulled = cullRangedDirLight(light, model);
                break;
            }
            if (!isCulled) {
              _lightIndices.push(l);
            }
          }
        };
        _proto._addRenderQueue = function _addRenderQueue(pass, subModel, model, lightPassIdx) {
          var validPunctualLights = this._pipeline.pipelineSceneData.validPunctualLights;
          var batchingScheme = pass.batchingScheme;
          var lp = null;
          if (batchingScheme === BatchingSchemes.NONE) {
            lp = _lightPassPool.alloc();
            lp.subModel = subModel;
            lp.passIdx = lightPassIdx;
          }
          for (var l = 0; l < _lightIndices.length; l++) {
            var lightIdx = _lightIndices[l];
            var light = validPunctualLights[lightIdx];
            var visibility = light.visibility;
            if ((visibility & model.node.layer) === model.node.layer) {
              switch (batchingScheme) {
                case BatchingSchemes.INSTANCING:
                  {
                    var buffer = pass.getInstancedBuffer(l);
                    buffer.merge(subModel, lightPassIdx);
                    buffer.dynamicOffsets[0] = this._lightBufferStride;
                    if (!this._instancedQueues[l]) {
                      this._instancedQueues[l] = new RenderInstancedQueue();
                    }
                    this._instancedQueues[l].queue.add(buffer);
                  }
                  break;
                default:
                  lp.lights.push(light);
                  lp.dynamicOffsets.push(this._lightBufferStride * lightIdx);
              }
            }
          }
          if (batchingScheme === BatchingSchemes.NONE) {
            this._lightPasses.push(lp);
          }
        };
        _proto._updateLightDescriptorSet = function _updateLightDescriptorSet(camera, cmdBuff) {
          var device = this._pipeline.device;
          var sceneData = this._pipeline.pipelineSceneData;
          var shadowInfo = sceneData.shadows;
          var shadowFrameBufferMap = sceneData.shadowFrameBufferMap;
          var mainLight = camera.scene.mainLight;
          var packing = supportsR32FloatTexture(device) ? 0.0 : 1.0;
          var globalDSManager = this._pipeline.globalDSManager;
          var validPunctualLights = sceneData.validPunctualLights;
          var cap = this._pipeline.device.capabilities;
          for (var i = 0; i < validPunctualLights.length; i++) {
            var light = validPunctualLights[i];
            var descriptorSet = globalDSManager.getOrCreateDescriptorSet(light);
            if (!descriptorSet) {
              continue;
            }
            var matShadowProj = void 0;
            var matShadowInvProj = void 0;
            switch (light.type) {
              case LightType.SPHERE:
                {
                  if (mainLight) {
                    PipelineUBO.updatePlanarNormalAndDistance(shadowInfo, this._shadowUBO);
                  }
                  this._shadowUBO[UBOShadow.SHADOW_WIDTH_HEIGHT_PCF_BIAS_INFO_OFFSET + 0] = shadowInfo.size.x;
                  this._shadowUBO[UBOShadow.SHADOW_WIDTH_HEIGHT_PCF_BIAS_INFO_OFFSET + 1] = shadowInfo.size.y;
                  this._shadowUBO[UBOShadow.SHADOW_WIDTH_HEIGHT_PCF_BIAS_INFO_OFFSET + 2] = 1.0;
                  this._shadowUBO[UBOShadow.SHADOW_WIDTH_HEIGHT_PCF_BIAS_INFO_OFFSET + 3] = 0.0;
                  this._shadowUBO[UBOShadow.SHADOW_LIGHT_PACKING_NBIAS_NULL_INFO_OFFSET + 0] = LightType.SPHERE;
                  this._shadowUBO[UBOShadow.SHADOW_LIGHT_PACKING_NBIAS_NULL_INFO_OFFSET + 1] = packing;
                  this._shadowUBO[UBOShadow.SHADOW_LIGHT_PACKING_NBIAS_NULL_INFO_OFFSET + 2] = 0.0;
                  this._shadowUBO[UBOShadow.SHADOW_LIGHT_PACKING_NBIAS_NULL_INFO_OFFSET + 3] = 0.0;
                  Color$1.toArray(this._shadowUBO, shadowInfo.shadowColor, UBOShadow.SHADOW_COLOR_OFFSET);
                  break;
                }
              case LightType.SPOT:
                {
                  var spotLight = light;
                  if (mainLight) {
                    PipelineUBO.updatePlanarNormalAndDistance(shadowInfo, this._shadowUBO);
                  }
                  Mat4.invert(_matShadowView, light.node.getWorldMatrix());
                  Mat4.perspective(_matShadowViewProj, light.angle, 1.0, 0.001, light.range, true, cap.clipSpaceMinZ, cap.clipSpaceSignY, 0);
                  matShadowProj = _matShadowViewProj.clone();
                  matShadowInvProj = _matShadowViewProj.clone().invert();
                  Mat4.multiply(_matShadowViewProj, _matShadowViewProj, _matShadowView);
                  Mat4.toArray(this._shadowUBO, _matShadowView, UBOShadow.MAT_LIGHT_VIEW_OFFSET);
                  Mat4.toArray(this._shadowUBO, _matShadowViewProj, UBOShadow.MAT_LIGHT_VIEW_PROJ_OFFSET);
                  this._shadowUBO[UBOShadow.SHADOW_NEAR_FAR_LINEAR_SATURATION_INFO_OFFSET + 0] = 0.01;
                  this._shadowUBO[UBOShadow.SHADOW_NEAR_FAR_LINEAR_SATURATION_INFO_OFFSET + 1] = light.range;
                  this._shadowUBO[UBOShadow.SHADOW_NEAR_FAR_LINEAR_SATURATION_INFO_OFFSET + 2] = 0.0;
                  this._shadowUBO[UBOShadow.SHADOW_NEAR_FAR_LINEAR_SATURATION_INFO_OFFSET + 3] = 0.0;
                  this._shadowUBO[UBOShadow.SHADOW_WIDTH_HEIGHT_PCF_BIAS_INFO_OFFSET + 0] = shadowInfo.size.x;
                  this._shadowUBO[UBOShadow.SHADOW_WIDTH_HEIGHT_PCF_BIAS_INFO_OFFSET + 1] = shadowInfo.size.y;
                  this._shadowUBO[UBOShadow.SHADOW_WIDTH_HEIGHT_PCF_BIAS_INFO_OFFSET + 2] = spotLight.shadowPcf;
                  this._shadowUBO[UBOShadow.SHADOW_WIDTH_HEIGHT_PCF_BIAS_INFO_OFFSET + 3] = spotLight.shadowBias;
                  this._shadowUBO[UBOShadow.SHADOW_LIGHT_PACKING_NBIAS_NULL_INFO_OFFSET + 0] = LightType.SPOT;
                  this._shadowUBO[UBOShadow.SHADOW_LIGHT_PACKING_NBIAS_NULL_INFO_OFFSET + 1] = packing;
                  this._shadowUBO[UBOShadow.SHADOW_LIGHT_PACKING_NBIAS_NULL_INFO_OFFSET + 2] = spotLight.shadowNormalBias;
                  this._shadowUBO[UBOShadow.SHADOW_LIGHT_PACKING_NBIAS_NULL_INFO_OFFSET + 3] = 0.0;
                  this._shadowUBO[UBOShadow.SHADOW_PROJ_DEPTH_INFO_OFFSET + 0] = matShadowProj.m10;
                  this._shadowUBO[UBOShadow.SHADOW_PROJ_DEPTH_INFO_OFFSET + 1] = matShadowProj.m14;
                  this._shadowUBO[UBOShadow.SHADOW_PROJ_DEPTH_INFO_OFFSET + 2] = matShadowProj.m11;
                  this._shadowUBO[UBOShadow.SHADOW_PROJ_DEPTH_INFO_OFFSET + 3] = matShadowProj.m15;
                  this._shadowUBO[UBOShadow.SHADOW_INV_PROJ_DEPTH_INFO_OFFSET + 0] = matShadowInvProj.m10;
                  this._shadowUBO[UBOShadow.SHADOW_INV_PROJ_DEPTH_INFO_OFFSET + 1] = matShadowInvProj.m14;
                  this._shadowUBO[UBOShadow.SHADOW_INV_PROJ_DEPTH_INFO_OFFSET + 2] = matShadowInvProj.m11;
                  this._shadowUBO[UBOShadow.SHADOW_INV_PROJ_DEPTH_INFO_OFFSET + 3] = matShadowInvProj.m15;
                  this._shadowUBO[UBOShadow.SHADOW_PROJ_INFO_OFFSET + 0] = matShadowProj.m00;
                  this._shadowUBO[UBOShadow.SHADOW_PROJ_INFO_OFFSET + 1] = matShadowProj.m05;
                  this._shadowUBO[UBOShadow.SHADOW_PROJ_INFO_OFFSET + 2] = 1.0 / matShadowProj.m00;
                  this._shadowUBO[UBOShadow.SHADOW_PROJ_INFO_OFFSET + 3] = 1.0 / matShadowProj.m05;
                  Color$1.toArray(this._shadowUBO, shadowInfo.shadowColor, UBOShadow.SHADOW_COLOR_OFFSET);
                  if (shadowFrameBufferMap.has(light)) {
                    var _shadowFrameBufferMap;
                    var texture = (_shadowFrameBufferMap = shadowFrameBufferMap.get(light)) === null || _shadowFrameBufferMap === void 0 ? void 0 : _shadowFrameBufferMap.colorTextures[0];
                    if (texture) {
                      descriptorSet.bindTexture(UNIFORM_SPOT_SHADOW_MAP_TEXTURE_BINDING, texture);
                    }
                  }
                  break;
                }
              case LightType.POINT:
                {
                  if (mainLight) {
                    PipelineUBO.updatePlanarNormalAndDistance(shadowInfo, this._shadowUBO);
                  }
                  this._shadowUBO[UBOShadow.SHADOW_WIDTH_HEIGHT_PCF_BIAS_INFO_OFFSET + 0] = shadowInfo.size.x;
                  this._shadowUBO[UBOShadow.SHADOW_WIDTH_HEIGHT_PCF_BIAS_INFO_OFFSET + 1] = shadowInfo.size.y;
                  this._shadowUBO[UBOShadow.SHADOW_WIDTH_HEIGHT_PCF_BIAS_INFO_OFFSET + 2] = 1.0;
                  this._shadowUBO[UBOShadow.SHADOW_WIDTH_HEIGHT_PCF_BIAS_INFO_OFFSET + 3] = 0.0;
                  this._shadowUBO[UBOShadow.SHADOW_LIGHT_PACKING_NBIAS_NULL_INFO_OFFSET + 0] = LightType.POINT;
                  this._shadowUBO[UBOShadow.SHADOW_LIGHT_PACKING_NBIAS_NULL_INFO_OFFSET + 1] = packing;
                  this._shadowUBO[UBOShadow.SHADOW_LIGHT_PACKING_NBIAS_NULL_INFO_OFFSET + 2] = 0.0;
                  this._shadowUBO[UBOShadow.SHADOW_LIGHT_PACKING_NBIAS_NULL_INFO_OFFSET + 3] = 0.0;
                  Color$1.toArray(this._shadowUBO, shadowInfo.shadowColor, UBOShadow.SHADOW_COLOR_OFFSET);
                  break;
                }
            }
            descriptorSet.update();
            var binding = isEnableEffect() ? getDescBindingFromName('CCShadow') : UBOShadow.BINDING;
            cmdBuff.updateBuffer(descriptorSet.getBuffer(binding), this._shadowUBO);
          }
        };
        _proto._updateUBOs = function _updateUBOs(camera, cmdBuff) {
          var exposure = camera.exposure;
          var sceneData = this._pipeline.pipelineSceneData;
          var isHDR = sceneData.isHDR;
          var shadowInfo = sceneData.shadows;
          var validPunctualLights = sceneData.validPunctualLights;
          if (validPunctualLights.length > this._lightBufferCount) {
            this._firstLightBufferView.destroy();
            this._lightBufferCount = nextPow2(validPunctualLights.length);
            this._lightBuffer.resize(this._lightBufferStride * this._lightBufferCount);
            this._lightBufferData = new Float32Array(this._lightBufferElementCount * this._lightBufferCount);
            this._firstLightBufferView.initialize(new BufferViewInfo(this._lightBuffer, 0, UBOForwardLight.SIZE));
          }
          for (var l = 0, offset = 0; l < validPunctualLights.length; l++, offset += this._lightBufferElementCount) {
            var light = validPunctualLights[l];
            switch (light.type) {
              case LightType.SPHERE:
                Vec3.toArray(_vec4Array, light.position);
                _vec4Array[3] = LightType.SPHERE;
                this._lightBufferData.set(_vec4Array, offset + UBOForwardLight.LIGHT_POS_OFFSET);
                _vec4Array[0] = light.size;
                _vec4Array[1] = light.range;
                _vec4Array[2] = 0.0;
                _vec4Array[3] = 0.0;
                this._lightBufferData.set(_vec4Array, offset + UBOForwardLight.LIGHT_SIZE_RANGE_ANGLE_OFFSET);
                Vec3.toArray(_vec4Array, light.color);
                if (light.useColorTemperature) {
                  var finalColor = light.finalColor;
                  _vec4Array[0] = finalColor.x;
                  _vec4Array[1] = finalColor.y;
                  _vec4Array[2] = finalColor.z;
                }
                if (isHDR) {
                  _vec4Array[3] = light.luminance * exposure * this._lightMeterScale;
                } else {
                  _vec4Array[3] = light.luminance;
                }
                this._lightBufferData.set(_vec4Array, offset + UBOForwardLight.LIGHT_COLOR_OFFSET);
                break;
              case LightType.SPOT:
                Vec3.toArray(_vec4Array, light.position);
                _vec4Array[3] = LightType.SPOT;
                this._lightBufferData.set(_vec4Array, offset + UBOForwardLight.LIGHT_POS_OFFSET);
                _vec4Array[0] = light.size;
                _vec4Array[1] = light.range;
                _vec4Array[2] = light.spotAngle;
                _vec4Array[3] = shadowInfo.enabled && light.shadowEnabled && shadowInfo.type === ShadowType.ShadowMap ? 1 : 0;
                this._lightBufferData.set(_vec4Array, offset + UBOForwardLight.LIGHT_SIZE_RANGE_ANGLE_OFFSET);
                Vec3.toArray(_vec4Array, light.direction);
                this._lightBufferData.set(_vec4Array, offset + UBOForwardLight.LIGHT_DIR_OFFSET);
                Vec3.toArray(_vec4Array, light.color);
                if (light.useColorTemperature) {
                  var _finalColor = light.finalColor;
                  _vec4Array[0] = _finalColor.x;
                  _vec4Array[1] = _finalColor.y;
                  _vec4Array[2] = _finalColor.z;
                }
                if (isHDR) {
                  _vec4Array[3] = light.luminance * exposure * this._lightMeterScale;
                } else {
                  _vec4Array[3] = light.luminance;
                }
                this._lightBufferData.set(_vec4Array, offset + UBOForwardLight.LIGHT_COLOR_OFFSET);
                break;
              case LightType.POINT:
                Vec3.toArray(_vec4Array, light.position);
                _vec4Array[3] = LightType.POINT;
                this._lightBufferData.set(_vec4Array, offset + UBOForwardLight.LIGHT_POS_OFFSET);
                _vec4Array[0] = 0.0;
                _vec4Array[1] = light.range;
                _vec4Array[2] = 0.0;
                _vec4Array[3] = 0.0;
                this._lightBufferData.set(_vec4Array, offset + UBOForwardLight.LIGHT_SIZE_RANGE_ANGLE_OFFSET);
                Vec3.toArray(_vec4Array, light.color);
                if (light.useColorTemperature) {
                  var _finalColor2 = light.finalColor;
                  _vec4Array[0] = _finalColor2.x;
                  _vec4Array[1] = _finalColor2.y;
                  _vec4Array[2] = _finalColor2.z;
                }
                if (isHDR) {
                  _vec4Array[3] = light.luminance * exposure * this._lightMeterScale;
                } else {
                  _vec4Array[3] = light.luminance;
                }
                this._lightBufferData.set(_vec4Array, offset + UBOForwardLight.LIGHT_COLOR_OFFSET);
                break;
              case LightType.RANGED_DIRECTIONAL:
                Vec3.toArray(_vec4Array, light.position);
                _vec4Array[3] = LightType.RANGED_DIRECTIONAL;
                this._lightBufferData.set(_vec4Array, offset + UBOForwardLight.LIGHT_POS_OFFSET);
                Vec3.toArray(_vec4Array, light.right);
                _vec4Array[3] = 0;
                this._lightBufferData.set(_vec4Array, offset + UBOForwardLight.LIGHT_SIZE_RANGE_ANGLE_OFFSET);
                Vec3.toArray(_vec4Array, light.direction);
                _vec4Array[3] = 0;
                this._lightBufferData.set(_vec4Array, offset + UBOForwardLight.LIGHT_DIR_OFFSET);
                var scale = light.scale;
                _v3$2.set(scale.x * 0.5, scale.y * 0.5, scale.z * 0.5);
                Vec3.toArray(_vec4Array, _v3$2);
                _vec4Array[3] = 0;
                this._lightBufferData.set(_vec4Array, offset + UBOForwardLight.LIGHT_BOUNDING_SIZE_VS_OFFSET);
                Vec3.toArray(_vec4Array, light.color);
                if (light.useColorTemperature) {
                  var _finalColor3 = light.finalColor;
                  _vec4Array[0] = _finalColor3.x;
                  _vec4Array[1] = _finalColor3.y;
                  _vec4Array[2] = _finalColor3.z;
                }
                if (isHDR) {
                  _vec4Array[3] = light.illuminance * exposure;
                } else {
                  _vec4Array[3] = light.illuminance;
                }
                this._lightBufferData.set(_vec4Array, offset + UBOForwardLight.LIGHT_COLOR_OFFSET);
                break;
            }
          }
          cmdBuff.updateBuffer(this._lightBuffer, this._lightBufferData);
        };
        return RenderAdditiveLightQueue;
      }();

      var _ab = new AABB();
      var _phaseID$3 = getPhaseID('planar-shadow');
      function getPlanarShadowPassIndex(subModel) {
        var passes = subModel.passes;
        var r = legacyCC.rendering;
        if (isEnableEffect()) _phaseID$3 = r.getPhaseID(r.getPassID('default'), 'planar-shadow');
        for (var k = 0; k < passes.length; k++) {
          if ((!r || !r.enableEffectImport) && passes[k].phase === _phaseID$3 || isEnableEffect() && passes[k].phaseID === _phaseID$3) {
            return k;
          }
        }
        return -1;
      }
      var PlanarShadowQueue = function () {
        function PlanarShadowQueue(pipeline) {
          this._subModelArray = [];
          this._shaderArray = [];
          this._passArray = [];
          this._castModels = [];
          this._instancedQueue = new RenderInstancedQueue();
          this._pipeline = void 0;
          this._pipeline = pipeline;
        }
        var _proto = PlanarShadowQueue.prototype;
        _proto.clear = function clear() {
          this._subModelArray.length = 0;
          this._shaderArray.length = 0;
          this._passArray.length = 0;
          this._instancedQueue.clear();
          this._castModels.length = 0;
        };
        _proto.gatherShadowPasses = function gatherShadowPasses(camera, cmdBuff) {
          this.clear();
          var pipelineSceneData = this._pipeline.pipelineSceneData;
          var shadows = pipelineSceneData.shadows;
          if (!shadows.enabled || shadows.type !== ShadowType.Planar || shadows.normal.length() < 0.000001) {
            return;
          }
          var scene = camera.scene;
          var frustum = camera.frustum;
          var shadowVisible = (camera.visibility & Layers.BitMask.DEFAULT) !== 0;
          if (!scene.mainLight || !shadowVisible) {
            return;
          }
          var models = scene.models;
          var visibility = camera.visibility;
          for (var i = 0; i < models.length; i++) {
            var model = models[i];
            if (scene.isCulledByLod(camera, model)) {
              continue;
            }
            if (model.enabled && model.node && model.castShadow && model.node && (visibility & model.node.layer) === model.node.layer) {
              this._castModels.push(model);
            }
          }
          for (var _i = 0; _i < this._castModels.length; _i++) {
            var _model = this._castModels[_i];
            if (_model.worldBounds) {
              AABB.transform(_ab, _model.worldBounds, shadows.matLight);
              if (!intersect.aabbFrustum(_ab, frustum)) {
                continue;
              }
            }
            var subModels = _model.subModels;
            for (var j = 0; j < subModels.length; j++) {
              var subModel = subModels[j];
              var shadowPassIdx = getPlanarShadowPassIndex(subModel);
              if (shadowPassIdx < 0) {
                this._subModelArray.push(subModel);
                var planarShader = shadows.getPlanarShader(subModel.patches);
                if (!planarShader) {
                  continue;
                }
                this._shaderArray.push(planarShader);
                this._passArray.push(shadows.material.passes[0]);
                continue;
              }
              var pass = subModel.passes[shadowPassIdx];
              var batchingScheme = pass.batchingScheme;
              if (batchingScheme === BatchingSchemes.INSTANCING) {
                var buffer = pass.getInstancedBuffer();
                buffer.merge(subModel, shadowPassIdx);
                this._instancedQueue.queue.add(buffer);
              } else {
                var shader = subModel.shaders[shadowPassIdx];
                this._subModelArray.push(subModel);
                if (shader) this._shaderArray.push(shader);
                this._passArray.push(pass);
              }
            }
          }
          this._instancedQueue.uploadBuffers(cmdBuff);
        };
        _proto.recordCommandBuffer = function recordCommandBuffer(device, renderPass, cmdBuff) {
          var shadows = this._pipeline.pipelineSceneData.shadows;
          if (!shadows.enabled || shadows.type !== ShadowType.Planar) {
            return;
          }
          this._instancedQueue.recordCommandBuffer(device, renderPass, cmdBuff);
          for (var i = 0; i < this._subModelArray.length; ++i) {
            var subModel = this._subModelArray[i];
            var shader = this._shaderArray[i];
            var pass = this._passArray[i];
            var ia = subModel.inputAssembler;
            var pso = PipelineStateManager.getOrCreatePipelineState(device, pass, shader, renderPass, ia);
            var descriptorSet = pass.descriptorSet;
            cmdBuff.bindPipelineState(pso);
            cmdBuff.bindDescriptorSet(SetIndex.MATERIAL, descriptorSet);
            cmdBuff.bindDescriptorSet(SetIndex.LOCAL, subModel.descriptorSet);
            cmdBuff.bindInputAssembler(ia);
            cmdBuff.draw(ia);
          }
        };
        return PlanarShadowQueue;
      }();

      var UIPhase = function () {
        function UIPhase() {
          this._phaseID = getPhaseID('default');
          var r = legacyCC.rendering;
          if (isEnableEffect()) this._phaseID = r.getPhaseID(r.getPassID('default'), 'default');
        }
        var _proto = UIPhase.prototype;
        _proto.activate = function activate(pipeline) {
          this._pipeline = pipeline;
        };
        _proto.render = function render(camera, renderPass) {
          var pipeline = this._pipeline;
          var device = pipeline.device;
          var cmdBuff = pipeline.commandBuffers[0];
          var scene = camera.scene;
          var batches = scene.batches;
          for (var i = 0; i < batches.length; i++) {
            var batch = batches[i];
            var visible = false;
            if (camera.visibility & batch.visFlags) {
              visible = true;
            }
            if (!visible) continue;
            var count = batch.shaders.length;
            for (var j = 0; j < count; j++) {
              var pass = batch.passes[j];
              if (pass.phase !== this._phaseID) continue;
              var shader = batch.shaders[j];
              var inputAssembler = batch.inputAssembler;
              var pso = PipelineStateManager.getOrCreatePipelineState(device, pass, shader, renderPass, inputAssembler);
              cmdBuff.bindPipelineState(pso);
              cmdBuff.bindDescriptorSet(SetIndex.MATERIAL, pass.descriptorSet);
              var ds = batch.descriptorSet;
              cmdBuff.bindDescriptorSet(SetIndex.LOCAL, ds);
              cmdBuff.bindInputAssembler(inputAssembler);
              cmdBuff.draw(inputAssembler);
            }
          }
        };
        return UIPhase;
      }();

      var _dec$2F, _dec2$1Y, _class$2C, _class2$2n, _initializer$26, _class3$I;
      var colors$6 = [new Color(0, 0, 0, 1)];
      var ForwardStage = exports('da', (_dec$2F = ccclass$n('ForwardStage'), _dec2$1Y = type$7([RenderQueueDesc]), _dec$2F(_class$2C = (_class2$2n = (_class3$I = function (_RenderStage) {
        _inheritsLoose(ForwardStage, _RenderStage);
        function ForwardStage() {
          var _this;
          _this = _RenderStage.call(this) || this;
          _this.renderQueues = _initializer$26 && _initializer$26();
          _this._renderQueues = [];
          _this._renderArea = new Rect();
          _this._instancedQueue = void 0;
          _this._phaseID = getPhaseID('default');
          _this._clearFlag = 0xffffffff;
          _this.additiveInstanceQueues = [];
          _this._instancedQueue = new RenderInstancedQueue();
          _this._uiPhase = new UIPhase();
          return _this;
        }
        var _proto = ForwardStage.prototype;
        _proto.addRenderInstancedQueue = function addRenderInstancedQueue(queue) {
          if (this.additiveInstanceQueues.includes(queue)) {
            return;
          }
          this.additiveInstanceQueues.push(queue);
        };
        _proto.removeRenderInstancedQueue = function removeRenderInstancedQueue(queue) {
          var index = this.additiveInstanceQueues.indexOf(queue);
          if (index > -1) {
            this.additiveInstanceQueues.splice(index, 1);
          }
        };
        _proto.initialize = function initialize(info) {
          _RenderStage.prototype.initialize.call(this, info);
          if (info.renderQueues) {
            this.renderQueues = info.renderQueues;
          }
          return true;
        };
        _proto.activate = function activate(pipeline, flow) {
          _RenderStage.prototype.activate.call(this, pipeline, flow);
          for (var i = 0; i < this.renderQueues.length; i++) {
            this._renderQueues[i] = convertRenderQueue(this.renderQueues[i]);
          }
          this._additiveLightQueue = new RenderAdditiveLightQueue(this._pipeline);
          this._planarQueue = new PlanarShadowQueue(this._pipeline);
          this._uiPhase.activate(pipeline);
        };
        _proto.destroy = function destroy() {};
        _proto.render = function render(camera) {
          var _camera$geometryRende;
          this._instancedQueue.clear();
          var pipeline = this._pipeline;
          var device = pipeline.device;
          this._renderQueues.forEach(renderQueueClearFunc);
          var renderObjects = pipeline.pipelineSceneData.renderObjects;
          var m = 0;
          var p = 0;
          var k = 0;
          for (var i = 0; i < renderObjects.length; ++i) {
            var ro = renderObjects[i];
            var subModels = ro.model.subModels;
            for (m = 0; m < subModels.length; ++m) {
              var subModel = subModels[m];
              var passes = subModel.passes;
              for (p = 0; p < passes.length; ++p) {
                var pass = passes[p];
                if (pass.phase !== this._phaseID) continue;
                var batchingScheme = pass.batchingScheme;
                if (batchingScheme === BatchingSchemes.INSTANCING) {
                  var instancedBuffer = pass.getInstancedBuffer();
                  instancedBuffer.merge(subModel, p);
                  this._instancedQueue.queue.add(instancedBuffer);
                } else {
                  for (k = 0; k < this._renderQueues.length; k++) {
                    this._renderQueues[k].insertRenderPass(ro, m, p);
                  }
                }
              }
            }
          }
          this._instancedQueue.sort();
          this._renderQueues.forEach(renderQueueSortFunc);
          var cmdBuff = pipeline.commandBuffers[0];
          pipeline.pipelineUBO.updateShadowUBO(camera);
          for (var _i = 0; _i < this.additiveInstanceQueues.length; _i++) {
            this.additiveInstanceQueues[_i].uploadBuffers(cmdBuff);
          }
          this._instancedQueue.uploadBuffers(cmdBuff);
          this._additiveLightQueue.gatherLightPasses(camera, cmdBuff);
          this._planarQueue.gatherShadowPasses(camera, cmdBuff);
          if (camera.clearFlag & ClearFlagBit.COLOR) {
            colors$6[0].x = camera.clearColor.x;
            colors$6[0].y = camera.clearColor.y;
            colors$6[0].z = camera.clearColor.z;
            colors$6[0].w = camera.clearColor.w;
          }
          pipeline.generateRenderArea(camera, this._renderArea);
          var framebuffer = camera.window.framebuffer;
          var renderPass = pipeline.getRenderPass(camera.clearFlag & this._clearFlag, framebuffer);
          cmdBuff.beginRenderPass(renderPass, framebuffer, this._renderArea, colors$6, camera.clearDepth, camera.clearStencil);
          cmdBuff.bindDescriptorSet(SetIndex.GLOBAL, pipeline.descriptorSet);
          this._renderQueues[0].recordCommandBuffer(device, renderPass, cmdBuff);
          for (var _i2 = 0; _i2 < this.additiveInstanceQueues.length; _i2++) {
            this.additiveInstanceQueues[_i2].recordCommandBuffer(device, renderPass, cmdBuff);
          }
          this._instancedQueue.recordCommandBuffer(device, renderPass, cmdBuff);
          this._additiveLightQueue.recordCommandBuffer(device, renderPass, cmdBuff);
          cmdBuff.bindDescriptorSet(SetIndex.GLOBAL, pipeline.descriptorSet);
          this._planarQueue.recordCommandBuffer(device, renderPass, cmdBuff);
          this._renderQueues[1].recordCommandBuffer(device, renderPass, cmdBuff);
          (_camera$geometryRende = camera.geometryRenderer) === null || _camera$geometryRende === void 0 ? void 0 : _camera$geometryRende.render(renderPass, cmdBuff, pipeline.pipelineSceneData);
          this._uiPhase.render(camera, renderPass);
          renderProfiler(device, renderPass, cmdBuff, pipeline.profiler, camera);
          cmdBuff.endRenderPass();
        };
        return ForwardStage;
      }(RenderStage), _class3$I.initInfo = {
        name: 'ForwardStage',
        priority: ForwardStagePriority.FORWARD,
        tag: 0,
        renderQueues: [{
          isTransparent: false,
          sortMode: RenderQueueSortMode.FRONT_TO_BACK,
          stages: ['default']
        }, {
          isTransparent: true,
          sortMode: RenderQueueSortMode.BACK_TO_FRONT,
          stages: ['default', 'planarShadow']
        }]
      }, _class3$I), (_initializer$26 = applyDecoratedInitializer(_class2$2n.prototype, "renderQueues", [_dec2$1Y, serializable$j], function () {
        return [];
      })), _class2$2n)) || _class$2C));

      var _dec$2E, _class$2B, _class2$2m;
      var ForwardFlow = exports('d9', (_dec$2E = ccclass$n('ForwardFlow'), _dec$2E(_class$2B = (_class2$2m = function (_RenderFlow) {
        _inheritsLoose(ForwardFlow, _RenderFlow);
        function ForwardFlow() {
          return _RenderFlow.apply(this, arguments) || this;
        }
        var _proto = ForwardFlow.prototype;
        _proto.initialize = function initialize(info) {
          _RenderFlow.prototype.initialize.call(this, info);
          if (this._stages.length === 0) {
            var forwardStage = new ForwardStage();
            forwardStage.initialize(ForwardStage.initInfo);
            this._stages.push(forwardStage);
          }
          return true;
        };
        _proto.activate = function activate(pipeline) {
          _RenderFlow.prototype.activate.call(this, pipeline);
        };
        _proto.render = function render(camera) {
          _RenderFlow.prototype.render.call(this, camera);
        };
        _proto.destroy = function destroy() {
          _RenderFlow.prototype.destroy.call(this);
        };
        return ForwardFlow;
      }(RenderFlow), _class2$2m.initInfo = {
        name: PIPELINE_FLOW_FORWARD,
        priority: ForwardFlowPriority.FORWARD,
        stages: []
      }, _class2$2m)) || _class$2B));

      var _phaseID$2 = getPhaseID('shadow-caster');
      function getShadowPassIndex(subModel) {
        var passes = subModel.passes;
        var r = legacyCC.rendering;
        if (isEnableEffect()) _phaseID$2 = r.getPhaseID(r.getPassID('default'), 'shadow-caster');
        for (var k = 0; k < passes.length; k++) {
          if ((!r || !r.enableEffectImport) && passes[k].phase === _phaseID$2 || isEnableEffect() && passes[k].phaseID === _phaseID$2) {
            return k;
          }
        }
        return -1;
      }
      var RenderShadowMapBatchedQueue = function () {
        function RenderShadowMapBatchedQueue(pipeline) {
          this._pipeline = void 0;
          this._subModelsArray = [];
          this._passArray = [];
          this._shaderArray = [];
          this._instancedQueue = void 0;
          this._pipeline = pipeline;
          this._instancedQueue = new RenderInstancedQueue();
        }
        var _proto = RenderShadowMapBatchedQueue.prototype;
        _proto.gatherLightPasses = function gatherLightPasses(camera, light, cmdBuff, level) {
          if (level === void 0) {
            level = 0;
          }
          this.clear();
          var sceneData = this._pipeline.pipelineSceneData;
          var shadowInfo = sceneData.shadows;
          if (light && shadowInfo.enabled && shadowInfo.type === ShadowType.ShadowMap) {
            switch (light.type) {
              case LightType.DIRECTIONAL:
                var dirLight = light;
                if (dirLight.shadowEnabled) {
                  var csmLayers = sceneData.csmLayers;
                  var layer;
                  if (dirLight.shadowFixedArea) {
                    layer = csmLayers.specialLayer;
                  } else {
                    layer = csmLayers.layers[level];
                  }
                  shadowCulling(camera, sceneData, layer);
                  var dirShadowObjects = layer.shadowObjects;
                  for (var i = 0; i < dirShadowObjects.length; i++) {
                    var ro = dirShadowObjects[i];
                    var model = ro.model;
                    this.add(model, level);
                  }
                }
                break;
              case LightType.SPOT:
                var spotLight = light;
                if (spotLight.shadowEnabled) {
                  var visibility = spotLight.visibility;
                  var castShadowObjects = sceneData.csmLayers.castShadowObjects;
                  for (var _i = 0; _i < castShadowObjects.length; _i++) {
                    var _ro = castShadowObjects[_i];
                    var _model = _ro.model;
                    if (_model.worldBounds) {
                      if ((visibility & _model.node.layer) !== _model.node.layer || !intersect.aabbFrustum(_model.worldBounds, spotLight.frustum)) {
                        continue;
                      }
                    }
                    this.add(_model, level);
                  }
                }
                break;
            }
            this._instancedQueue.uploadBuffers(cmdBuff);
          }
        };
        _proto.clear = function clear() {
          this._subModelsArray.length = 0;
          this._shaderArray.length = 0;
          this._passArray.length = 0;
          this._instancedQueue.clear();
        };
        _proto.add = function add(model, level) {
          var subModels = model.subModels;
          for (var j = 0; j < subModels.length; j++) {
            var subModel = subModels[j];
            var shadowPassIdx = getShadowPassIndex(subModel);
            if (shadowPassIdx < 0) {
              continue;
            }
            var pass = subModel.passes[shadowPassIdx];
            var batchingScheme = pass.batchingScheme;
            if (batchingScheme === BatchingSchemes.INSTANCING) {
              var buffer = pass.getInstancedBuffer(level);
              buffer.merge(subModel, shadowPassIdx);
              this._instancedQueue.queue.add(buffer);
            } else {
              var shader = subModel.shaders[shadowPassIdx];
              this._subModelsArray.push(subModel);
              if (shader) this._shaderArray.push(shader);
              this._passArray.push(pass);
            }
          }
        };
        _proto.recordCommandBuffer = function recordCommandBuffer(device, renderPass, cmdBuff) {
          this._instancedQueue.recordCommandBuffer(device, renderPass, cmdBuff);
          for (var i = 0; i < this._subModelsArray.length; ++i) {
            var subModel = this._subModelsArray[i];
            var shader = this._shaderArray[i];
            var pass = this._passArray[i];
            var ia = subModel.inputAssembler;
            var pso = PipelineStateManager.getOrCreatePipelineState(device, pass, shader, renderPass, ia);
            var descriptorSet = pass.descriptorSet;
            cmdBuff.bindPipelineState(pso);
            cmdBuff.bindDescriptorSet(SetIndex.MATERIAL, descriptorSet);
            cmdBuff.bindDescriptorSet(SetIndex.LOCAL, subModel.descriptorSet);
            cmdBuff.bindInputAssembler(ia);
            cmdBuff.draw(ia);
          }
        };
        return RenderShadowMapBatchedQueue;
      }();

      var _dec$2D, _class$2A, _class2$2l;
      var colors$5 = [new Color(1, 1, 1, 1)];
      var ShadowStage = exports('di', (_dec$2D = ccclass$n('ShadowStage'), _dec$2D(_class$2A = (_class2$2l = function (_RenderStage) {
        _inheritsLoose(ShadowStage, _RenderStage);
        function ShadowStage() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _RenderStage.call.apply(_RenderStage, [this].concat(args)) || this;
          _this._additiveShadowQueue = void 0;
          _this._shadowFrameBuffer = null;
          _this._renderArea = new Rect();
          _this._light = null;
          _this._globalDS = null;
          _this._level = 0;
          _this._isShadowMapCleared = false;
          return _this;
        }
        var _proto = ShadowStage.prototype;
        _proto.setUsage = function setUsage(globalDS, light, shadowFrameBuffer, level) {
          if (level === void 0) {
            level = 0;
          }
          this._globalDS = globalDS;
          this._light = light;
          this._shadowFrameBuffer = shadowFrameBuffer;
          this._level = level;
        };
        _proto.destroy = function destroy() {
          var _this$_additiveShadow;
          this._shadowFrameBuffer = null;
          this._globalDS = null;
          this._light = null;
          (_this$_additiveShadow = this._additiveShadowQueue) === null || _this$_additiveShadow === void 0 ? void 0 : _this$_additiveShadow.clear();
        };
        _proto.clearFramebuffer = function clearFramebuffer(camera) {
          if (!this._light || !this._shadowFrameBuffer || this._isShadowMapCleared) {
            return;
          }
          colors$5[0].w = camera.clearColor.w;
          var pipeline = this._pipeline;
          var pipelineSceneData = pipeline.pipelineSceneData;
          var shadingScale = pipelineSceneData.shadingScale;
          var shadowInfo = pipelineSceneData.shadows;
          var vp = camera.viewport;
          var shadowMapSize = shadowInfo.size;
          this._renderArea.x = vp.x * shadowMapSize.x;
          this._renderArea.y = vp.y * shadowMapSize.y;
          this._renderArea.width = vp.width * shadowMapSize.x * shadingScale;
          this._renderArea.height = vp.height * shadowMapSize.y * shadingScale;
          var cmdBuff = pipeline.commandBuffers[0];
          var renderPass = this._shadowFrameBuffer.renderPass;
          cmdBuff.beginRenderPass(renderPass, this._shadowFrameBuffer, this._renderArea, colors$5, camera.clearDepth, camera.clearStencil);
          cmdBuff.endRenderPass();
          this._isShadowMapCleared = true;
        };
        _proto.render = function render(camera) {
          var pipeline = this._pipeline;
          var pipelineSceneData = pipeline.pipelineSceneData;
          var shadowInfo = pipelineSceneData.shadows;
          var descriptorSet = this._globalDS;
          var cmdBuff = pipeline.commandBuffers[0];
          var level = this._level;
          var device = pipeline.device;
          if (!this._light || !this._shadowFrameBuffer) {
            return;
          }
          this._pipeline.pipelineUBO.updateShadowUBOLight(descriptorSet, this._light, level);
          this._additiveShadowQueue.gatherLightPasses(camera, this._light, cmdBuff, level);
          var shadowMapSize = shadowInfo.size;
          switch (this._light.type) {
            case LightType.DIRECTIONAL:
              {
                var mainLight = this._light;
                if (mainLight.shadowFixedArea || mainLight.csmLevel === CSMLevel.LEVEL_1 || !pipelineSceneData.csmSupported) {
                  this._renderArea.x = 0;
                  this._renderArea.y = 0;
                  this._renderArea.width = shadowMapSize.x;
                  this._renderArea.height = shadowMapSize.y;
                } else {
                  var screenSpaceSignY = device.capabilities.screenSpaceSignY;
                  this._renderArea.x = level % 2 * 0.5 * shadowMapSize.x;
                  if (screenSpaceSignY > 0.0) {
                    this._renderArea.y = (1 - Math.floor(level / 2)) * 0.5 * shadowMapSize.y;
                  } else {
                    this._renderArea.y = Math.floor(level / 2) * 0.5 * shadowMapSize.y;
                  }
                  this._renderArea.width = 0.5 * shadowMapSize.x;
                  this._renderArea.height = 0.5 * shadowMapSize.y;
                }
                break;
              }
            case LightType.SPOT:
              {
                this._renderArea.x = 0;
                this._renderArea.y = 0;
                this._renderArea.width = shadowMapSize.x;
                this._renderArea.height = shadowMapSize.y;
                break;
              }
          }
          var renderPass = this._shadowFrameBuffer.renderPass;
          cmdBuff.beginRenderPass(renderPass, this._shadowFrameBuffer, this._renderArea, colors$5, camera.clearDepth, camera.clearStencil);
          cmdBuff.bindDescriptorSet(SetIndex.GLOBAL, descriptorSet);
          this._additiveShadowQueue.recordCommandBuffer(device, renderPass, cmdBuff);
          cmdBuff.endRenderPass();
          this._isShadowMapCleared = false;
        };
        _proto.activate = function activate(pipeline, flow) {
          _RenderStage.prototype.activate.call(this, pipeline, flow);
          this._additiveShadowQueue = new RenderShadowMapBatchedQueue(pipeline);
          this._isShadowMapCleared = false;
        };
        return ShadowStage;
      }(RenderStage), _class2$2l.initInfo = {
        name: 'ShadowStage',
        priority: ForwardStagePriority.FORWARD,
        tag: 0
      }, _class2$2l)) || _class$2A));

      var _dec$2C, _class$2z, _class2$2k;
      var _validLights = [];
      var ShadowFlow = exports('dh', (_dec$2C = ccclass$n('ShadowFlow'), _dec$2C(_class$2z = (_class2$2k = function (_RenderFlow) {
        _inheritsLoose(ShadowFlow, _RenderFlow);
        function ShadowFlow() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _RenderFlow.call.apply(_RenderFlow, [this].concat(args)) || this;
          _this._shadowRenderPass = null;
          return _this;
        }
        var _proto = ShadowFlow.prototype;
        _proto.initialize = function initialize(info) {
          _RenderFlow.prototype.initialize.call(this, info);
          if (this._stages.length === 0) {
            var shadowMapStage = new ShadowStage();
            shadowMapStage.initialize(ShadowStage.initInfo);
            this._stages.push(shadowMapStage);
          }
          return true;
        };
        _proto.activate = function activate(pipeline) {
          _RenderFlow.prototype.activate.call(this, pipeline);
          var isRGBE = supportsR32FloatTexture(pipeline.device) ? 0 : 1;
          pipeline.macros.CC_SHADOWMAP_FORMAT = isRGBE;
          var isLinear = pipeline.device.gfxAPI === API.WEBGL ? 1 : 0;
          pipeline.macros.CC_SHADOWMAP_USE_LINEAR_DEPTH = isLinear;
          pipeline.pipelineSceneData.csmSupported = pipeline.device.capabilities.maxFragmentUniformVectors >= (UBOGlobal.COUNT + UBOCamera.COUNT + UBOShadow.COUNT + UBOCSM.COUNT) / 4;
          pipeline.macros.CC_SUPPORT_CASCADED_SHADOW_MAP = pipeline.pipelineSceneData.csmSupported;
          pipeline.macros.CC_SHADOW_TYPE = 0;
          pipeline.macros.CC_DIR_SHADOW_PCF_TYPE = PCFType.HARD;
          pipeline.macros.CC_DIR_LIGHT_SHADOW_TYPE = 0;
          pipeline.macros.CC_CASCADED_LAYERS_TRANSITION = 0;
          pipeline.onGlobalPipelineStateChanged();
        };
        _proto.render = function render(camera) {
          var pipeline = this._pipeline;
          var shadowInfo = pipeline.pipelineSceneData.shadows;
          var csmLayers = pipeline.pipelineSceneData.csmLayers;
          var shadowFrameBufferMap = pipeline.pipelineSceneData.shadowFrameBufferMap;
          var castShadowObjects = csmLayers.castShadowObjects;
          var validPunctualLights = this._pipeline.pipelineSceneData.validPunctualLights;
          if (!shadowInfo.enabled || shadowInfo.type !== ShadowType.ShadowMap) {
            return;
          }
          var n = 0;
          var m = 0;
          for (; n < shadowInfo.maxReceived && m < validPunctualLights.length;) {
            var light = validPunctualLights[m];
            if (light.type === LightType.SPOT) {
              var spotLight = light;
              if (spotLight.shadowEnabled) {
                _validLights.push(light);
                n++;
              }
            }
            m++;
          }
          if (castShadowObjects.length === 0) {
            this.clearShadowMap(_validLights, camera);
            return;
          }
          if (shadowInfo.shadowMapDirty) {
            this.resizeShadowMap();
          }
          var _ref = camera.scene,
            mainLight = _ref.mainLight;
          if (mainLight && mainLight.shadowEnabled) {
            var globalDS = pipeline.descriptorSet;
            if (!shadowFrameBufferMap.has(mainLight)) {
              this._initShadowFrameBuffer(pipeline, mainLight, camera.window.swapchain);
            }
            var shadowFrameBuffer = shadowFrameBufferMap.get(mainLight);
            if (mainLight.shadowFixedArea) {
              this._renderStage(camera, mainLight, shadowFrameBuffer, globalDS);
            } else {
              var csmLevel = pipeline.pipelineSceneData.csmSupported ? mainLight.csmLevel : 1;
              for (var i = 0; i < csmLevel; i++) {
                this._renderStage(camera, mainLight, shadowFrameBuffer, globalDS, i);
              }
            }
          }
          for (var l = 0; l < _validLights.length; l++) {
            var _light = _validLights[l];
            var ds = pipeline.globalDSManager.getOrCreateDescriptorSet(_light);
            if (!shadowFrameBufferMap.has(_light)) {
              this._initShadowFrameBuffer(pipeline, _light, camera.window.swapchain);
            }
            var _shadowFrameBuffer = shadowFrameBufferMap.get(_light);
            this._renderStage(camera, _light, _shadowFrameBuffer, ds);
          }
          _validLights.length = 0;
        };
        _proto.destroy = function destroy() {
          _RenderFlow.prototype.destroy.call(this);
          if (this._pipeline) {
            var shadowFrameBufferMap = this._pipeline.pipelineSceneData.shadowFrameBufferMap;
            var shadowFrameBuffers = Array.from(shadowFrameBufferMap.values());
            for (var i = 0; i < shadowFrameBuffers.length; i++) {
              var frameBuffer = shadowFrameBuffers[i];
              if (!frameBuffer) {
                continue;
              }
              var renderTargets = frameBuffer.colorTextures;
              for (var j = 0; j < renderTargets.length; j++) {
                var renderTarget = renderTargets[j];
                if (renderTarget) {
                  renderTarget.destroy();
                }
              }
              renderTargets.length = 0;
              var depth = frameBuffer.depthStencilTexture;
              if (depth) {
                depth.destroy();
              }
              frameBuffer.destroy();
            }
            shadowFrameBufferMap.clear();
          }
          if (this._shadowRenderPass) {
            this._shadowRenderPass.destroy();
          }
        };
        _proto._initShadowFrameBuffer = function _initShadowFrameBuffer(pipeline, light, swapchain) {
          var device = pipeline.device;
          var shadows = pipeline.pipelineSceneData.shadows;
          var shadowMapSize = shadows.size;
          var shadowFrameBufferMap = pipeline.pipelineSceneData.shadowFrameBufferMap;
          var format = supportsR32FloatTexture(device) ? Format.R32F : Format.RGBA8;
          if (!this._shadowRenderPass) {
            var colorAttachment = new ColorAttachment();
            colorAttachment.format = format;
            colorAttachment.loadOp = LoadOp.CLEAR;
            colorAttachment.storeOp = StoreOp.STORE;
            colorAttachment.sampleCount = 1;
            var depthStencilAttachment = new DepthStencilAttachment();
            depthStencilAttachment.format = Format.DEPTH_STENCIL;
            depthStencilAttachment.depthLoadOp = LoadOp.CLEAR;
            depthStencilAttachment.depthStoreOp = StoreOp.DISCARD;
            depthStencilAttachment.stencilLoadOp = LoadOp.CLEAR;
            depthStencilAttachment.stencilStoreOp = StoreOp.DISCARD;
            depthStencilAttachment.sampleCount = 1;
            var renderPassInfo = new RenderPassInfo([colorAttachment], depthStencilAttachment);
            this._shadowRenderPass = device.createRenderPass(renderPassInfo);
          }
          var shadowRenderTargets = [];
          shadowRenderTargets.push(device.createTexture(new TextureInfo(TextureType.TEX2D, TextureUsageBit.COLOR_ATTACHMENT | TextureUsageBit.SAMPLED, format, shadowMapSize.x, shadowMapSize.y)));
          var depth = device.createTexture(new TextureInfo(TextureType.TEX2D, TextureUsageBit.DEPTH_STENCIL_ATTACHMENT, Format.DEPTH_STENCIL, shadowMapSize.x, shadowMapSize.y));
          var shadowFrameBuffer = device.createFramebuffer(new FramebufferInfo(this._shadowRenderPass, shadowRenderTargets, depth));
          shadowFrameBufferMap.set(light, shadowFrameBuffer);
        };
        _proto._renderStage = function _renderStage(camera, light, shadowFrameBuffer, globalDS, level) {
          if (level === void 0) {
            level = 0;
          }
          for (var i = 0; i < this._stages.length; i++) {
            var shadowStage = this._stages[i];
            shadowStage.setUsage(globalDS, light, shadowFrameBuffer, level);
            shadowStage.render(camera);
          }
        };
        _proto.clearShadowMap = function clearShadowMap(validLights, camera) {
          var pipeline = this._pipeline;
          var scene = pipeline.pipelineSceneData;
          var _ref2 = camera.scene,
            mainLight = _ref2.mainLight;
          if (mainLight) {
            var globalDS = this._pipeline.descriptorSet;
            if (!scene.shadowFrameBufferMap.has(mainLight)) {
              this._initShadowFrameBuffer(this._pipeline, mainLight, camera.window.swapchain);
            }
            var shadowFrameBuffer = scene.shadowFrameBufferMap.get(mainLight);
            for (var i = 0; i < this._stages.length; i++) {
              var shadowStage = this._stages[i];
              shadowStage.setUsage(globalDS, mainLight, shadowFrameBuffer);
              shadowStage.clearFramebuffer(camera);
            }
          }
          for (var l = 0; l < validLights.length; l++) {
            var light = validLights[l];
            var ds = pipeline.globalDSManager.getOrCreateDescriptorSet(light);
            if (!scene.shadowFrameBufferMap.has(light)) {
              this._initShadowFrameBuffer(this._pipeline, light, camera.window.swapchain);
            }
            var _shadowFrameBuffer2 = scene.shadowFrameBufferMap.get(light);
            for (var _i = 0; _i < this._stages.length; _i++) {
              var _shadowStage = this._stages[_i];
              _shadowStage.setUsage(ds, light, _shadowFrameBuffer2);
              _shadowStage.clearFramebuffer(camera);
            }
          }
        };
        _proto.resizeShadowMap = function resizeShadowMap() {
          var shadows = this._pipeline.pipelineSceneData.shadows;
          var shadowMapSize = shadows.size;
          var pipeline = this._pipeline;
          var device = pipeline.device;
          var shadowFrameBufferMap = pipeline.pipelineSceneData.shadowFrameBufferMap;
          var format = supportsR32FloatTexture(device) ? Format.R32F : Format.RGBA8;
          for (var _iterator = _createForOfIteratorHelperLoose(shadowFrameBufferMap.keys()), _step; !(_step = _iterator()).done;) {
            var key = _step.value;
            var frameBuffer = shadowFrameBufferMap.get(key);
            if (!frameBuffer) {
              continue;
            }
            var renderTargets = [];
            renderTargets.push(pipeline.device.createTexture(new TextureInfo(TextureType.TEX2D, TextureUsageBit.COLOR_ATTACHMENT | TextureUsageBit.SAMPLED, format, shadowMapSize.x, shadowMapSize.y)));
            var depth = frameBuffer.depthStencilTexture;
            if (depth) {
              depth.resize(shadowMapSize.x, shadowMapSize.y);
            }
            var shadowRenderPass = frameBuffer.renderPass;
            frameBuffer.destroy();
            var newFrameBuffer = device.createFramebuffer(new FramebufferInfo(shadowRenderPass, renderTargets, depth));
            shadowFrameBufferMap.set(key, newFrameBuffer);
          }
          shadows.shadowMapDirty = false;
        };
        return ShadowFlow;
      }(RenderFlow), _class2$2k.initInfo = {
        name: PIPELINE_FLOW_SHADOW,
        priority: ForwardFlowPriority.SHADOW,
        tag: RenderFlowTag.SCENE,
        stages: []
      }, _class2$2k)) || _class$2z));

      var CC_USE_RGBE_OUTPUT = 'CC_USE_RGBE_OUTPUT';
      var _phaseID$1 = getPhaseID('default');
      var _phaseReflectMapID = getPhaseID('reflect-map');
      function getPassIndex(subModel) {
        var passes = subModel.passes;
        var r = legacyCC.rendering;
        if (isEnableEffect()) _phaseID$1 = r.getPhaseID(r.getPassID('default'), 'default');
        for (var k = 0; k < passes.length; k++) {
          if ((!r || !r.enableEffectImport) && passes[k].phase === _phaseID$1 || isEnableEffect() && passes[k].phaseID === _phaseID$1) {
            return k;
          }
        }
        return -1;
      }
      function getReflectMapPassIndex(subModel) {
        var passes = subModel.passes;
        var r = legacyCC.rendering;
        if (isEnableEffect()) _phaseReflectMapID = r.getPhaseID(r.getPassID('default'), 'reflect-map');
        for (var k = 0; k < passes.length; k++) {
          if ((!r || !r.enableEffectImport) && passes[k].phase === _phaseReflectMapID || isEnableEffect() && passes[k].phaseID === _phaseReflectMapID) {
            return k;
          }
        }
        return -1;
      }
      var RenderReflectionProbeQueue = function () {
        function RenderReflectionProbeQueue(pipeline) {
          this._pipeline = void 0;
          this._subModelsArray = [];
          this._passArray = [];
          this._shaderArray = [];
          this._rgbeSubModelsArray = [];
          this._instancedQueue = void 0;
          this._patches = [];
          this._pipeline = pipeline;
          this._instancedQueue = new RenderInstancedQueue();
        }
        var _proto = RenderReflectionProbeQueue.prototype;
        _proto.gatherRenderObjects = function gatherRenderObjects(probe, camera, cmdBuff) {
          this.clear();
          var scene = camera.scene;
          var sceneData = this._pipeline.pipelineSceneData;
          var skybox = sceneData.skybox;
          if (skybox.enabled && skybox.model && probe.camera.clearFlag & SKYBOX_FLAG) {
            this.add(skybox.model);
          }
          var models = scene.models;
          var visibility = probe.visibility;
          for (var i = 0; i < models.length; i++) {
            var model = models[i];
            if (!model.node || scene.isCulledByLod(camera, model)) {
              continue;
            }
            if ((visibility & model.node.layer) !== model.node.layer && !(visibility & model.visFlags)) {
              continue;
            }
            if (model.enabled && model.worldBounds && model.bakeToReflectionProbe) {
              if (probe.probeType === ProbeType.CUBE) {
                if (intersect.aabbWithAABB(model.worldBounds, probe.boundingBox)) {
                  this.add(model);
                }
              } else if (intersect.aabbFrustum(model.worldBounds, probe.camera.frustum)) {
                this.add(model);
              }
            }
          }
          this._instancedQueue.uploadBuffers(cmdBuff);
        };
        _proto.clear = function clear() {
          this._subModelsArray.length = 0;
          this._shaderArray.length = 0;
          this._passArray.length = 0;
          this._instancedQueue.clear();
          this._rgbeSubModelsArray.length = 0;
        };
        _proto.add = function add(model) {
          var subModels = model.subModels;
          for (var j = 0; j < subModels.length; j++) {
            var subModel = subModels[j];
            var isTransparent = subModel.passes[0].blendState.targets[0].blend;
            if (isTransparent) {
              continue;
            }
            var passIdx = getReflectMapPassIndex(subModel);
            var bUseReflectPass = true;
            if (passIdx < 0) {
              passIdx = getPassIndex(subModel);
              bUseReflectPass = false;
            }
            if (passIdx < 0) {
              continue;
            }
            var pass = subModel.passes[passIdx];
            var batchingScheme = pass.batchingScheme;
            if (!bUseReflectPass) {
              this._patches = [];
              this._patches = this._patches.concat(subModel.patches);
              var useRGBEPatchs = [{
                name: CC_USE_RGBE_OUTPUT,
                value: true
              }];
              this._patches = this._patches.concat(useRGBEPatchs);
              subModel.onMacroPatchesStateChanged(this._patches);
              this._rgbeSubModelsArray.push(subModel);
            }
            if (batchingScheme === BatchingSchemes.INSTANCING) {
              var buffer = pass.getInstancedBuffer();
              buffer.merge(subModel, passIdx);
              this._instancedQueue.queue.add(buffer);
            } else {
              var shader = subModel.shaders[passIdx];
              this._subModelsArray.push(subModel);
              if (shader) this._shaderArray.push(shader);
              this._passArray.push(pass);
            }
          }
        };
        _proto.recordCommandBuffer = function recordCommandBuffer(device, renderPass, cmdBuff) {
          this._instancedQueue.recordCommandBuffer(device, renderPass, cmdBuff);
          for (var i = 0; i < this._subModelsArray.length; ++i) {
            var subModel = this._subModelsArray[i];
            var shader = this._shaderArray[i];
            var pass = this._passArray[i];
            var ia = subModel.inputAssembler;
            var pso = PipelineStateManager.getOrCreatePipelineState(device, pass, shader, renderPass, ia);
            var descriptorSet = pass.descriptorSet;
            cmdBuff.bindPipelineState(pso);
            cmdBuff.bindDescriptorSet(SetIndex.MATERIAL, descriptorSet);
            cmdBuff.bindDescriptorSet(SetIndex.LOCAL, subModel.descriptorSet);
            cmdBuff.bindInputAssembler(ia);
            cmdBuff.draw(ia);
          }
          this.resetRGBEMacro();
          this._instancedQueue.clear();
        };
        _proto.resetRGBEMacro = function resetRGBEMacro() {
          for (var i = 0; i < this._rgbeSubModelsArray.length; i++) {
            this._patches = [];
            var subModel = this._rgbeSubModelsArray[i];
            this._patches = this._patches.concat(subModel.patches);
            if (!this._patches) continue;
            for (var j = 0; j < this._patches.length; j++) {
              var patch = this._patches[j];
              if (patch.name === CC_USE_RGBE_OUTPUT) {
                this._patches.splice(j, 1);
                break;
              }
            }
            subModel.onMacroPatchesStateChanged(this._patches);
          }
        };
        return RenderReflectionProbeQueue;
      }();

      var _dec$2B, _class$2y, _class2$2j;
      var colors$4 = [new Color(1, 1, 1, 1)];
      var ReflectionProbeStage = exports('dq', (_dec$2B = ccclass$n('ReflectionProbeStage'), _dec$2B(_class$2y = (_class2$2j = function (_RenderStage) {
        _inheritsLoose(ReflectionProbeStage, _RenderStage);
        function ReflectionProbeStage() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _RenderStage.call.apply(_RenderStage, [this].concat(args)) || this;
          _this._frameBuffer = null;
          _this._renderArea = new Rect();
          _this._probe = null;
          _this._probeRenderQueue = void 0;
          _this._rgbeColor = new Vec3();
          return _this;
        }
        var _proto = ReflectionProbeStage.prototype;
        _proto.setUsageInfo = function setUsageInfo(probe, frameBuffer) {
          this._probe = probe;
          this._frameBuffer = frameBuffer;
        };
        _proto.destroy = function destroy() {
          var _this$_probeRenderQue;
          this._frameBuffer = null;
          (_this$_probeRenderQue = this._probeRenderQueue) === null || _this$_probeRenderQue === void 0 ? void 0 : _this$_probeRenderQue.clear();
        };
        _proto.clearFramebuffer = function clearFramebuffer(camera) {
          if (!this._frameBuffer) {
            return;
          }
          colors$4[0].w = camera.clearColor.w;
          var pipeline = this._pipeline;
          var pipelineSceneData = pipeline.pipelineSceneData;
          var shadingScale = pipelineSceneData.shadingScale;
          var vp = camera.viewport;
          var size = this._probe.resolution;
          this._renderArea.x = vp.x * size;
          this._renderArea.y = vp.y * size;
          this._renderArea.width = vp.width * size * shadingScale;
          this._renderArea.height = vp.height * size * shadingScale;
          var cmdBuff = pipeline.commandBuffers[0];
          var renderPass = this._frameBuffer.renderPass;
          cmdBuff.beginRenderPass(renderPass, this._frameBuffer, this._renderArea, colors$4, camera.clearDepth, camera.clearStencil);
          cmdBuff.endRenderPass();
        };
        _proto.render = function render(camera) {
          var pipeline = this._pipeline;
          var cmdBuff = pipeline.commandBuffers[0];
          this._probeRenderQueue.gatherRenderObjects(this._probe, camera, cmdBuff);
          pipeline.pipelineUBO.updateCameraUBO(this._probe.camera);
          this._renderArea.x = 0;
          this._renderArea.y = 0;
          this._renderArea.width = this._probe.renderArea().x;
          this._renderArea.height = this._probe.renderArea().y;
          var renderPass = this._frameBuffer.renderPass;
          if (this._probe.camera.clearFlag & ClearFlagBit.COLOR) {
            this._rgbeColor.x = this._probe.camera.clearColor.x;
            this._rgbeColor.y = this._probe.camera.clearColor.y;
            this._rgbeColor.z = this._probe.camera.clearColor.z;
            var rgbe = packRGBE(this._rgbeColor);
            colors$4[0].x = rgbe.x;
            colors$4[0].y = rgbe.y;
            colors$4[0].z = rgbe.z;
            colors$4[0].w = rgbe.w;
          }
          var device = pipeline.device;
          cmdBuff.beginRenderPass(renderPass, this._frameBuffer, this._renderArea, colors$4, this._probe.camera.clearDepth, this._probe.camera.clearStencil);
          cmdBuff.bindDescriptorSet(SetIndex.GLOBAL, pipeline.descriptorSet);
          this._probeRenderQueue.recordCommandBuffer(device, renderPass, cmdBuff);
          cmdBuff.endRenderPass();
          pipeline.pipelineUBO.updateCameraUBO(camera);
        };
        _proto.activate = function activate(pipeline, flow) {
          _RenderStage.prototype.activate.call(this, pipeline, flow);
          this._probeRenderQueue = new RenderReflectionProbeQueue(pipeline);
        };
        return ReflectionProbeStage;
      }(RenderStage), _class2$2j.initInfo = {
        name: 'ReflectionProbeStage',
        priority: ForwardStagePriority.FORWARD,
        tag: 0
      }, _class2$2j)) || _class$2y));

      var _dec$2A, _class$2x, _class2$2i;
      var ReflectionProbeFlow = exports('dp', (_dec$2A = ccclass$n('ReflectionProbeFlow'), _dec$2A(_class$2x = (_class2$2i = function (_RenderFlow) {
        _inheritsLoose(ReflectionProbeFlow, _RenderFlow);
        function ReflectionProbeFlow() {
          return _RenderFlow.apply(this, arguments) || this;
        }
        var _proto = ReflectionProbeFlow.prototype;
        _proto.initialize = function initialize(info) {
          _RenderFlow.prototype.initialize.call(this, info);
          if (this._stages.length === 0) {
            var probeStage = new ReflectionProbeStage();
            probeStage.initialize(ReflectionProbeStage.initInfo);
            this._stages.push(probeStage);
          }
          return true;
        };
        _proto.activate = function activate(pipeline) {
          _RenderFlow.prototype.activate.call(this, pipeline);
        };
        _proto.render = function render(camera) {
          if (!legacyCC.internal.reflectionProbeManager) {
            return;
          }
          var probes = legacyCC.internal.reflectionProbeManager.getProbes();
          for (var i = 0; i < probes.length; i++) {
            if (probes[i].needRender) {
              if (probes[i].probeType === ProbeType.PLANAR) {
                this._renderStage(camera, probes[i]);
              }
            }
          }
        };
        _proto.destroy = function destroy() {
          _RenderFlow.prototype.destroy.call(this);
        };
        _proto._renderStage = function _renderStage(camera, probe) {
          for (var i = 0; i < this._stages.length; i++) {
            var probeStage = this._stages[i];
            if (probe.probeType === ProbeType.PLANAR) {
              legacyCC.internal.reflectionProbeManager.updatePlanarMap(probe, null);
              probeStage.setUsageInfo(probe, probe.realtimePlanarTexture.window.framebuffer);
              probeStage.render(camera);
              legacyCC.internal.reflectionProbeManager.updatePlanarMap(probe, probe.realtimePlanarTexture.getGFXTexture());
            } else {
              for (var faceIdx = 0; faceIdx < 6; faceIdx++) {
                var renderTexture = probe.bakedCubeTextures[faceIdx];
                if (!renderTexture) return;
                probe.updateCameraDir(faceIdx);
                probeStage.setUsageInfo(probe, renderTexture.window.framebuffer);
                probeStage.render(camera);
              }
              probe.needRender = false;
            }
          }
        };
        return ReflectionProbeFlow;
      }(RenderFlow), _class2$2i.initInfo = {
        name: 'PIPELINE_FLOW_RELECTION_PROBE',
        priority: 0,
        tag: RenderFlowTag.SCENE,
        stages: []
      }, _class2$2i)) || _class$2x));

      var _dec$2z, _dec2$1X, _class$2w, _class2$2h, _initializer$25;
      var PIPELINE_TYPE$1 = 0;
      function createDefaultPipeline() {
        var rppl = new ForwardPipeline();
        rppl.initialize({
          flows: []
        });
        return rppl;
      }
      var ForwardPipeline = exports('d7', (_dec$2z = ccclass$n('ForwardPipeline'), _dec2$1X = type$7([RenderTextureConfig]), _dec$2z(_class$2w = (_class2$2h = function (_RenderPipeline) {
        _inheritsLoose(ForwardPipeline, _RenderPipeline);
        function ForwardPipeline() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _RenderPipeline.call.apply(_RenderPipeline, [this].concat(args)) || this;
          _this.renderTextures = _initializer$25 && _initializer$25();
          _this._postRenderPass = null;
          return _this;
        }
        var _proto = ForwardPipeline.prototype;
        _proto.initialize = function initialize(info) {
          _RenderPipeline.prototype.initialize.call(this, info);
          if (this._flows.length === 0) {
            var shadowFlow = new ShadowFlow();
            shadowFlow.initialize(ShadowFlow.initInfo);
            this._flows.push(shadowFlow);
            var reflectionFlow = new ReflectionProbeFlow();
            reflectionFlow.initialize(ReflectionProbeFlow.initInfo);
            this._flows.push(reflectionFlow);
            var forwardFlow = new ForwardFlow();
            forwardFlow.initialize(ForwardFlow.initInfo);
            this._flows.push(forwardFlow);
          }
          return true;
        };
        _proto.activate = function activate(swapchain) {
          this._macros = {
            CC_PIPELINE_TYPE: PIPELINE_TYPE$1
          };
          this._pipelineSceneData = new PipelineSceneData();
          if (!_RenderPipeline.prototype.activate.call(this, swapchain)) {
            return false;
          }
          if (!this._activeRenderer(swapchain)) {
            errorID(2402);
            return false;
          }
          return true;
        };
        _proto._ensureEnoughSize = function _ensureEnoughSize(cameras) {
          var newWidth = this._width;
          var newHeight = this._height;
          for (var i = 0; i < cameras.length; ++i) {
            var window = cameras[i].window;
            newWidth = Math.max(window.width, newWidth);
            newHeight = Math.max(window.height, newHeight);
          }
          if (newWidth !== this._width || newHeight !== this._height) {
            this._width = newWidth;
            this._height = newHeight;
          }
        };
        _proto.destroy = function destroy() {
          this._destroyUBOs();
          this._destroyQuadInputAssembler();
          var rpIter = this._renderPasses.values();
          var rpRes = rpIter.next();
          while (!rpRes.done) {
            rpRes.value.destroy();
            rpRes = rpIter.next();
          }
          this._commandBuffers.length = 0;
          return _RenderPipeline.prototype.destroy.call(this);
        };
        _proto._activeRenderer = function _activeRenderer(swapchain) {
          var device = this.device;
          this._commandBuffers.push(device.commandBuffer);
          var shadowMapSampler = this.globalDSManager.pointSampler;
          this._descriptorSet.bindSampler(UNIFORM_SHADOWMAP_BINDING, shadowMapSampler);
          this._descriptorSet.bindTexture(UNIFORM_SHADOWMAP_BINDING, builtinResMgr.get('default-texture').getGFXTexture());
          this._descriptorSet.bindSampler(UNIFORM_SPOT_SHADOW_MAP_TEXTURE_BINDING, shadowMapSampler);
          this._descriptorSet.bindTexture(UNIFORM_SPOT_SHADOW_MAP_TEXTURE_BINDING, builtinResMgr.get('default-texture').getGFXTexture());
          this._descriptorSet.update();
          return true;
        };
        _proto._destroyUBOs = function _destroyUBOs() {
          if (this._descriptorSet) {
            this._descriptorSet.getBuffer(UBOGlobal.BINDING).destroy();
            this._descriptorSet.getBuffer(UBOShadow.BINDING).destroy();
            this._descriptorSet.getBuffer(UBOCamera.BINDING).destroy();
            this._descriptorSet.getTexture(UNIFORM_SHADOWMAP_BINDING).destroy();
            this._descriptorSet.getTexture(UNIFORM_SPOT_SHADOW_MAP_TEXTURE_BINDING).destroy();
          }
        };
        _createClass(ForwardPipeline, [{
          key: "postRenderPass",
          get: function get() {
            return this._postRenderPass;
          }
        }]);
        return ForwardPipeline;
      }(RenderPipeline), (_initializer$25 = applyDecoratedInitializer(_class2$2h.prototype, "renderTextures", [_dec2$1X, serializable$j], function () {
        return [];
      })), _class2$2h)) || _class$2w));

      var _dec$2y, _dec2$1W, _class$2v, _class2$2g, _initializer$24, _class3$H;
      var colors$3 = [new Color(0, 0, 0, 0), new Color(0, 0, 0, 0), new Color(0, 0, 0, 0)];
      var GbufferStage = exports('dd', (_dec$2y = ccclass$n('GbufferStage'), _dec2$1W = type$7([RenderQueueDesc]), _dec$2y(_class$2v = (_class2$2g = (_class3$H = function (_RenderStage) {
        _inheritsLoose(GbufferStage, _RenderStage);
        function GbufferStage() {
          var _this;
          _this = _RenderStage.call(this) || this;
          _this.renderQueues = _initializer$24 && _initializer$24();
          _this._renderQueues = [];
          _this._renderArea = new Rect();
          _this._instancedQueue = void 0;
          _this._phaseID = getPhaseID('default');
          _this._instancedQueue = new RenderInstancedQueue();
          return _this;
        }
        var _proto = GbufferStage.prototype;
        _proto.initialize = function initialize(info) {
          _RenderStage.prototype.initialize.call(this, info);
          if (info.renderQueues) {
            this.renderQueues = info.renderQueues;
          }
          return true;
        };
        _proto.activate = function activate(pipeline, flow) {
          _RenderStage.prototype.activate.call(this, pipeline, flow);
          for (var i = 0; i < this.renderQueues.length; i++) {
            this._renderQueues[i] = convertRenderQueue(this.renderQueues[i]);
          }
        };
        _proto.destroy = function destroy() {};
        _proto.render = function render(camera) {
          this._instancedQueue.clear();
          var pipeline = this._pipeline;
          var device = pipeline.device;
          this._renderQueues.forEach(renderQueueClearFunc);
          pipeline.generateRenderArea(camera, this._renderArea);
          pipeline.updateQuadVertexData(this._renderArea, camera.window);
          var renderObjects = pipeline.pipelineSceneData.renderObjects;
          var m = 0;
          var p = 0;
          var k = 0;
          for (var i = 0; i < renderObjects.length; ++i) {
            var ro = renderObjects[i];
            var subModels = ro.model.subModels;
            for (m = 0; m < subModels.length; ++m) {
              var subModel = subModels[m];
              var passes = subModel.passes;
              for (p = 0; p < passes.length; ++p) {
                var pass = passes[p];
                if (pass.phase !== this._phaseID) continue;
                var batchingScheme = pass.batchingScheme;
                if (batchingScheme === BatchingSchemes.INSTANCING) {
                  var instancedBuffer = pass.getInstancedBuffer();
                  instancedBuffer.merge(subModel, p);
                  this._instancedQueue.queue.add(instancedBuffer);
                } else {
                  for (k = 0; k < this._renderQueues.length; k++) {
                    this._renderQueues[k].insertRenderPass(ro, m, p);
                  }
                }
              }
            }
          }
          this._renderQueues.forEach(renderQueueSortFunc);
          var cmdBuff = pipeline.commandBuffers[0];
          this._instancedQueue.uploadBuffers(cmdBuff);
          if (camera.clearFlag & ClearFlagBit.COLOR) {
            if (pipeline.pipelineSceneData.isHDR) {
              SRGBToLinear(colors$3[0], camera.clearColor);
            } else {
              colors$3[0].x = camera.clearColor.x;
              colors$3[0].y = camera.clearColor.y;
              colors$3[0].z = camera.clearColor.z;
            }
          }
          colors$3[0].w = camera.clearColor.w;
          var deferredData = pipeline.getPipelineRenderData();
          var framebuffer = deferredData.gbufferFrameBuffer;
          var renderPass = framebuffer.renderPass;
          cmdBuff.beginRenderPass(renderPass, framebuffer, this._renderArea, colors$3, camera.clearDepth, camera.clearStencil);
          cmdBuff.setScissor(pipeline.generateScissor(camera));
          cmdBuff.setViewport(pipeline.generateViewport(camera));
          cmdBuff.bindDescriptorSet(SetIndex.GLOBAL, pipeline.descriptorSet);
          for (var _i = 0; _i < this.renderQueues.length; _i++) {
            this._renderQueues[_i].recordCommandBuffer(device, renderPass, cmdBuff);
          }
          this._instancedQueue.recordCommandBuffer(device, renderPass, cmdBuff);
          cmdBuff.endRenderPass();
        };
        return GbufferStage;
      }(RenderStage), _class3$H.initInfo = {
        name: 'GbufferStage',
        priority: DeferredStagePriority.GBUFFER,
        tag: 0,
        renderQueues: [{
          isTransparent: false,
          sortMode: RenderQueueSortMode.FRONT_TO_BACK,
          stages: ['default']
        }, {
          isTransparent: true,
          sortMode: RenderQueueSortMode.BACK_TO_FRONT,
          stages: ['default']
        }]
      }, _class3$H), (_initializer$24 = applyDecoratedInitializer(_class2$2g.prototype, "renderQueues", [_dec2$1W, serializable$j], function () {
        return [];
      })), _class2$2g)) || _class$2v));

      var _dec$2x, _dec2$1V, _dec3$1l, _class$2u, _class2$2f, _initializer$23, _initializer2$1D, _class3$G;
      var _v3$1 = new Vec3();
      var _rangedDirLightBoundingBox = new AABB(0.0, 0.0, 0.0, 0.5, 0.5, 0.5);
      var _tmpBoundingBox = new AABB();
      var colors$2 = [new Color(0, 0, 0, 1)];
      var LightingStage = exports('de', (_dec$2x = ccclass$n('LightingStage'), _dec2$1V = type$7(Material), _dec3$1l = type$7([RenderQueueDesc]), _dec$2x(_class$2u = (_class2$2f = (_class3$G = function (_RenderStage) {
        _inheritsLoose(LightingStage, _RenderStage);
        function LightingStage() {
          var _this;
          _this = _RenderStage.call(this) || this;
          _this._deferredLitsBufs = null;
          _this._maxDeferredLights = UBODeferredLight.LIGHTS_PER_PASS;
          _this._lightBufferData = void 0;
          _this._lightMeterScale = 10000.0;
          _this._descriptorSet = null;
          _this._descriptorSetLayout = void 0;
          _this._renderArea = new Rect();
          _this._uiPhase = void 0;
          _this._deferredMaterial = _initializer$23 && _initializer$23();
          _this.renderQueues = _initializer2$1D && _initializer2$1D();
          _this._phaseID = getPhaseID('default');
          _this._renderQueues = [];
          _this._uiPhase = new UIPhase();
          return _this;
        }
        var _proto = LightingStage.prototype;
        _proto.initialize = function initialize(info) {
          _RenderStage.prototype.initialize.call(this, info);
          return true;
        };
        _proto.gatherLights = function gatherLights(camera) {
          var pipeline = this._pipeline;
          var cmdBuff = pipeline.commandBuffers[0];
          var sphereLights = camera.scene.sphereLights;
          var spotLights = camera.scene.spotLights;
          var pointLights = camera.scene.pointLights;
          var rangedDirLights = camera.scene.rangedDirLights;
          var _sphere = Sphere.create(0, 0, 0, 1);
          var _vec4Array = new Float32Array(4);
          var exposure = camera.exposure;
          var idx = 0;
          var elementLen = Vec4.length;
          var fieldLen = elementLen * this._maxDeferredLights;
          for (var i = 0; i < sphereLights.length && idx < this._maxDeferredLights; i++, ++idx) {
            var light = sphereLights[i];
            Sphere.set(_sphere, light.position.x, light.position.y, light.position.z, light.range);
            if (intersect.sphereFrustum(_sphere, camera.frustum)) {
              Vec3.toArray(_vec4Array, light.position);
              _vec4Array[3] = LightType.SPHERE;
              this._lightBufferData.set(_vec4Array, idx * elementLen);
              Vec3.toArray(_vec4Array, light.color);
              if (light.useColorTemperature) {
                var finalColor = light.finalColor;
                _vec4Array[0] = finalColor.x;
                _vec4Array[1] = finalColor.y;
                _vec4Array[2] = finalColor.z;
              }
              if (pipeline.pipelineSceneData.isHDR) {
                _vec4Array[3] = light.luminance * exposure * this._lightMeterScale;
              } else {
                _vec4Array[3] = light.luminance;
              }
              this._lightBufferData.set(_vec4Array, idx * elementLen + fieldLen * 1);
              _vec4Array[0] = light.size;
              _vec4Array[1] = light.range;
              _vec4Array[2] = 0.0;
              this._lightBufferData.set(_vec4Array, idx * elementLen + fieldLen * 2);
            }
          }
          for (var _i = 0; _i < spotLights.length && idx < this._maxDeferredLights; _i++, ++idx) {
            var _light = spotLights[_i];
            Sphere.set(_sphere, _light.position.x, _light.position.y, _light.position.z, _light.range);
            if (intersect.sphereFrustum(_sphere, camera.frustum)) {
              Vec3.toArray(_vec4Array, _light.position);
              _vec4Array[3] = LightType.SPOT;
              this._lightBufferData.set(_vec4Array, idx * elementLen + fieldLen * 0);
              Vec3.toArray(_vec4Array, _light.color);
              if (_light.useColorTemperature) {
                var _finalColor = _light.finalColor;
                _vec4Array[0] = _finalColor.x;
                _vec4Array[1] = _finalColor.y;
                _vec4Array[2] = _finalColor.z;
              }
              if (pipeline.pipelineSceneData.isHDR) {
                _vec4Array[3] = _light.luminance * exposure * this._lightMeterScale;
              } else {
                _vec4Array[3] = _light.luminance;
              }
              this._lightBufferData.set(_vec4Array, idx * elementLen + fieldLen * 1);
              _vec4Array[0] = _light.size;
              _vec4Array[1] = _light.range;
              _vec4Array[2] = _light.spotAngle;
              this._lightBufferData.set(_vec4Array, idx * elementLen + fieldLen * 2);
              Vec3.toArray(_vec4Array, _light.direction);
              this._lightBufferData.set(_vec4Array, idx * elementLen + fieldLen * 3);
            }
          }
          for (var _i2 = 0; _i2 < pointLights.length && idx < this._maxDeferredLights; _i2++, ++idx) {
            var _light2 = pointLights[_i2];
            Sphere.set(_sphere, _light2.position.x, _light2.position.y, _light2.position.z, _light2.range);
            if (intersect.sphereFrustum(_sphere, camera.frustum)) {
              Vec3.toArray(_vec4Array, _light2.position);
              _vec4Array[3] = LightType.POINT;
              this._lightBufferData.set(_vec4Array, idx * elementLen);
              Vec3.toArray(_vec4Array, _light2.color);
              if (_light2.useColorTemperature) {
                var _finalColor2 = _light2.finalColor;
                _vec4Array[0] = _finalColor2.x;
                _vec4Array[1] = _finalColor2.y;
                _vec4Array[2] = _finalColor2.z;
              }
              if (pipeline.pipelineSceneData.isHDR) {
                _vec4Array[3] = _light2.luminance * exposure * this._lightMeterScale;
              } else {
                _vec4Array[3] = _light2.luminance;
              }
              this._lightBufferData.set(_vec4Array, idx * elementLen + fieldLen * 1);
              _vec4Array[0] = 0.0;
              _vec4Array[1] = _light2.range;
              _vec4Array[2] = 0.0;
              this._lightBufferData.set(_vec4Array, idx * elementLen + fieldLen * 2);
            }
          }
          for (var _i3 = 0; _i3 < rangedDirLights.length && idx < this._maxDeferredLights; _i3++, ++idx) {
            var _light3 = rangedDirLights[_i3];
            AABB.transform(_tmpBoundingBox, _rangedDirLightBoundingBox, _light3.node.getWorldMatrix());
            if (intersect.aabbFrustum(_tmpBoundingBox, camera.frustum)) {
              Vec3.toArray(_vec4Array, _light3.position);
              _vec4Array[3] = LightType.RANGED_DIRECTIONAL;
              this._lightBufferData.set(_vec4Array, idx * elementLen);
              Vec3.toArray(_vec4Array, _light3.color);
              if (_light3.useColorTemperature) {
                var _finalColor3 = _light3.finalColor;
                _vec4Array[0] = _finalColor3.x;
                _vec4Array[1] = _finalColor3.y;
                _vec4Array[2] = _finalColor3.z;
              }
              if (pipeline.pipelineSceneData.isHDR) {
                _vec4Array[3] = _light3.illuminance * exposure;
              } else {
                _vec4Array[3] = _light3.illuminance;
              }
              this._lightBufferData.set(_vec4Array, idx * elementLen + fieldLen * 1);
              Vec3.toArray(_vec4Array, _light3.right);
              _vec4Array[3] = 0;
              this._lightBufferData.set(_vec4Array, idx * elementLen + fieldLen * 2);
              Vec3.toArray(_vec4Array, _light3.direction);
              _vec4Array[3] = 0;
              this._lightBufferData.set(_vec4Array, idx * elementLen + fieldLen * 3);
              var scale = _light3.scale;
              _v3$1.set(scale.x * 0.5, scale.y * 0.5, scale.z * 0.5);
              Vec3.toArray(_vec4Array, _v3$1);
              _vec4Array[3] = 0;
              this._lightBufferData.set(_vec4Array, idx * elementLen + fieldLen * 4);
            }
          }
          var offset = fieldLen * 3 + 3;
          this._lightBufferData.set([idx], offset);
          cmdBuff.updateBuffer(this._deferredLitsBufs, this._lightBufferData);
        };
        _proto._createStageDescriptor = function _createStageDescriptor(pass) {
          var device = this._pipeline.device;
          var totalSize = Float32Array.BYTES_PER_ELEMENT * 4 * 4 * this._maxDeferredLights;
          totalSize = Math.ceil(totalSize / device.capabilities.uboOffsetAlignment) * device.capabilities.uboOffsetAlignment;
          this._deferredLitsBufs = device.createBuffer(new BufferInfo(BufferUsageBit.UNIFORM | BufferUsageBit.TRANSFER_DST, MemoryUsageBit.HOST | MemoryUsageBit.DEVICE, totalSize, device.capabilities.uboOffsetAlignment));
          var deferredLitsBufView = device.createBuffer(new BufferViewInfo(this._deferredLitsBufs, 0, totalSize));
          this._lightBufferData = new Float32Array(totalSize / Float32Array.BYTES_PER_ELEMENT);
          this._descriptorSet = device.createDescriptorSet(new DescriptorSetInfo(pass.localSetLayout));
          this._descriptorSet.bindBuffer(UBOForwardLight.BINDING, deferredLitsBufView);
          var _localUBO = device.createBuffer(new BufferInfo(BufferUsageBit.UNIFORM | BufferUsageBit.TRANSFER_DST, MemoryUsageBit.DEVICE, UBOLocal.SIZE, UBOLocal.SIZE));
          this._descriptorSet.bindBuffer(UBOLocal.BINDING, _localUBO);
        };
        _proto.activate = function activate(pipeline, flow) {
          _RenderStage.prototype.activate.call(this, pipeline, flow);
          this._uiPhase.activate(pipeline);
          for (var i = 0; i < this.renderQueues.length; i++) {
            this._renderQueues[i] = convertRenderQueue(this.renderQueues[i]);
          }
          this._planarQueue = new PlanarShadowQueue(this._pipeline);
          if (this._deferredMaterial) {
            pipeline.pipelineSceneData.deferredLightingMaterial = this._deferredMaterial;
          }
        };
        _proto.destroy = function destroy() {
          var _this$_deferredLitsBu;
          (_this$_deferredLitsBu = this._deferredLitsBufs) === null || _this$_deferredLitsBu === void 0 ? void 0 : _this$_deferredLitsBu.destroy();
          this._deferredLitsBufs = null;
          this._descriptorSet = null;
        };
        _proto.render = function render(camera) {
          var _camera$geometryRende;
          var pipeline = this._pipeline;
          var device = pipeline.device;
          var cmdBuff = pipeline.commandBuffers[0];
          var sceneData = pipeline.pipelineSceneData;
          var renderObjects = sceneData.renderObjects;
          this._planarQueue.gatherShadowPasses(camera, cmdBuff);
          pipeline.generateRenderArea(camera, this._renderArea);
          var deferredData = pipeline.getPipelineRenderData();
          var lightingMat = sceneData.deferredLightingMaterial;
          var pass = lightingMat.passes[0];
          var shader = pass.getShaderVariant();
          for (var i = 0; i < 3; ++i) {
            pass.descriptorSet.bindTexture(i, deferredData.gbufferRenderTargets[i]);
            pass.descriptorSet.bindSampler(i, deferredData.sampler);
          }
          pass.descriptorSet.bindTexture(3, deferredData.outputDepth);
          pass.descriptorSet.bindSampler(3, deferredData.sampler);
          pass.descriptorSet.update();
          if (!this._descriptorSet) {
            this._createStageDescriptor(pass);
          }
          this.gatherLights(camera);
          if (camera.clearFlag & ClearFlagBit.COLOR) {
            colors$2[0].x = camera.clearColor.x;
            colors$2[0].y = camera.clearColor.y;
            colors$2[0].z = camera.clearColor.z;
          }
          colors$2[0].w = 0;
          var framebuffer = deferredData.outputFrameBuffer;
          var renderPass = framebuffer.renderPass;
          pipeline.pipelineUBO.updateShadowUBO(camera);
          cmdBuff.beginRenderPass(renderPass, framebuffer, this._renderArea, colors$2, camera.clearDepth, camera.clearStencil);
          cmdBuff.setScissor(pipeline.generateScissor(camera));
          cmdBuff.setViewport(pipeline.generateViewport(camera));
          cmdBuff.bindDescriptorSet(SetIndex.GLOBAL, pipeline.descriptorSet);
          var inputAssembler = pipeline.quadIAOffscreen;
          var pso = null;
          if (pass != null && shader != null && inputAssembler != null) {
            pso = PipelineStateManager.getOrCreatePipelineState(device, pass, shader, renderPass, inputAssembler);
          }
          if (pso != null) {
            this._descriptorSet.update();
            cmdBuff.bindPipelineState(pso);
            cmdBuff.bindDescriptorSet(SetIndex.MATERIAL, pass.descriptorSet);
            cmdBuff.bindDescriptorSet(SetIndex.LOCAL, this._descriptorSet);
            cmdBuff.bindInputAssembler(inputAssembler);
            cmdBuff.draw(inputAssembler);
          }
          this._renderQueues.forEach(renderQueueClearFunc);
          var m = 0;
          var p = 0;
          var k = 0;
          for (var _i4 = 0; _i4 < renderObjects.length; ++_i4) {
            var ro = renderObjects[_i4];
            var subModels = ro.model.subModels;
            for (m = 0; m < subModels.length; ++m) {
              var subModel = subModels[m];
              var passes = subModel.passes;
              for (p = 0; p < passes.length; ++p) {
                var _pass = passes[p];
                if (_pass.phase !== this._phaseID) continue;
                for (k = 0; k < this._renderQueues.length; k++) {
                  this._renderQueues[k].insertRenderPass(ro, m, p);
                }
              }
            }
          }
          if (renderObjects.length > 0) {
            this._renderQueues.forEach(renderQueueSortFunc);
            for (var _i5 = 0; _i5 < this._renderQueues.length; _i5++) {
              this._renderQueues[_i5].recordCommandBuffer(device, renderPass, cmdBuff);
            }
            this._planarQueue.recordCommandBuffer(device, renderPass, cmdBuff);
          }
          (_camera$geometryRende = camera.geometryRenderer) === null || _camera$geometryRende === void 0 ? void 0 : _camera$geometryRende.render(renderPass, cmdBuff, pipeline.pipelineSceneData);
          this._uiPhase.render(camera, renderPass);
          cmdBuff.endRenderPass();
        };
        return LightingStage;
      }(RenderStage), _class3$G.initInfo = {
        name: 'LightingStage',
        priority: DeferredStagePriority.LIGHTING,
        tag: 0
      }, _class3$G), (_initializer$23 = applyDecoratedInitializer(_class2$2f.prototype, "_deferredMaterial", [_dec2$1V, serializable$j], function () {
        return null;
      }), _initializer2$1D = applyDecoratedInitializer(_class2$2f.prototype, "renderQueues", [_dec3$1l, serializable$j], function () {
        return [];
      })), _class2$2f)) || _class$2u));

      var _dec$2w, _dec2$1U, _dec3$1k, _class$2t, _class2$2e, _initializer$22, _initializer2$1C, _class3$F;
      var colors$1 = [new Color(0, 0, 0, 1)];
      var PostProcessStage = exports('dg', (_dec$2w = ccclass$n('PostProcessStage'), _dec2$1U = type$7(Material), _dec3$1k = type$7([RenderQueueDesc]), _dec$2w(_class$2t = (_class2$2e = (_class3$F = function (_RenderStage) {
        _inheritsLoose(PostProcessStage, _RenderStage);
        function PostProcessStage() {
          var _this;
          _this = _RenderStage.call(this) || this;
          _this._postProcessMaterial = _initializer$22 && _initializer$22();
          _this.renderQueues = _initializer2$1C && _initializer2$1C();
          _this._renderArea = new Rect();
          _this._stageDesc = void 0;
          _this._localUBO = void 0;
          _this._uiPhase = new UIPhase();
          return _this;
        }
        var _proto = PostProcessStage.prototype;
        _proto.initialize = function initialize(info) {
          _RenderStage.prototype.initialize.call(this, info);
          return true;
        };
        _proto.activate = function activate(pipeline, flow) {
          _RenderStage.prototype.activate.call(this, pipeline, flow);
          if (this._postProcessMaterial) {
            pipeline.pipelineSceneData.postprocessMaterial = this._postProcessMaterial;
          }
          this._uiPhase.activate(pipeline);
        };
        _proto.destroy = function destroy() {};
        _proto.render = function render(camera) {
          var pipeline = this._pipeline;
          var device = pipeline.device;
          var sceneData = pipeline.pipelineSceneData;
          var cmdBuff = pipeline.commandBuffers[0];
          pipeline.pipelineUBO.updateCameraUBO(camera);
          var vp = camera.viewport;
          this._renderArea.x = vp.x * camera.window.width;
          this._renderArea.y = vp.y * camera.window.height;
          this._renderArea.width = vp.width * camera.window.width;
          this._renderArea.height = vp.height * camera.window.height;
          var renderData = pipeline.getPipelineRenderData();
          var framebuffer = camera.window.framebuffer;
          var renderPass = pipeline.getRenderPass(camera.clearFlag, framebuffer);
          if (camera.clearFlag & ClearFlagBit.COLOR) {
            colors$1[0].x = camera.clearColor.x;
            colors$1[0].y = camera.clearColor.y;
            colors$1[0].z = camera.clearColor.z;
          }
          colors$1[0].w = camera.clearColor.w;
          cmdBuff.beginRenderPass(renderPass, framebuffer, this._renderArea, colors$1, camera.clearDepth, camera.clearStencil);
          cmdBuff.bindDescriptorSet(SetIndex.GLOBAL, pipeline.descriptorSet);
          var builtinPostProcess = sceneData.postprocessMaterial;
          var pass = builtinPostProcess.passes[0];
          var shader = pass.getShaderVariant();
          if (pipeline.bloomEnabled) {
            pass.descriptorSet.bindTexture(0, renderData.bloom.combineTex);
          } else {
            pass.descriptorSet.bindTexture(0, renderData.outputRenderTargets[0]);
          }
          pass.descriptorSet.bindSampler(0, renderData.sampler);
          pass.descriptorSet.update();
          var inputAssembler = camera.window.swapchain ? pipeline.quadIAOnscreen : pipeline.quadIAOffscreen;
          var pso = null;
          if (pass != null && shader != null && inputAssembler != null) {
            pso = PipelineStateManager.getOrCreatePipelineState(device, pass, shader, renderPass, inputAssembler);
          }
          var renderObjects = pipeline.pipelineSceneData.renderObjects;
          if (pso != null && renderObjects.length > 0) {
            if (!this._stageDesc) {
              this._stageDesc = device.createDescriptorSet(new DescriptorSetInfo(pass.localSetLayout));
              this._localUBO = device.createBuffer(new BufferInfo(BufferUsageBit.UNIFORM | BufferUsageBit.TRANSFER_DST, MemoryUsageBit.DEVICE, UBOLocal.SIZE, UBOLocal.SIZE));
              this._stageDesc.bindBuffer(UBOLocal.BINDING, this._localUBO);
            }
            this._stageDesc.update();
            cmdBuff.bindPipelineState(pso);
            cmdBuff.bindDescriptorSet(SetIndex.MATERIAL, pass.descriptorSet);
            cmdBuff.bindDescriptorSet(SetIndex.LOCAL, this._stageDesc);
            cmdBuff.bindInputAssembler(inputAssembler);
            cmdBuff.draw(inputAssembler);
          }
          this._uiPhase.render(camera, renderPass);
          renderProfiler(device, renderPass, cmdBuff, pipeline.profiler, camera);
          cmdBuff.endRenderPass();
        };
        return PostProcessStage;
      }(RenderStage), _class3$F.initInfo = {
        name: 'PostProcessStage',
        priority: CommonStagePriority.POST_PROCESS,
        tag: 0
      }, _class3$F), (_initializer$22 = applyDecoratedInitializer(_class2$2e.prototype, "_postProcessMaterial", [_dec2$1U, serializable$j], function () {
        return null;
      }), _initializer2$1C = applyDecoratedInitializer(_class2$2e.prototype, "renderQueues", [_dec3$1k, serializable$j], function () {
        return [];
      })), _class2$2e)) || _class$2t));

      var AntiAliasing;
      (function (AntiAliasing) {
        AntiAliasing[AntiAliasing["NONE"] = 0] = "NONE";
        AntiAliasing[AntiAliasing["FXAA"] = 1] = "FXAA";
      })(AntiAliasing || (AntiAliasing = {}));
      var BLOOM_PREFILTERPASS_INDEX = 0;
      var BLOOM_DOWNSAMPLEPASS_INDEX = 1;
      var BLOOM_UPSAMPLEPASS_INDEX = BLOOM_DOWNSAMPLEPASS_INDEX + MAX_BLOOM_FILTER_PASS_NUM;
      var BLOOM_COMBINEPASS_INDEX = BLOOM_UPSAMPLEPASS_INDEX + MAX_BLOOM_FILTER_PASS_NUM;
      var DeferredPipelineSceneData = function (_PipelineSceneData) {
        _inheritsLoose(DeferredPipelineSceneData, _PipelineSceneData);
        function DeferredPipelineSceneData() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _PipelineSceneData.call.apply(_PipelineSceneData, [this].concat(args)) || this;
          _this._antiAliasing = AntiAliasing.NONE;
          return _this;
        }
        var _proto = DeferredPipelineSceneData.prototype;
        _proto.updatePipelineSceneData = function updatePipelineSceneData() {
          this.updatePipelinePassInfo();
        };
        _proto.updateBloomPass = function updateBloomPass() {
          if (!this._bloomMaterial) return;
          var prefilterPass = this._bloomMaterial.passes[BLOOM_PREFILTERPASS_INDEX];
          prefilterPass.beginChangeStatesSilently();
          prefilterPass.tryCompile();
          prefilterPass.endChangeStatesSilently();
          for (var i = 0; i < MAX_BLOOM_FILTER_PASS_NUM; ++i) {
            var downsamplePass = this._bloomMaterial.passes[BLOOM_DOWNSAMPLEPASS_INDEX + i];
            downsamplePass.beginChangeStatesSilently();
            downsamplePass.tryCompile();
            downsamplePass.endChangeStatesSilently();
            var upsamplePass = this._bloomMaterial.passes[BLOOM_UPSAMPLEPASS_INDEX + i];
            upsamplePass.beginChangeStatesSilently();
            upsamplePass.tryCompile();
            upsamplePass.endChangeStatesSilently();
          }
          var combinePass = this._bloomMaterial.passes[BLOOM_COMBINEPASS_INDEX];
          combinePass.beginChangeStatesSilently();
          combinePass.tryCompile();
          combinePass.endChangeStatesSilently();
        };
        _proto.updatePostProcessPass = function updatePostProcessPass() {
          if (!this.postprocessMaterial) return;
          var passPost = this.postprocessMaterial.passes[0];
          passPost.beginChangeStatesSilently();
          passPost.tryCompile();
          passPost.endChangeStatesSilently();
        };
        _proto.initPipelinePassInfo = function initPipelinePassInfo() {
          var deferredMat = new Material();
          deferredMat._uuid = 'builtin-deferred-material';
          deferredMat.initialize({
            effectName: 'pipeline/deferred-lighting'
          });
          for (var i = 0; i < deferredMat.passes.length; ++i) {
            deferredMat.passes[i].tryCompile();
          }
          this._deferredLightingMaterial = deferredMat;
          var bloomMat = new Material();
          bloomMat._uuid = 'builtin-bloom-material';
          bloomMat.initialize({
            effectName: 'pipeline/bloom'
          });
          for (var _i = 0; _i < bloomMat.passes.length; ++_i) {
            bloomMat.passes[_i].tryCompile();
          }
          this._bloomMaterial = bloomMat;
          var postMat = new Material();
          postMat._uuid = 'builtin-post-process-material';
          postMat.initialize({
            effectName: 'pipeline/post-process',
            defines: {
              ANTIALIAS_TYPE: this._antiAliasing
            }
          });
          for (var _i2 = 0; _i2 < postMat.passes.length; ++_i2) {
            postMat.passes[_i2].tryCompile();
          }
          this._postprocessMaterial = postMat;
          this.updatePipelinePassInfo();
        };
        _proto.updatePipelinePassInfo = function updatePipelinePassInfo() {
          this.updateBloomPass();
          this.updatePostProcessPass();
          this.updateDeferredPassInfo();
        };
        _proto.activate = function activate(device) {
          _PipelineSceneData.prototype.activate.call(this, device);
          this.initPipelinePassInfo();
          return true;
        };
        _proto.updateDeferredPassInfo = function updateDeferredPassInfo() {
          this.updateDeferredLightPass();
        };
        _proto.updateDeferredLightPass = function updateDeferredLightPass() {
          if (!this._deferredLightingMaterial) return;
          legacyCC.director.root.pipeline.macros.CC_RECEIVE_SHADOW = 1;
          var passLit = this._deferredLightingMaterial.passes[0];
          passLit.beginChangeStatesSilently();
          passLit.tryCompile();
          passLit.endChangeStatesSilently();
        };
        _createClass(DeferredPipelineSceneData, [{
          key: "antiAliasing",
          get: function get() {
            return this._antiAliasing;
          },
          set: function set(value) {
            this._antiAliasing = value;
            if (this._postprocessMaterial) {
              var defines = this._postprocessMaterial.passes[0].defines;
              Object.assign(defines, {
                ANTIALIAS_TYPE: value
              });
              var renderMat = new Material();
              renderMat.initialize({
                effectAsset: this._postprocessMaterial.effectAsset,
                defines: defines
              });
              for (var i = 0; i < renderMat.passes.length; ++i) {
                renderMat.passes[i].tryCompile();
              }
              this._postprocessMaterial = renderMat;
            }
          }
        }, {
          key: "bloomMaterial",
          get: function get() {
            return this._bloomMaterial;
          },
          set: function set(mat) {
            if (this._bloomMaterial === mat || !mat) return;
            this._bloomMaterial = mat;
            this.updatePipelinePassInfo();
          }
        }, {
          key: "postprocessMaterial",
          get: function get() {
            return this._postprocessMaterial;
          },
          set: function set(mat) {
            if (this._postprocessMaterial === mat || !mat) return;
            this._postprocessMaterial = mat;
            this.updatePipelinePassInfo();
          }
        }, {
          key: "deferredLightingMaterial",
          get: function get() {
            return this._deferredLightingMaterial;
          },
          set: function set(mat) {
            if (this._deferredLightingMaterial === mat || !mat) return;
            this._deferredLightingMaterial = mat;
            this.updatePipelinePassInfo();
          }
        }]);
        return DeferredPipelineSceneData;
      }(PipelineSceneData);

      var _class$2s, _dec$2v, _dec2$1T, _class2$2d, _class3$E, _initializer$21, _class4$r;
      var colors = [new Color(0, 0, 0, 1)];
      var UBOBloom = function UBOBloom() {};
      _class$2s = UBOBloom;
      UBOBloom.TEXTURE_SIZE_OFFSET = 0;
      UBOBloom.COUNT = _class$2s.TEXTURE_SIZE_OFFSET + 4;
      UBOBloom.SIZE = _class$2s.COUNT * 4;
      var BloomStage = exports('df', (_dec$2v = ccclass$n('BloomStage'), _dec2$1T = type$7(Material), _dec$2v(_class2$2d = (_class3$E = (_class4$r = function (_RenderStage) {
        _inheritsLoose(BloomStage, _RenderStage);
        function BloomStage() {
          var _this;
          _this = _RenderStage.call(this) || this;
          _this.threshold = 1.0;
          _this.intensity = 0.8;
          _this.iterations = 2;
          _this._bloomMaterial = _initializer$21 && _initializer$21();
          _this._renderArea = new Rect();
          _this._bloomUBO = [];
          return _this;
        }
        var _proto = BloomStage.prototype;
        _proto.initialize = function initialize(info) {
          _RenderStage.prototype.initialize.call(this, info);
          return true;
        };
        _proto.activate = function activate(pipeline, flow) {
          _RenderStage.prototype.activate.call(this, pipeline, flow);
          if (this._bloomMaterial) {
            pipeline.pipelineSceneData.bloomMaterial = this._bloomMaterial;
          }
        };
        _proto.destroy = function destroy() {};
        _proto.render = function render(camera) {
          var _camera$window;
          var pipeline = this._pipeline;
          pipeline.generateBloomRenderData();
          if (!((_camera$window = camera.window) !== null && _camera$window !== void 0 && _camera$window.swapchain) && !pipeline.macros.CC_PIPELINE_TYPE) {
            return;
          }
          if (!pipeline.bloomEnabled || pipeline.pipelineSceneData.renderObjects.length === 0) return;
          if (this._bloomUBO.length === 0) {
            var passNumber = MAX_BLOOM_FILTER_PASS_NUM * 2 + 2;
            for (var i = 0; i < passNumber; ++i) {
              this._bloomUBO[i] = pipeline.device.createBuffer(new BufferInfo(BufferUsageBit.UNIFORM | BufferUsageBit.TRANSFER_DST, MemoryUsageBit.HOST | MemoryUsageBit.DEVICE, UBOBloom.SIZE, UBOBloom.SIZE));
            }
          }
          if (camera.clearFlag & ClearFlagBit.COLOR) {
            colors[0].x = camera.clearColor.x;
            colors[0].y = camera.clearColor.y;
            colors[0].z = camera.clearColor.z;
          }
          colors[0].w = camera.clearColor.w;
          this._prefilterPass(camera, pipeline);
          this._downsamplePass(camera, pipeline);
          this._upsamplePass(camera, pipeline);
          this._combinePass(camera, pipeline);
        };
        _proto._prefilterPass = function _prefilterPass(camera, pipeline) {
          pipeline.generateRenderArea(camera, this._renderArea);
          this._renderArea.width >>= 1;
          this._renderArea.height >>= 1;
          var cmdBuff = pipeline.commandBuffers[0];
          var sceneData = pipeline.pipelineSceneData;
          var builtinBloomProcess = sceneData.bloomMaterial;
          var pass = builtinBloomProcess.passes[BLOOM_PREFILTERPASS_INDEX];
          var renderData = pipeline.getPipelineRenderData();
          var bloomData = renderData.bloom;
          var textureSize = new Float32Array(UBOBloom.COUNT);
          textureSize[UBOBloom.TEXTURE_SIZE_OFFSET + 2] = this.threshold;
          cmdBuff.updateBuffer(this._bloomUBO[0], textureSize);
          cmdBuff.beginRenderPass(bloomData.renderPass, bloomData.prefilterFramebuffer, this._renderArea, colors, 0, 0);
          cmdBuff.bindDescriptorSet(SetIndex.GLOBAL, pipeline.descriptorSet);
          pass.descriptorSet.bindBuffer(0, this._bloomUBO[0]);
          pass.descriptorSet.bindTexture(1, renderData.outputRenderTargets[0]);
          pass.descriptorSet.bindSampler(1, bloomData.sampler);
          pass.descriptorSet.update();
          cmdBuff.bindDescriptorSet(SetIndex.MATERIAL, pass.descriptorSet);
          var inputAssembler = camera.window.swapchain ? pipeline.quadIAOffscreen : pipeline.quadIAOnscreen;
          var pso = null;
          var shader = pass.getShaderVariant();
          if (pass != null && shader != null && inputAssembler != null) {
            pso = PipelineStateManager.getOrCreatePipelineState(pipeline.device, pass, shader, bloomData.renderPass, inputAssembler);
          }
          if (pso != null) {
            cmdBuff.bindPipelineState(pso);
            cmdBuff.bindInputAssembler(inputAssembler);
            cmdBuff.draw(inputAssembler);
          }
          cmdBuff.endRenderPass();
        };
        _proto._downsamplePass = function _downsamplePass(camera, pipeline) {
          pipeline.generateRenderArea(camera, this._renderArea);
          this._renderArea.width >>= 1;
          this._renderArea.height >>= 1;
          var cmdBuff = pipeline.commandBuffers[0];
          var sceneData = pipeline.pipelineSceneData;
          var builtinBloomProcess = sceneData.bloomMaterial;
          var bloomData = pipeline.getPipelineRenderData().bloom;
          var textureSize = new Float32Array(UBOBloom.COUNT);
          for (var i = 0; i < this.iterations; ++i) {
            textureSize[UBOBloom.TEXTURE_SIZE_OFFSET + 0] = this._renderArea.width;
            textureSize[UBOBloom.TEXTURE_SIZE_OFFSET + 1] = this._renderArea.height;
            cmdBuff.updateBuffer(this._bloomUBO[i + 1], textureSize);
            this._renderArea.width >>= 1;
            this._renderArea.height >>= 1;
            cmdBuff.beginRenderPass(bloomData.renderPass, bloomData.downsampleFramebuffers[i], this._renderArea, colors, 0, 0);
            var pass = builtinBloomProcess.passes[BLOOM_DOWNSAMPLEPASS_INDEX + i];
            var shader = pass.getShaderVariant();
            pass.descriptorSet.bindBuffer(0, this._bloomUBO[i + 1]);
            if (i === 0) {
              pass.descriptorSet.bindTexture(1, bloomData.prefiterTex);
            } else {
              pass.descriptorSet.bindTexture(1, bloomData.downsampleTexs[i - 1]);
            }
            pass.descriptorSet.bindSampler(1, bloomData.sampler);
            pass.descriptorSet.update();
            cmdBuff.bindDescriptorSet(SetIndex.MATERIAL, pass.descriptorSet);
            var inputAssembler = camera.window.swapchain ? pipeline.quadIAOffscreen : pipeline.quadIAOnscreen;
            var pso = null;
            if (pass != null && shader != null && inputAssembler != null) {
              pso = PipelineStateManager.getOrCreatePipelineState(pipeline.device, pass, shader, bloomData.renderPass, inputAssembler);
            }
            if (pso != null) {
              cmdBuff.bindPipelineState(pso);
              cmdBuff.bindInputAssembler(inputAssembler);
              cmdBuff.draw(inputAssembler);
            }
            cmdBuff.endRenderPass();
          }
        };
        _proto._upsamplePass = function _upsamplePass(camera, pipeline) {
          var bloomData = pipeline.getPipelineRenderData().bloom;
          pipeline.generateRenderArea(camera, this._renderArea);
          this._renderArea.width >>= this.iterations + 1;
          this._renderArea.height >>= this.iterations + 1;
          var cmdBuff = pipeline.commandBuffers[0];
          var sceneData = pipeline.pipelineSceneData;
          var builtinBloomProcess = sceneData.bloomMaterial;
          var textureSize = new Float32Array(UBOBloom.COUNT);
          for (var i = 0; i < this.iterations; ++i) {
            var index = i + MAX_BLOOM_FILTER_PASS_NUM + 1;
            textureSize[UBOBloom.TEXTURE_SIZE_OFFSET + 0] = this._renderArea.width;
            textureSize[UBOBloom.TEXTURE_SIZE_OFFSET + 1] = this._renderArea.height;
            cmdBuff.updateBuffer(this._bloomUBO[index], textureSize);
            this._renderArea.width <<= 1;
            this._renderArea.height <<= 1;
            cmdBuff.beginRenderPass(bloomData.renderPass, bloomData.upsampleFramebuffers[this.iterations - 1 - i], this._renderArea, colors, 0, 0);
            var pass = builtinBloomProcess.passes[BLOOM_UPSAMPLEPASS_INDEX + i];
            var shader = pass.getShaderVariant();
            pass.descriptorSet.bindBuffer(0, this._bloomUBO[index]);
            if (i === 0) {
              pass.descriptorSet.bindTexture(1, bloomData.downsampleTexs[this.iterations - 1]);
            } else {
              pass.descriptorSet.bindTexture(1, bloomData.upsampleTexs[this.iterations - i]);
            }
            pass.descriptorSet.bindSampler(1, bloomData.sampler);
            pass.descriptorSet.update();
            cmdBuff.bindDescriptorSet(SetIndex.MATERIAL, pass.descriptorSet);
            var inputAssembler = camera.window.swapchain ? pipeline.quadIAOffscreen : pipeline.quadIAOnscreen;
            var pso = null;
            if (pass != null && shader != null && inputAssembler != null) {
              pso = PipelineStateManager.getOrCreatePipelineState(pipeline.device, pass, shader, bloomData.renderPass, inputAssembler);
            }
            if (pso != null) {
              cmdBuff.bindPipelineState(pso);
              cmdBuff.bindInputAssembler(inputAssembler);
              cmdBuff.draw(inputAssembler);
            }
            cmdBuff.endRenderPass();
          }
        };
        _proto._combinePass = function _combinePass(camera, pipeline) {
          pipeline.generateRenderArea(camera, this._renderArea);
          var cmdBuff = pipeline.commandBuffers[0];
          var sceneData = pipeline.pipelineSceneData;
          var builtinBloomProcess = sceneData.bloomMaterial;
          var deferredData = pipeline.getPipelineRenderData();
          var bloomData = deferredData.bloom;
          var uboIndex = MAX_BLOOM_FILTER_PASS_NUM * 2 + 1;
          var textureSize = new Float32Array(UBOBloom.COUNT);
          textureSize[UBOBloom.TEXTURE_SIZE_OFFSET + 3] = this.intensity;
          cmdBuff.updateBuffer(this._bloomUBO[uboIndex], textureSize);
          cmdBuff.beginRenderPass(bloomData.renderPass, bloomData.combineFramebuffer, this._renderArea, colors, 0, 0);
          cmdBuff.bindDescriptorSet(SetIndex.GLOBAL, pipeline.descriptorSet);
          var pass = builtinBloomProcess.passes[BLOOM_COMBINEPASS_INDEX];
          pass.descriptorSet.bindBuffer(0, this._bloomUBO[uboIndex]);
          pass.descriptorSet.bindTexture(1, deferredData.outputRenderTargets[0]);
          pass.descriptorSet.bindTexture(2, bloomData.upsampleTexs[0]);
          pass.descriptorSet.bindSampler(1, bloomData.sampler);
          pass.descriptorSet.bindSampler(2, bloomData.sampler);
          pass.descriptorSet.update();
          cmdBuff.bindDescriptorSet(SetIndex.MATERIAL, pass.descriptorSet);
          var inputAssembler = camera.window.swapchain ? pipeline.quadIAOffscreen : pipeline.quadIAOnscreen;
          var pso = null;
          var shader = pass.getShaderVariant();
          if (pass != null && shader != null && inputAssembler != null) {
            pso = PipelineStateManager.getOrCreatePipelineState(pipeline.device, pass, shader, bloomData.renderPass, inputAssembler);
          }
          if (pso != null) {
            cmdBuff.bindPipelineState(pso);
            cmdBuff.bindInputAssembler(inputAssembler);
            cmdBuff.draw(inputAssembler);
          }
          cmdBuff.endRenderPass();
        };
        return BloomStage;
      }(RenderStage), _class4$r.initInfo = {
        name: 'BloomStage',
        priority: CommonStagePriority.BLOOM,
        tag: 0
      }, _class4$r), (_initializer$21 = applyDecoratedInitializer(_class3$E.prototype, "_bloomMaterial", [_dec2$1T, serializable$j], function () {
        return null;
      })), _class3$E)) || _class2$2d));

      var _dec$2u, _class$2r, _class2$2c;
      var MainFlow = exports('dc', (_dec$2u = ccclass$n('MainFlow'), _dec$2u(_class$2r = (_class2$2c = function (_RenderFlow) {
        _inheritsLoose(MainFlow, _RenderFlow);
        function MainFlow() {
          return _RenderFlow.apply(this, arguments) || this;
        }
        var _proto = MainFlow.prototype;
        _proto.initialize = function initialize(info) {
          _RenderFlow.prototype.initialize.call(this, info);
          if (this._stages.length === 0) {
            var gbufferStage = new GbufferStage();
            gbufferStage.initialize(GbufferStage.initInfo);
            this._stages.push(gbufferStage);
            var lightingStage = new LightingStage();
            lightingStage.initialize(LightingStage.initInfo);
            this._stages.push(lightingStage);
            var bloomStage = new BloomStage();
            bloomStage.initialize(BloomStage.initInfo);
            this._stages.push(bloomStage);
            var postProcessStage = new PostProcessStage();
            postProcessStage.initialize(PostProcessStage.initInfo);
            this._stages.push(postProcessStage);
          }
          return true;
        };
        _proto.activate = function activate(pipeline) {
          _RenderFlow.prototype.activate.call(this, pipeline);
        };
        _proto.render = function render(camera) {
          _RenderFlow.prototype.render.call(this, camera);
        };
        _proto.destroy = function destroy() {
          _RenderFlow.prototype.destroy.call(this);
        };
        return MainFlow;
      }(RenderFlow), _class2$2c.initInfo = {
        name: PIPELINE_FLOW_MAIN,
        priority: DeferredFlowPriority.MAIN,
        stages: []
      }, _class2$2c)) || _class$2r));

      var _dec$2t, _dec2$1S, _class2$2b, _class3$D, _initializer$20;
      var PIPELINE_TYPE = 1;
      var DeferredRenderData = function (_PipelineRenderData) {
        _inheritsLoose(DeferredRenderData, _PipelineRenderData);
        function DeferredRenderData() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _PipelineRenderData.call.apply(_PipelineRenderData, [this].concat(args)) || this;
          _this.gbufferFrameBuffer = null;
          _this.gbufferRenderTargets = [];
          return _this;
        }
        return DeferredRenderData;
      }(PipelineRenderData);
      var DeferredPipeline = exports('db', (_dec$2t = ccclass$n('DeferredPipeline'), _dec2$1S = type$7([RenderTextureConfig]), _dec$2t(_class2$2b = (_class3$D = function (_RenderPipeline) {
        _inheritsLoose(DeferredPipeline, _RenderPipeline);
        function DeferredPipeline() {
          var _this2;
          for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
            args[_key2] = arguments[_key2];
          }
          _this2 = _RenderPipeline.call.apply(_RenderPipeline, [this].concat(args)) || this;
          _this2._gbufferRenderPass = null;
          _this2._lightingRenderPass = null;
          _this2.renderTextures = _initializer$20 && _initializer$20();
          return _this2;
        }
        var _proto = DeferredPipeline.prototype;
        _proto.initialize = function initialize(info) {
          _RenderPipeline.prototype.initialize.call(this, info);
          if (this._flows.length === 0) {
            var shadowFlow = new ShadowFlow();
            shadowFlow.initialize(ShadowFlow.initInfo);
            this._flows.push(shadowFlow);
            var mainFlow = new MainFlow();
            mainFlow.initialize(MainFlow.initInfo);
            this._flows.push(mainFlow);
          }
          return true;
        };
        _proto.activate = function activate(swapchain) {
          this._macros = {
            CC_PIPELINE_TYPE: PIPELINE_TYPE
          };
          this._pipelineSceneData = new DeferredPipelineSceneData();
          if (!_RenderPipeline.prototype.activate.call(this, swapchain)) {
            return false;
          }
          if (!this._activeRenderer(swapchain)) {
            errorID(2402);
            return false;
          }
          return true;
        };
        _proto.destroy = function destroy() {
          this._destroyUBOs();
          this._destroyQuadInputAssembler();
          this._destroyDeferredData();
          var rpIter = this._renderPasses.values();
          var rpRes = rpIter.next();
          while (!rpRes.done) {
            rpRes.value.destroy();
            rpRes = rpIter.next();
          }
          this._commandBuffers.length = 0;
          return _RenderPipeline.prototype.destroy.call(this);
        };
        _proto.onGlobalPipelineStateChanged = function onGlobalPipelineStateChanged() {
          this.pipelineSceneData.updatePipelineSceneData();
        };
        _proto.getPipelineRenderData = function getPipelineRenderData() {
          if (!this._pipelineRenderData) {
            this._generateDeferredRenderData();
          }
          return this._pipelineRenderData;
        };
        _proto._activeRenderer = function _activeRenderer(swapchain) {
          var device = this.device;
          this._commandBuffers.push(device.commandBuffer);
          var sampler = this.globalDSManager.pointSampler;
          this._descriptorSet.bindSampler(UNIFORM_SHADOWMAP_BINDING, sampler);
          this._descriptorSet.bindTexture(UNIFORM_SHADOWMAP_BINDING, builtinResMgr.get('default-texture').getGFXTexture());
          this._descriptorSet.bindSampler(UNIFORM_SPOT_SHADOW_MAP_TEXTURE_BINDING, sampler);
          this._descriptorSet.bindTexture(UNIFORM_SPOT_SHADOW_MAP_TEXTURE_BINDING, builtinResMgr.get('default-texture').getGFXTexture());
          this._descriptorSet.update();
          var inputAssemblerDataOffscreen = new PipelineInputAssemblerData();
          inputAssemblerDataOffscreen = this._createQuadInputAssembler();
          if (!inputAssemblerDataOffscreen.quadIB || !inputAssemblerDataOffscreen.quadVB || !inputAssemblerDataOffscreen.quadIA) {
            return false;
          }
          this._quadIB = inputAssemblerDataOffscreen.quadIB;
          this._quadVBOffscreen = inputAssemblerDataOffscreen.quadVB;
          this._quadIAOffscreen = inputAssemblerDataOffscreen.quadIA;
          var inputAssemblerDataOnscreen = this._createQuadInputAssembler();
          if (!inputAssemblerDataOnscreen.quadIB || !inputAssemblerDataOnscreen.quadVB || !inputAssemblerDataOnscreen.quadIA) {
            return false;
          }
          this._quadVBOnscreen = inputAssemblerDataOnscreen.quadVB;
          this._quadIAOnscreen = inputAssemblerDataOnscreen.quadIA;
          if (!this._gbufferRenderPass) {
            var colorAttachment0 = new ColorAttachment();
            colorAttachment0.format = Format.RGBA16F;
            colorAttachment0.loadOp = LoadOp.CLEAR;
            colorAttachment0.storeOp = StoreOp.STORE;
            var colorAttachment1 = new ColorAttachment();
            colorAttachment1.format = Format.RGBA16F;
            colorAttachment1.loadOp = LoadOp.CLEAR;
            colorAttachment1.storeOp = StoreOp.STORE;
            var colorAttachment2 = new ColorAttachment();
            colorAttachment2.format = Format.RGBA16F;
            colorAttachment2.loadOp = LoadOp.CLEAR;
            colorAttachment2.storeOp = StoreOp.STORE;
            var depthStencilAttachment = new DepthStencilAttachment();
            depthStencilAttachment.format = Format.DEPTH_STENCIL;
            depthStencilAttachment.depthLoadOp = LoadOp.CLEAR;
            depthStencilAttachment.depthStoreOp = StoreOp.STORE;
            depthStencilAttachment.stencilLoadOp = LoadOp.CLEAR;
            depthStencilAttachment.stencilStoreOp = StoreOp.STORE;
            var renderPassInfo = new RenderPassInfo([colorAttachment0, colorAttachment1, colorAttachment2], depthStencilAttachment);
            this._gbufferRenderPass = device.createRenderPass(renderPassInfo);
          }
          if (!this._lightingRenderPass) {
            var colorAttachment = new ColorAttachment();
            colorAttachment.format = Format.RGBA8;
            colorAttachment.loadOp = LoadOp.CLEAR;
            colorAttachment.storeOp = StoreOp.STORE;
            colorAttachment.barrier = device.getGeneralBarrier(new GeneralBarrierInfo(AccessFlagBit.NONE, AccessFlagBit.COLOR_ATTACHMENT_WRITE));
            var _depthStencilAttachment = new DepthStencilAttachment();
            _depthStencilAttachment.format = Format.DEPTH_STENCIL;
            _depthStencilAttachment.depthLoadOp = LoadOp.LOAD;
            _depthStencilAttachment.depthStoreOp = StoreOp.DISCARD;
            _depthStencilAttachment.stencilLoadOp = LoadOp.LOAD;
            _depthStencilAttachment.stencilStoreOp = StoreOp.DISCARD;
            colorAttachment.barrier = device.getGeneralBarrier(new GeneralBarrierInfo(AccessFlagBit.DEPTH_STENCIL_ATTACHMENT_WRITE, AccessFlagBit.DEPTH_STENCIL_ATTACHMENT_WRITE));
            var _renderPassInfo = new RenderPassInfo([colorAttachment], _depthStencilAttachment);
            this._lightingRenderPass = device.createRenderPass(_renderPassInfo);
          }
          this._width = swapchain.width;
          this._height = swapchain.height;
          this._generateDeferredRenderData();
          return true;
        };
        _proto._destroyUBOs = function _destroyUBOs() {
          if (this._descriptorSet) {
            this._descriptorSet.getBuffer(UBOGlobal.BINDING).destroy();
            this._descriptorSet.getBuffer(UBOShadow.BINDING).destroy();
            this._descriptorSet.getBuffer(UBOCamera.BINDING).destroy();
            this._descriptorSet.getTexture(UNIFORM_SHADOWMAP_BINDING).destroy();
            this._descriptorSet.getTexture(UNIFORM_SPOT_SHADOW_MAP_TEXTURE_BINDING).destroy();
          }
        };
        _proto._destroyDeferredData = function _destroyDeferredData() {
          var deferredData = this._pipelineRenderData;
          if (deferredData) {
            if (deferredData.gbufferFrameBuffer) deferredData.gbufferFrameBuffer.destroy();
            if (deferredData.outputFrameBuffer) deferredData.outputFrameBuffer.destroy();
            if (deferredData.outputDepth) deferredData.outputDepth.destroy();
            for (var i = 0; i < deferredData.gbufferRenderTargets.length; i++) {
              deferredData.gbufferRenderTargets[i].destroy();
            }
            deferredData.gbufferRenderTargets.length = 0;
            for (var _i = 0; _i < deferredData.outputRenderTargets.length; _i++) {
              deferredData.outputRenderTargets[_i].destroy();
            }
            deferredData.outputRenderTargets.length = 0;
            this._destroyBloomData();
          }
          this._pipelineRenderData = null;
        };
        _proto._ensureEnoughSize = function _ensureEnoughSize(cameras) {
          var newWidth = this._width;
          var newHeight = this._height;
          for (var i = 0; i < cameras.length; ++i) {
            var window = cameras[i].window;
            newWidth = Math.max(window.width, newWidth);
            newHeight = Math.max(window.height, newHeight);
          }
          if (newWidth !== this._width || newHeight !== this._height) {
            this._width = newWidth;
            this._height = newHeight;
            this._destroyDeferredData();
            this._generateDeferredRenderData();
          }
        };
        _proto._generateDeferredRenderData = function _generateDeferredRenderData() {
          var _this3 = this;
          var device = this.device;
          var data = this._pipelineRenderData = new DeferredRenderData();
          var sceneData = this.pipelineSceneData;
          for (var i = 0; i < 3; ++i) {
            data.gbufferRenderTargets.push(device.createTexture(new TextureInfo(TextureType.TEX2D, TextureUsageBit.COLOR_ATTACHMENT | TextureUsageBit.SAMPLED, Format.RGBA16F, this._width * sceneData.shadingScale, this._height * sceneData.shadingScale)));
          }
          data.outputDepth = device.createTexture(new TextureInfo(TextureType.TEX2D, TextureUsageBit.DEPTH_STENCIL_ATTACHMENT | TextureUsageBit.SAMPLED, Format.DEPTH_STENCIL, this._width * sceneData.shadingScale, this._height * sceneData.shadingScale));
          data.gbufferFrameBuffer = device.createFramebuffer(new FramebufferInfo(this._gbufferRenderPass, data.gbufferRenderTargets, data.outputDepth));
          data.outputRenderTargets.push(device.createTexture(new TextureInfo(TextureType.TEX2D, TextureUsageBit.COLOR_ATTACHMENT | TextureUsageBit.SAMPLED, Format.RGBA16F, this._width * sceneData.shadingScale, this._height * sceneData.shadingScale)));
          data.outputFrameBuffer = device.createFramebuffer(new FramebufferInfo(this._lightingRenderPass, data.outputRenderTargets, null));
          data.sampler = this.globalDSManager.pointSampler;
          this.on(PipelineEventType.ATTACHMENT_SCALE_CAHNGED, function (val) {
            data.sampler = val < 1 ? _this3.globalDSManager.pointSampler : _this3.globalDSManager.linearSampler;
            data.gbufferFrameBuffer = _this3.newFramebufferByRatio(data.gbufferFrameBuffer);
            data.gbufferFrameBuffer = _this3.newFramebufferByRatio(data.outputFrameBuffer);
          });
        };
        return DeferredPipeline;
      }(RenderPipeline), (_initializer$20 = applyDecoratedInitializer(_class3$D.prototype, "renderTextures", [_dec2$1S, serializable$j], function () {
        return [];
      })), _class3$D)) || _class2$2b));

      var XREye;
      (function (XREye) {
        XREye[XREye["NONE"] = -1] = "NONE";
        XREye[XREye["LEFT"] = 0] = "LEFT";
        XREye[XREye["RIGHT"] = 1] = "RIGHT";
      })(XREye || (XREye = {}));
      var XRConfigKey;
      (function (XRConfigKey) {
        XRConfigKey[XRConfigKey["SESSION_RUNNING"] = 2] = "SESSION_RUNNING";
        XRConfigKey[XRConfigKey["VIEW_COUNT"] = 6] = "VIEW_COUNT";
        XRConfigKey[XRConfigKey["SWAPCHAIN_WIDTH"] = 7] = "SWAPCHAIN_WIDTH";
        XRConfigKey[XRConfigKey["SWAPCHAIN_HEIGHT"] = 8] = "SWAPCHAIN_HEIGHT";
        XRConfigKey[XRConfigKey["DEVICE_IPD"] = 37] = "DEVICE_IPD";
        XRConfigKey[XRConfigKey["SPLIT_AR_GLASSES"] = 42] = "SPLIT_AR_GLASSES";
      })(XRConfigKey || (XRConfigKey = {}));
      var XRPoseType;
      (function (XRPoseType) {
        XRPoseType[XRPoseType["VIEW_LEFT"] = 0] = "VIEW_LEFT";
        XRPoseType[XRPoseType["HAND_LEFT"] = 1] = "HAND_LEFT";
        XRPoseType[XRPoseType["AIM_LEFT"] = 2] = "AIM_LEFT";
        XRPoseType[XRPoseType["VIEW_RIGHT"] = 3] = "VIEW_RIGHT";
        XRPoseType[XRPoseType["HAND_RIGHT"] = 4] = "HAND_RIGHT";
        XRPoseType[XRPoseType["AIM_RIGHT"] = 5] = "AIM_RIGHT";
        XRPoseType[XRPoseType["HEAD_MIDDLE"] = 6] = "HEAD_MIDDLE";
      })(XRPoseType || (XRPoseType = {}));

      var v2_0 = new Vec2();
      var SplashScreen = function () {
        var _proto = SplashScreen.prototype;
        _proto.init = function init() {
          var _settings$querySettin,
            _settings$querySettin2,
            _settings$querySettin3,
            _settings$querySettin4,
            _settings$querySettin5,
            _settings$querySettin6,
            _this = this;
          this.settings = {
            displayRatio: (_settings$querySettin = settings.querySettings(Settings.Category.SPLASH_SCREEN, 'displayRatio')) !== null && _settings$querySettin !== void 0 ? _settings$querySettin : 0.4,
            totalTime: (_settings$querySettin2 = settings.querySettings(Settings.Category.SPLASH_SCREEN, 'totalTime')) !== null && _settings$querySettin2 !== void 0 ? _settings$querySettin2 : 3000,
            watermarkLocation: (_settings$querySettin3 = settings.querySettings(Settings.Category.SPLASH_SCREEN, 'watermarkLocation')) !== null && _settings$querySettin3 !== void 0 ? _settings$querySettin3 : 'default',
            autoFit: (_settings$querySettin4 = settings.querySettings(Settings.Category.SPLASH_SCREEN, 'autoFit')) !== null && _settings$querySettin4 !== void 0 ? _settings$querySettin4 : true,
            logo: (_settings$querySettin5 = settings.querySettings(Settings.Category.SPLASH_SCREEN, 'logo')) !== null && _settings$querySettin5 !== void 0 ? _settings$querySettin5 : undefined,
            background: (_settings$querySettin6 = settings.querySettings(Settings.Category.SPLASH_SCREEN, 'background')) !== null && _settings$querySettin6 !== void 0 ? _settings$querySettin6 : undefined
          };
          this._curTime = 0;
          if (this.settings.totalTime <= 0 || this.settings.logo === undefined || this.settings.background === undefined) {
            this.settings.totalTime = 0;
          } else {
            this.device = legacyCC.director.root.device;
            this.swapchain = legacyCC.director.root.mainWindow.swapchain;
            this.preInit();
            this.initLayout();
            if (this.settings.logo.type === 'default') {
              this.initWaterMark();
            }
            var bgPromise = Promise.resolve();
            var logoPromise = Promise.resolve();
            if (this.settings.background.type === 'custom') {
              bgPromise = new Promise(function (resolve, reject) {
                _this.bgImage = new ccwindow.Image();
                _this.bgImage.onload = function () {
                  _this.initBG();
                  resolve();
                };
                _this.bgImage.onerror = function () {
                  reject();
                };
                _this.bgImage.src = _this.settings.background.base64;
              });
            }
            if (this.settings.logo.type !== 'none') {
              logoPromise = new Promise(function (resolve, reject) {
                _this.logoImage = new ccwindow.Image();
                _this.logoImage.onload = function () {
                  _this.initLogo();
                  resolve();
                };
                _this.logoImage.onerror = function () {
                  reject();
                };
                _this.logoImage.src = _this.settings.logo.base64;
              });
            }
            return Promise.all([bgPromise, logoPromise]);
          }
          return Promise.resolve([]);
        };
        _proto.preInit = function preInit() {
          var _this$settings$backgr;
          var clearColor = (_this$settings$backgr = this.settings.background) === null || _this$settings$backgr === void 0 ? void 0 : _this$settings$backgr.color;
          this.clearColors = clearColor ? [new Color(clearColor.x, clearColor.y, clearColor.z, clearColor.w)] : [new Color(0, 0, 0, 1)];
          var device = this.device,
            swapchain = this.swapchain;
          this.renderArea = new Rect(0, 0, swapchain.width, swapchain.height);
          this.cmdBuff = device.commandBuffer;
          var verts = new Float32Array([0.5, 0.5, 1, 0, -0.5, 0.5, 0, 0, 0.5, -0.5, 1, 1, -0.5, -0.5, 0, 1]);
          var vbStride = Float32Array.BYTES_PER_ELEMENT * 4;
          var vbSize = vbStride * 4;
          this.vertexBuffers = device.createBuffer(new BufferInfo(BufferUsageBit.VERTEX | BufferUsageBit.TRANSFER_DST, MemoryUsageBit.DEVICE, vbSize, vbStride));
          this.vertexBuffers.update(verts);
          var indices = new Uint16Array([0, 1, 2, 1, 3, 2]);
          var ibStride = Uint16Array.BYTES_PER_ELEMENT;
          var ibSize = ibStride * 6;
          this.indicesBuffers = device.createBuffer(new BufferInfo(BufferUsageBit.INDEX | BufferUsageBit.TRANSFER_DST, MemoryUsageBit.DEVICE, ibSize, ibStride));
          this.indicesBuffers.update(indices);
          var attributes = [new Attribute('a_position', Format.RG32F), new Attribute('a_texCoord', Format.RG32F)];
          var IAInfo = new InputAssemblerInfo(attributes, [this.vertexBuffers], this.indicesBuffers);
          this.quadAssmebler = device.createInputAssembler(IAInfo);
          this.projection = new Mat4();
          Mat4.ortho(this.projection, -1, 1, -1, 1, -1, 1, device.capabilities.clipSpaceMinZ, device.capabilities.clipSpaceSignY, swapchain.surfaceTransform);
          this.isMobile = sys.isMobile;
        };
        _proto.initLayout = function initLayout() {
          if (this.isMobile) {
            this.bgWidth = 812;
            this.bgHeight = 375;
            this.logoWidthTemp = 70;
            this.logoHeightTemp = 100;
            this.textSize = 12;
            this.textHeight = this.textSize + this.textExpandSize;
            this.textXTrans = 1 / 2;
            this.textYExtraTrans = 16;
          } else {
            this.bgWidth = 1920;
            this.bgHeight = 1080;
            this.logoWidthTemp = 140;
            this.logoHeightTemp = 200;
            this.textSize = 24;
            this.textHeight = this.textSize + this.textExpandSize;
            this.textXTrans = 1 / 2;
            this.textYExtraTrans = 32;
          }
          this.logoXTrans = 1 / 2;
          this.logoYTrans = 1 / 6 + 2.5 / 6;
          this.initScale();
        };
        _proto.initScale = function initScale() {
          var dw = this.swapchain.width;
          var dh = this.swapchain.height;
          var desiredWidth = this.isMobile ? 375 : 1080;
          var desiredHeight = this.isMobile ? 812 : 1920;
          if (dw > dh) {
            var temp = desiredHeight;
            desiredHeight = desiredWidth;
            desiredWidth = temp;
          }
          if (dw / dh > 16 / 9) {
            this.scaleSize = dh / desiredHeight;
          } else {
            this.scaleSize = dw / desiredWidth;
          }
        };
        _proto.update = function update(deltaTime) {
          var settings = this.settings;
          var device = this.device,
            swapchain = this.swapchain;
          Mat4.ortho(this.projection, -1, 1, -1, 1, -1, 1, device.capabilities.clipSpaceMinZ, device.capabilities.clipSpaceSignY, swapchain.surfaceTransform);
          var dw = swapchain.width;
          var dh = swapchain.height;
          this.initScale();
          this._curTime += deltaTime * 1000;
          var percent = clamp01(this._curTime / settings.totalTime);
          var u_p = cubicOut(percent);
          var scaleX = 1;
          var scaleY = 1;
          if (this.settings.background.type === 'custom') {
            if (dw < dh) {
              scaleX = dh * this.bgRatio;
              scaleY = dh;
            } else {
              scaleX = dw;
              scaleY = dw * this.bgRatio;
            }
            this.bgMat.setProperty('resolution', v2_0.set(dw, dh), 0);
            this.bgMat.setProperty('scale', v2_0.set(scaleX, scaleY), 0);
            this.bgMat.setProperty('translate', v2_0.set(dw * 0.5, dh * 0.5), 0);
            this.bgMat.setProperty('percent', 1.0);
            this.bgMat.setProperty('u_projection', this.projection);
            this.bgMat.passes[0].update();
          }
          var logoYTrans = dh * this.logoYTrans;
          if (this.settings.logo.type !== 'none') {
            scaleX = this.logoWidth * this.scaleSize * settings.displayRatio;
            scaleY = this.logoHeight * this.scaleSize * settings.displayRatio;
            this.logoMat.setProperty('resolution', v2_0.set(dw, dh), 0);
            this.logoMat.setProperty('scale', v2_0.set(scaleX, scaleY), 0);
            this.logoMat.setProperty('translate', v2_0.set(dw * this.logoXTrans, logoYTrans), 0);
            this.logoMat.setProperty('percent', u_p);
            this.logoMat.setProperty('u_projection', this.projection);
            this.logoMat.passes[0].update();
          }
          if (this.settings.logo.type === 'default' && this.watermarkMat) {
            var watermarkTW = this.watermarkTexture.width;
            var watermarkTH = this.watermarkTexture.height;
            scaleX = watermarkTW;
            scaleY = watermarkTH;
            var textYTrans = logoYTrans - (this.logoHeight * 0.5 * settings.displayRatio + this.textYExtraTrans) * this.scaleSize - watermarkTH * 0.5;
            this.watermarkMat.setProperty('resolution', v2_0.set(dw, dh), 0);
            this.watermarkMat.setProperty('scale', v2_0.set(scaleX, scaleY), 0);
            this.watermarkMat.setProperty('translate', v2_0.set(dw * this.textXTrans, textYTrans), 0);
            this.watermarkMat.setProperty('percent', u_p);
            this.watermarkMat.setProperty('u_projection', this.projection);
            this.watermarkMat.passes[0].update();
          }
          this.frame();
        };
        _proto.initBG = function initBG() {
          var device = this.device;
          this.bgMat = new Material();
          this.bgMat.initialize({
            effectName: 'util/splash-screen'
          });
          var samplerInfo = new SamplerInfo();
          samplerInfo.addressU = Address.CLAMP;
          samplerInfo.addressV = Address.CLAMP;
          samplerInfo.addressW = Address.CLAMP;
          this.sampler = device.getSampler(samplerInfo);
          this.bgTexture = device.createTexture(new TextureInfo(TextureType.TEX2D, TextureUsageBit.SAMPLED | TextureUsageBit.TRANSFER_DST, Format.RGBA8, this.bgImage.width, this.bgImage.height));
          var pass = this.bgMat.passes[0];
          var binding = pass.getBinding('mainTexture');
          pass.bindTexture(binding, this.bgTexture);
          this.shader = pass.getShaderVariant();
          var descriptorSet = pass.descriptorSet;
          descriptorSet.bindSampler(binding, this.sampler);
          descriptorSet.update();
          var region = new BufferTextureCopy();
          region.texExtent.width = this.bgImage.width;
          region.texExtent.height = this.bgImage.height;
          region.texExtent.depth = 1;
          device.copyTexImagesToTexture([this.bgImage], this.bgTexture, [region]);
        };
        _proto.initLogo = function initLogo() {
          var device = this.device;
          this.logoMat = new Material();
          this.logoMat.initialize({
            effectName: 'util/splash-screen'
          });
          var samplerInfo = new SamplerInfo();
          samplerInfo.addressU = Address.CLAMP;
          samplerInfo.addressV = Address.CLAMP;
          samplerInfo.addressW = Address.CLAMP;
          this.sampler = device.getSampler(samplerInfo);
          this.logoTexture = device.createTexture(new TextureInfo(TextureType.TEX2D, TextureUsageBit.SAMPLED | TextureUsageBit.TRANSFER_DST, Format.RGBA8, this.logoImage.width, this.logoImage.height));
          var pass = this.logoMat.passes[0];
          var binding = pass.getBinding('mainTexture');
          pass.bindTexture(binding, this.logoTexture);
          this.shader = pass.getShaderVariant();
          var descriptorSet = pass.descriptorSet;
          descriptorSet.bindSampler(binding, this.sampler);
          descriptorSet.update();
          var region = new BufferTextureCopy();
          region.texExtent.width = this.logoImage.width;
          region.texExtent.height = this.logoImage.height;
          region.texExtent.depth = 1;
          device.copyTexImagesToTexture([this.logoImage], this.logoTexture, [region]);
          var logoRatio = this.logoImage.width / this.logoImage.height;
          if (logoRatio < 1) {
            this.logoWidth = this.logoWidthTemp;
            this.logoHeight = this.logoWidthTemp / logoRatio;
          } else {
            this.logoWidth = this.logoHeightTemp * logoRatio;
            this.logoHeight = this.logoHeightTemp;
          }
        };
        _proto.initWaterMark = function initWaterMark() {
          var watermarkImg = ccwindow.document.createElement('canvas');
          watermarkImg.height = this.textHeight * this.scaleSize;
          watermarkImg.style.width = "" + watermarkImg.width;
          watermarkImg.style.height = "" + watermarkImg.height;
          var text = 'Created with Cocos';
          var ctx = watermarkImg.getContext('2d');
          ctx.font = this.textSize * this.scaleSize + "px Arial";
          ctx.textBaseline = 'top';
          ctx.textAlign = 'center';
          ctx.fillStyle = '#707070';
          var textLength = ctx.measureText(text).width + 10;
          watermarkImg.width = textLength;
          ctx.font = this.textSize * this.scaleSize + "px Arial";
          ctx.textBaseline = 'top';
          ctx.textAlign = 'center';
          ctx.fillStyle = '#707070';
          ctx.fillText(text, watermarkImg.width / 2, 0);
          var region = new BufferTextureCopy();
          region.texExtent.width = watermarkImg.width;
          region.texExtent.height = watermarkImg.height;
          region.texExtent.depth = 1;
          this.watermarkTexture = this.device.createTexture(new TextureInfo(TextureType.TEX2D, TextureUsageBit.SAMPLED | TextureUsageBit.TRANSFER_DST, Format.RGBA8, watermarkImg.width, watermarkImg.height));
          this.device.copyTexImagesToTexture([watermarkImg], this.watermarkTexture, [region]);
          this.watermarkMat = new Material();
          this.watermarkMat.initialize({
            effectName: 'util/splash-screen'
          });
          var pass = this.watermarkMat.passes[0];
          var binding = pass.getBinding('mainTexture');
          pass.bindTexture(binding, this.watermarkTexture);
          pass.descriptorSet.update();
        };
        _proto.frame = function frame() {
          var device = this.device,
            swapchain = this.swapchain;
          if (!sys.isXR || xr.entry.isRenderAllowable()) {
            var renderSize = sys.isXR ? 2 : 1;
            for (var xrEye = 0; xrEye < renderSize; xrEye++) {
              if (sys.isXR) {
                xr.entry.renderLoopStart(xrEye);
                var xrFov = xr.entry.getEyeFov(xrEye);
                var radioLeft = 1.0;
                var radioRight = 1.0;
                if (xrEye === XREye.LEFT) {
                  radioLeft = Math.abs(Math.tan(xrFov[0])) / Math.abs(Math.tan(xrFov[1]));
                } else if (xrEye === XREye.RIGHT) {
                  radioRight = Math.abs(Math.tan(xrFov[1])) / Math.abs(Math.tan(xrFov[0]));
                }
                Mat4.ortho(this.projection, -radioLeft, radioRight, -1, 1, -1, 1, device.capabilities.clipSpaceMinZ, device.capabilities.clipSpaceSignY, swapchain.surfaceTransform);
                this.projection.m00 = preTransforms[swapchain.surfaceTransform][0];
                this.projection.m05 = preTransforms[swapchain.surfaceTransform][3] * device.capabilities.clipSpaceSignY;
                if (this.settings.background.type === 'custom') {
                  this.bgMat.setProperty('u_projection', this.projection);
                  this.bgMat.passes[0].update();
                }
                if (this.settings.logo.type !== 'none') {
                  this.logoMat.setProperty('u_projection', this.projection);
                  this.logoMat.passes[0].update();
                }
                if (this.settings.logo.type === 'default' && this.watermarkMat) {
                  this.watermarkMat.setProperty('u_projection', this.projection);
                  this.watermarkMat.passes[0].update();
                }
              }
              device.enableAutoBarrier(true);
              device.acquire([swapchain]);
              var cmdBuff = this.cmdBuff;
              var framebuffer = legacyCC.director.root.mainWindow.framebuffer;
              var renderArea = this.renderArea;
              renderArea.width = swapchain.width;
              renderArea.height = swapchain.height;
              cmdBuff.begin();
              cmdBuff.beginRenderPass(framebuffer.renderPass, framebuffer, renderArea, this.clearColors, 1.0, 0);
              if (this.settings.background.type === 'custom') {
                var bgPass = this.bgMat.passes[0];
                var bgPso = PipelineStateManager.getOrCreatePipelineState(device, bgPass, this.shader, framebuffer.renderPass, this.quadAssmebler);
                cmdBuff.bindPipelineState(bgPso);
                cmdBuff.bindDescriptorSet(SetIndex.MATERIAL, bgPass.descriptorSet);
                cmdBuff.bindInputAssembler(this.quadAssmebler);
                cmdBuff.draw(this.quadAssmebler);
              }
              if (this.settings.logo.type !== 'none') {
                var logoPass = this.logoMat.passes[0];
                var logoPso = PipelineStateManager.getOrCreatePipelineState(device, logoPass, this.shader, framebuffer.renderPass, this.quadAssmebler);
                cmdBuff.bindPipelineState(logoPso);
                cmdBuff.bindDescriptorSet(SetIndex.MATERIAL, logoPass.descriptorSet);
                cmdBuff.bindInputAssembler(this.quadAssmebler);
                cmdBuff.draw(this.quadAssmebler);
              }
              if (this.settings.logo.type === 'default' && this.watermarkMat) {
                var wartermarkPass = this.watermarkMat.passes[0];
                var watermarkPso = PipelineStateManager.getOrCreatePipelineState(device, wartermarkPass, this.shader, framebuffer.renderPass, this.quadAssmebler);
                cmdBuff.bindPipelineState(watermarkPso);
                cmdBuff.bindDescriptorSet(SetIndex.MATERIAL, wartermarkPass.descriptorSet);
                cmdBuff.bindInputAssembler(this.quadAssmebler);
                cmdBuff.draw(this.quadAssmebler);
              }
              cmdBuff.endRenderPass();
              cmdBuff.end();
              device.flushCommands([cmdBuff]);
              device.queue.submit([cmdBuff]);
              device.present();
              device.enableAutoBarrier(!legacyCC.rendering);
              if (sys.isXR) {
                xr.entry.renderLoopEnd(xrEye);
              }
            }
          }
        };
        _proto.destroy = function destroy() {
          this.device = null;
          this.swapchain = null;
          this.clearColors = null;
          if (this.settings.background.type === 'custom') {
            if (this.bgImage.destroy) this.bgImage.destroy();
            this.bgImage = null;
            this.bgMat.destroy();
            this.bgMat = null;
            this.bgTexture.destroy();
            this.bgTexture = null;
          }
          if (this.settings.logo.type !== 'none') {
            if (this.logoImage.destroy) this.logoImage.destroy();
            this.logoImage = null;
            this.logoMat.destroy();
            this.logoMat = null;
            this.logoTexture.destroy();
            this.logoTexture = null;
          }
          this.renderArea = null;
          this.cmdBuff = null;
          this.shader = null;
          this.quadAssmebler.destroy();
          this.quadAssmebler = null;
          this.vertexBuffers.destroy();
          this.vertexBuffers = null;
          this.indicesBuffers.destroy();
          this.indicesBuffers = null;
          this.sampler = null;
          if (this.settings.logo.type === 'default' && this.watermarkTexture) {
            this.watermarkMat.destroy();
            this.watermarkMat = null;
            this.watermarkTexture.destroy();
            this.watermarkTexture = null;
          }
          this.settings = null;
        };
        function SplashScreen() {
          this.settings = void 0;
          this._curTime = 0;
          this.device = void 0;
          this.swapchain = void 0;
          this.shader = void 0;
          this.sampler = void 0;
          this.cmdBuff = void 0;
          this.quadAssmebler = void 0;
          this.vertexBuffers = void 0;
          this.indicesBuffers = void 0;
          this.renderArea = void 0;
          this.clearColors = void 0;
          this.projection = void 0;
          this.isMobile = false;
          this.bgMat = void 0;
          this.bgImage = void 0;
          this.bgTexture = void 0;
          this.logoMat = void 0;
          this.logoImage = void 0;
          this.logoTexture = void 0;
          this.watermarkMat = void 0;
          this.watermarkTexture = void 0;
          this.bgWidth = 1920;
          this.bgHeight = 1080;
          this.bgRatio = 16 / 9;
          this.logoWidthTemp = 140;
          this.logoHeightTemp = 200;
          this.logoWidth = 0;
          this.logoHeight = 0;
          this.logoXTrans = 1 / 2;
          this.logoYTrans = 1 / 6 + 2.5 / 6;
          this.textSize = 24;
          this.textHeight = 24;
          this.textXTrans = 1 / 2;
          this.textYExtraTrans = 32;
          this.textExpandSize = 4;
          this.scaleSize = 1;
        }
        _createClass(SplashScreen, [{
          key: "isFinished",
          get: function get() {
            return this._curTime >= this.settings.totalTime;
          }
        }, {
          key: "curTime",
          get: function get() {
            return this._curTime;
          },
          set: function set(val) {
            this._curTime = val;
          }
        }], [{
          key: "instance",
          get: function get() {
            if (!SplashScreen._ins) {
              SplashScreen._ins = new SplashScreen();
            }
            return SplashScreen._ins;
          }
        }]);
        return SplashScreen;
      }();
      SplashScreen._ins = void 0;
      legacyCC.internal.SplashScreen = SplashScreen;

      var Event = exports('eo', function () {
        function Event(type, bubbles) {
          this.type = void 0;
          this.bubbles = void 0;
          this.target = null;
          this.currentTarget = null;
          this.eventPhase = 0;
          this.propagationStopped = false;
          this.propagationImmediateStopped = false;
          this.type = type;
          this.bubbles = !!bubbles;
        }
        var _proto = Event.prototype;
        _proto.unuse = function unuse() {
          this.type = Event.NO_TYPE;
          this.target = null;
          this.currentTarget = null;
          this.eventPhase = Event.NONE;
          this.propagationStopped = false;
          this.propagationImmediateStopped = false;
        };
        _proto.reuse = function reuse(type, bubbles) {
          this.type = type;
          this.bubbles = bubbles || false;
        };
        _proto.isStopped = function isStopped() {
          return this.propagationStopped || this.propagationImmediateStopped;
        };
        _proto.getCurrentTarget = function getCurrentTarget() {
          return this.currentTarget;
        };
        _proto.getType = function getType() {
          return this.type;
        };
        return Event;
      }());
      Event.NO_TYPE = 'no_type';
      Event.TOUCH = 'touch';
      Event.MOUSE = 'mouse';
      Event.KEYBOARD = 'keyboard';
      Event.ACCELERATION = 'acceleration';
      Event.NONE = 0;
      Event.CAPTURING_PHASE = 1;
      Event.AT_TARGET = 2;
      Event.BUBBLING_PHASE = 3;
      legacyCC.Event = Event;

      var SystemEventType; exports('en', SystemEventType);
      (function (SystemEventType) {
        SystemEventType["TOUCH_START"] = "touch-start";
        SystemEventType["TOUCH_MOVE"] = "touch-move";
        SystemEventType["TOUCH_END"] = "touch-end";
        SystemEventType["TOUCH_CANCEL"] = "touch-cancel";
        SystemEventType["MOUSE_DOWN"] = "mouse-down";
        SystemEventType["MOUSE_MOVE"] = "mouse-move";
        SystemEventType["MOUSE_UP"] = "mouse-up";
        SystemEventType["MOUSE_WHEEL"] = "mouse-wheel";
        SystemEventType["MOUSE_ENTER"] = "mouse-enter";
        SystemEventType["MOUSE_LEAVE"] = "mouse-leave";
        SystemEventType["KEY_DOWN"] = "keydown";
        SystemEventType["KEY_UP"] = "keyup";
        SystemEventType["DEVICEMOTION"] = "devicemotion";
        SystemEventType["TRANSFORM_CHANGED"] = "transform-changed";
        SystemEventType["SCENE_CHANGED_FOR_PERSISTS"] = "scene-changed-for-persists";
        SystemEventType["SIZE_CHANGED"] = "size-changed";
        SystemEventType["ANCHOR_CHANGED"] = "anchor-changed";
        SystemEventType["COLOR_CHANGED"] = "color-changed";
        SystemEventType["CHILD_ADDED"] = "child-added";
        SystemEventType["CHILD_REMOVED"] = "child-removed";
        SystemEventType["PARENT_CHANGED"] = "parent-changed";
        SystemEventType["NODE_DESTROYED"] = "node-destroyed";
        SystemEventType["LAYER_CHANGED"] = "layer-changed";
        SystemEventType["SIBLING_ORDER_CHANGED"] = "sibling-order-changed";
      })(SystemEventType || (exports('en', SystemEventType = {})));
      var InputEventType;
      (function (InputEventType) {
        InputEventType["TOUCH_START"] = "touch-start";
        InputEventType["TOUCH_MOVE"] = "touch-move";
        InputEventType["TOUCH_END"] = "touch-end";
        InputEventType["TOUCH_CANCEL"] = "touch-cancel";
        InputEventType["MOUSE_DOWN"] = "mouse-down";
        InputEventType["MOUSE_MOVE"] = "mouse-move";
        InputEventType["MOUSE_UP"] = "mouse-up";
        InputEventType["MOUSE_WHEEL"] = "mouse-wheel";
        InputEventType["KEY_DOWN"] = "keydown";
        InputEventType["KEY_PRESSING"] = "key-pressing";
        InputEventType["KEY_UP"] = "keyup";
        InputEventType["DEVICEMOTION"] = "devicemotion";
        InputEventType["GAMEPAD_INPUT"] = "gamepad-input";
        InputEventType["GAMEPAD_CHANGE"] = "gamepad-change";
        InputEventType["HANDLE_INPUT"] = "handle-input";
        InputEventType["HANDLE_POSE_INPUT"] = "handle-pose-input";
        InputEventType["HMD_POSE_INPUT"] = "hmd-pose-input";
        InputEventType["HANDHELD_POSE_INPUT"] = "handheld-pose-input";
      })(InputEventType || (InputEventType = {}));
      legacyCC.SystemEventType = SystemEventType;

      var EventAcceleration = exports('ep', function (_Event) {
        _inheritsLoose(EventAcceleration, _Event);
        function EventAcceleration(acc, bubbles) {
          var _this;
          _this = _Event.call(this, SystemEventType.DEVICEMOTION, bubbles) || this;
          _this.acc = void 0;
          _this.acc = acc;
          return _this;
        }
        return EventAcceleration;
      }(Event));
      Event.EventAcceleration = EventAcceleration;

      var EventKeyboard = exports('eq', function (_Event) {
        _inheritsLoose(EventKeyboard, _Event);
        function EventKeyboard(keyCode, eventType, bubbles) {
          var _this;
          if (typeof eventType === 'boolean') {
            var _isPressed = eventType;
            eventType = _isPressed ? SystemEventType.KEY_DOWN : SystemEventType.KEY_UP;
          }
          _this = _Event.call(this, eventType, bubbles) || this;
          _this.windowId = void 0;
          _this.keyCode = void 0;
          _this.rawEvent = void 0;
          _this._isPressed = void 0;
          _this._isPressed = eventType !== SystemEventType.KEY_UP;
          if (typeof keyCode === 'number') {
            _this.keyCode = keyCode;
          } else {
            _this.keyCode = keyCode.keyCode;
            _this.rawEvent = keyCode;
          }
          _this.windowId = 0;
          return _this;
        }
        _createClass(EventKeyboard, [{
          key: "isPressed",
          get: function get() {
            return this._isPressed;
          }
        }]);
        return EventKeyboard;
      }(Event));
      Event.EventKeyboard = EventKeyboard;

      var EventMouse = exports('er', function (_Event) {
        _inheritsLoose(EventMouse, _Event);
        function EventMouse(eventType, bubbles, prevLoc, windowId) {
          var _this;
          _this = _Event.call(this, eventType, bubbles) || this;
          _this.movementX = 0;
          _this.movementY = 0;
          _this.windowId = 0;
          _this.preventSwallow = false;
          _this._eventType = void 0;
          _this._button = EventMouse.BUTTON_MISSING;
          _this._x = 0;
          _this._y = 0;
          _this._prevX = 0;
          _this._prevY = 0;
          _this._scrollX = 0;
          _this._scrollY = 0;
          _this._eventType = eventType;
          if (prevLoc) {
            _this._prevX = prevLoc.x;
            _this._prevY = prevLoc.y;
          }
          _this.windowId = windowId !== null && windowId !== void 0 ? windowId : _this.windowId;
          return _this;
        }
        var _proto = EventMouse.prototype;
        _proto.setScrollData = function setScrollData(scrollX, scrollY) {
          this._scrollX = scrollX;
          this._scrollY = scrollY;
        };
        _proto.getScrollX = function getScrollX() {
          return this._scrollX;
        };
        _proto.getScrollY = function getScrollY() {
          return this._scrollY;
        };
        _proto.setLocation = function setLocation(x, y) {
          this._x = x;
          this._y = y;
        };
        _proto.getLocation = function getLocation(out) {
          if (!out) {
            out = new Vec2();
          }
          Vec2.set(out, this._x, this._y);
          return out;
        };
        _proto.getLocationInView = function getLocationInView(out) {
          if (!out) {
            out = new Vec2();
          }
          Vec2.set(out, this._x, legacyCC.view._designResolutionSize.height - this._y);
          return out;
        };
        _proto.getUILocation = function getUILocation(out) {
          if (!out) {
            out = new Vec2();
          }
          Vec2.set(out, this._x, this._y);
          legacyCC.view._convertToUISpace(out);
          return out;
        };
        _proto.getPreviousLocation = function getPreviousLocation(out) {
          if (!out) {
            out = new Vec2();
          }
          Vec2.set(out, this._prevX, this._prevY);
          return out;
        };
        _proto.getUIPreviousLocation = function getUIPreviousLocation(out) {
          if (!out) {
            out = new Vec2();
          }
          Vec2.set(out, this._prevX, this._prevY);
          legacyCC.view._convertToUISpace(out);
          return out;
        };
        _proto.getDelta = function getDelta(out) {
          if (!out) {
            out = new Vec2();
          }
          Vec2.set(out, this._x - this._prevX, this._y - this._prevY);
          return out;
        };
        _proto.getDeltaX = function getDeltaX() {
          return this._x - this._prevX;
        };
        _proto.getDeltaY = function getDeltaY() {
          return this._y - this._prevY;
        };
        _proto.getUIDelta = function getUIDelta(out) {
          if (!out) {
            out = new Vec2();
          }
          Vec2.set(out, (this._x - this._prevX) / legacyCC.view.getScaleX(), (this._y - this._prevY) / legacyCC.view.getScaleY());
          return out;
        };
        _proto.getUIDeltaX = function getUIDeltaX() {
          return (this._x - this._prevX) / legacyCC.view.getScaleX();
        };
        _proto.getUIDeltaY = function getUIDeltaY() {
          return (this._y - this._prevY) / legacyCC.view.getScaleY();
        };
        _proto.setButton = function setButton(button) {
          this._button = button;
        };
        _proto.getButton = function getButton() {
          return this._button;
        };
        _proto.getLocationX = function getLocationX() {
          return this._x;
        };
        _proto.getLocationY = function getLocationY() {
          return this._y;
        };
        _proto.getUILocationX = function getUILocationX() {
          var viewport = legacyCC.view.getViewportRect();
          return (this._x - viewport.x) / legacyCC.view.getScaleX();
        };
        _proto.getUILocationY = function getUILocationY() {
          var viewport = legacyCC.view.getViewportRect();
          return (this._y - viewport.y) / legacyCC.view.getScaleY();
        };
        _createClass(EventMouse, [{
          key: "eventType",
          get: function get() {
            return this._eventType;
          }
        }]);
        return EventMouse;
      }(Event));
      EventMouse.BUTTON_MISSING = -1;
      EventMouse.BUTTON_LEFT = 0;
      EventMouse.BUTTON_RIGHT = 2;
      EventMouse.BUTTON_MIDDLE = 1;
      EventMouse.BUTTON_4 = 3;
      EventMouse.BUTTON_5 = 4;
      EventMouse.BUTTON_6 = 5;
      EventMouse.BUTTON_7 = 6;
      EventMouse.BUTTON_8 = 7;
      Event.EventMouse = EventMouse;

      var _vec2$1 = new Vec2();
      var EventTouch = exports('es', function (_Event) {
        _inheritsLoose(EventTouch, _Event);
        function EventTouch(changedTouches, bubbles, eventType, touches) {
          var _this;
          if (touches === void 0) {
            touches = [];
          }
          _this = _Event.call(this, eventType, bubbles) || this;
          _this.touch = null;
          _this.simulate = false;
          _this.windowId = 0;
          _this.preventSwallow = false;
          _this._eventCode = void 0;
          _this._touches = void 0;
          _this._allTouches = void 0;
          _this._eventCode = eventType;
          _this._touches = changedTouches || [];
          _this._allTouches = touches;
          return _this;
        }
        var _proto = EventTouch.prototype;
        _proto.getEventCode = function getEventCode() {
          return this._eventCode;
        };
        _proto.getTouches = function getTouches() {
          return this._touches;
        };
        _proto.getAllTouches = function getAllTouches() {
          return this._allTouches;
        };
        _proto.setLocation = function setLocation(x, y) {
          if (this.touch) {
            this.touch.setTouchInfo(this.touch.getID(), x, y);
          }
        };
        _proto.getLocation = function getLocation(out) {
          return this.touch ? this.touch.getLocation(out) : new Vec2();
        };
        _proto.getUILocation = function getUILocation(out) {
          return this.touch ? this.touch.getUILocation(out) : new Vec2();
        };
        _proto.getLocationInView = function getLocationInView(out) {
          return this.touch ? this.touch.getLocationInView(out) : new Vec2();
        };
        _proto.getPreviousLocation = function getPreviousLocation(out) {
          return this.touch ? this.touch.getPreviousLocation(out) : new Vec2();
        };
        _proto.getStartLocation = function getStartLocation(out) {
          return this.touch ? this.touch.getStartLocation(out) : new Vec2();
        };
        _proto.getUIStartLocation = function getUIStartLocation(out) {
          return this.touch ? this.touch.getUIStartLocation(out) : new Vec2();
        };
        _proto.getID = function getID() {
          return this.touch ? this.touch.getID() : null;
        };
        _proto.getDelta = function getDelta(out) {
          return this.touch ? this.touch.getDelta(out) : new Vec2();
        };
        _proto.getUIDelta = function getUIDelta(out) {
          return this.touch ? this.touch.getUIDelta(out) : new Vec2();
        };
        _proto.getDeltaX = function getDeltaX() {
          return this.touch ? this.touch.getDelta(_vec2$1).x : 0;
        };
        _proto.getDeltaY = function getDeltaY() {
          return this.touch ? this.touch.getDelta(_vec2$1).y : 0;
        };
        _proto.getLocationX = function getLocationX() {
          return this.touch ? this.touch.getLocationX() : 0;
        };
        _proto.getLocationY = function getLocationY() {
          return this.touch ? this.touch.getLocationY() : 0;
        };
        return EventTouch;
      }(Event));
      EventTouch.MAX_TOUCHES = 5;
      Event.EventTouch = EventTouch;

      var EventGamepad = exports('et', function (_Event) {
        _inheritsLoose(EventGamepad, _Event);
        function EventGamepad(type, gamepad) {
          var _this;
          _this = _Event.call(this, type, false) || this;
          _this.gamepad = void 0;
          _this.gamepad = gamepad;
          return _this;
        }
        return EventGamepad;
      }(Event));

      var EventHandle = exports('eu', function (_Event) {
        _inheritsLoose(EventHandle, _Event);
        function EventHandle(eventType, handleInputDevice) {
          var _this;
          _this = _Event.call(this, eventType, false) || this;
          _this.handleInputDevice = void 0;
          _this.handleInputDevice = handleInputDevice;
          return _this;
        }
        return EventHandle;
      }(Event));

      var EventHMD = exports('ev', function (_Event) {
        _inheritsLoose(EventHMD, _Event);
        function EventHMD(eventType, hmdInputDevice) {
          var _this;
          _this = _Event.call(this, eventType, false) || this;
          _this.hmdInputDevice = void 0;
          _this.hmdInputDevice = hmdInputDevice;
          return _this;
        }
        return EventHMD;
      }(Event));

      var EventHandheld = exports('ew', function (_Event) {
        _inheritsLoose(EventHandheld, _Event);
        function EventHandheld(eventType, handheldInputDevice) {
          var _this;
          _this = _Event.call(this, eventType, false) || this;
          _this.handheldInputDevice = void 0;
          _this.handheldInputDevice = handheldInputDevice;
          return _this;
        }
        return EventHandheld;
      }(Event));

      var Acceleration = exports('ex', function Acceleration(x, y, z, timestamp) {
        if (x === void 0) {
          x = 0;
        }
        if (y === void 0) {
          y = 0;
        }
        if (z === void 0) {
          z = 0;
        }
        if (timestamp === void 0) {
          timestamp = 0;
        }
        this.x = void 0;
        this.y = void 0;
        this.z = void 0;
        this.timestamp = void 0;
        this.x = x;
        this.y = y;
        this.z = z;
        this.timestamp = timestamp;
      });

      var KeyCode; exports('ey', KeyCode);
      (function (KeyCode) {
        KeyCode[KeyCode["NONE"] = 0] = "NONE";
        KeyCode[KeyCode["MOBILE_BACK"] = 6] = "MOBILE_BACK";
        KeyCode[KeyCode["BACKSPACE"] = 8] = "BACKSPACE";
        KeyCode[KeyCode["TAB"] = 9] = "TAB";
        KeyCode[KeyCode["ENTER"] = 13] = "ENTER";
        KeyCode[KeyCode["SHIFT_LEFT"] = 16] = "SHIFT_LEFT";
        KeyCode[KeyCode["CTRL_LEFT"] = 17] = "CTRL_LEFT";
        KeyCode[KeyCode["ALT_LEFT"] = 18] = "ALT_LEFT";
        KeyCode[KeyCode["PAUSE"] = 19] = "PAUSE";
        KeyCode[KeyCode["CAPS_LOCK"] = 20] = "CAPS_LOCK";
        KeyCode[KeyCode["ESCAPE"] = 27] = "ESCAPE";
        KeyCode[KeyCode["SPACE"] = 32] = "SPACE";
        KeyCode[KeyCode["PAGE_UP"] = 33] = "PAGE_UP";
        KeyCode[KeyCode["PAGE_DOWN"] = 34] = "PAGE_DOWN";
        KeyCode[KeyCode["END"] = 35] = "END";
        KeyCode[KeyCode["HOME"] = 36] = "HOME";
        KeyCode[KeyCode["ARROW_LEFT"] = 37] = "ARROW_LEFT";
        KeyCode[KeyCode["ARROW_UP"] = 38] = "ARROW_UP";
        KeyCode[KeyCode["ARROW_RIGHT"] = 39] = "ARROW_RIGHT";
        KeyCode[KeyCode["ARROW_DOWN"] = 40] = "ARROW_DOWN";
        KeyCode[KeyCode["INSERT"] = 45] = "INSERT";
        KeyCode[KeyCode["DELETE"] = 46] = "DELETE";
        KeyCode[KeyCode["DIGIT_0"] = 48] = "DIGIT_0";
        KeyCode[KeyCode["DIGIT_1"] = 49] = "DIGIT_1";
        KeyCode[KeyCode["DIGIT_2"] = 50] = "DIGIT_2";
        KeyCode[KeyCode["DIGIT_3"] = 51] = "DIGIT_3";
        KeyCode[KeyCode["DIGIT_4"] = 52] = "DIGIT_4";
        KeyCode[KeyCode["DIGIT_5"] = 53] = "DIGIT_5";
        KeyCode[KeyCode["DIGIT_6"] = 54] = "DIGIT_6";
        KeyCode[KeyCode["DIGIT_7"] = 55] = "DIGIT_7";
        KeyCode[KeyCode["DIGIT_8"] = 56] = "DIGIT_8";
        KeyCode[KeyCode["DIGIT_9"] = 57] = "DIGIT_9";
        KeyCode[KeyCode["KEY_A"] = 65] = "KEY_A";
        KeyCode[KeyCode["KEY_B"] = 66] = "KEY_B";
        KeyCode[KeyCode["KEY_C"] = 67] = "KEY_C";
        KeyCode[KeyCode["KEY_D"] = 68] = "KEY_D";
        KeyCode[KeyCode["KEY_E"] = 69] = "KEY_E";
        KeyCode[KeyCode["KEY_F"] = 70] = "KEY_F";
        KeyCode[KeyCode["KEY_G"] = 71] = "KEY_G";
        KeyCode[KeyCode["KEY_H"] = 72] = "KEY_H";
        KeyCode[KeyCode["KEY_I"] = 73] = "KEY_I";
        KeyCode[KeyCode["KEY_J"] = 74] = "KEY_J";
        KeyCode[KeyCode["KEY_K"] = 75] = "KEY_K";
        KeyCode[KeyCode["KEY_L"] = 76] = "KEY_L";
        KeyCode[KeyCode["KEY_M"] = 77] = "KEY_M";
        KeyCode[KeyCode["KEY_N"] = 78] = "KEY_N";
        KeyCode[KeyCode["KEY_O"] = 79] = "KEY_O";
        KeyCode[KeyCode["KEY_P"] = 80] = "KEY_P";
        KeyCode[KeyCode["KEY_Q"] = 81] = "KEY_Q";
        KeyCode[KeyCode["KEY_R"] = 82] = "KEY_R";
        KeyCode[KeyCode["KEY_S"] = 83] = "KEY_S";
        KeyCode[KeyCode["KEY_T"] = 84] = "KEY_T";
        KeyCode[KeyCode["KEY_U"] = 85] = "KEY_U";
        KeyCode[KeyCode["KEY_V"] = 86] = "KEY_V";
        KeyCode[KeyCode["KEY_W"] = 87] = "KEY_W";
        KeyCode[KeyCode["KEY_X"] = 88] = "KEY_X";
        KeyCode[KeyCode["KEY_Y"] = 89] = "KEY_Y";
        KeyCode[KeyCode["KEY_Z"] = 90] = "KEY_Z";
        KeyCode[KeyCode["NUM_0"] = 96] = "NUM_0";
        KeyCode[KeyCode["NUM_1"] = 97] = "NUM_1";
        KeyCode[KeyCode["NUM_2"] = 98] = "NUM_2";
        KeyCode[KeyCode["NUM_3"] = 99] = "NUM_3";
        KeyCode[KeyCode["NUM_4"] = 100] = "NUM_4";
        KeyCode[KeyCode["NUM_5"] = 101] = "NUM_5";
        KeyCode[KeyCode["NUM_6"] = 102] = "NUM_6";
        KeyCode[KeyCode["NUM_7"] = 103] = "NUM_7";
        KeyCode[KeyCode["NUM_8"] = 104] = "NUM_8";
        KeyCode[KeyCode["NUM_9"] = 105] = "NUM_9";
        KeyCode[KeyCode["NUM_MULTIPLY"] = 106] = "NUM_MULTIPLY";
        KeyCode[KeyCode["NUM_PLUS"] = 107] = "NUM_PLUS";
        KeyCode[KeyCode["NUM_SUBTRACT"] = 109] = "NUM_SUBTRACT";
        KeyCode[KeyCode["NUM_DECIMAL"] = 110] = "NUM_DECIMAL";
        KeyCode[KeyCode["NUM_DIVIDE"] = 111] = "NUM_DIVIDE";
        KeyCode[KeyCode["F1"] = 112] = "F1";
        KeyCode[KeyCode["F2"] = 113] = "F2";
        KeyCode[KeyCode["F3"] = 114] = "F3";
        KeyCode[KeyCode["F4"] = 115] = "F4";
        KeyCode[KeyCode["F5"] = 116] = "F5";
        KeyCode[KeyCode["F6"] = 117] = "F6";
        KeyCode[KeyCode["F7"] = 118] = "F7";
        KeyCode[KeyCode["F8"] = 119] = "F8";
        KeyCode[KeyCode["F9"] = 120] = "F9";
        KeyCode[KeyCode["F10"] = 121] = "F10";
        KeyCode[KeyCode["F11"] = 122] = "F11";
        KeyCode[KeyCode["F12"] = 123] = "F12";
        KeyCode[KeyCode["NUM_LOCK"] = 144] = "NUM_LOCK";
        KeyCode[KeyCode["SCROLL_LOCK"] = 145] = "SCROLL_LOCK";
        KeyCode[KeyCode["SEMICOLON"] = 186] = "SEMICOLON";
        KeyCode[KeyCode["EQUAL"] = 187] = "EQUAL";
        KeyCode[KeyCode["COMMA"] = 188] = "COMMA";
        KeyCode[KeyCode["DASH"] = 189] = "DASH";
        KeyCode[KeyCode["PERIOD"] = 190] = "PERIOD";
        KeyCode[KeyCode["SLASH"] = 191] = "SLASH";
        KeyCode[KeyCode["BACK_QUOTE"] = 192] = "BACK_QUOTE";
        KeyCode[KeyCode["BRACKET_LEFT"] = 219] = "BRACKET_LEFT";
        KeyCode[KeyCode["BACKSLASH"] = 220] = "BACKSLASH";
        KeyCode[KeyCode["BRACKET_RIGHT"] = 221] = "BRACKET_RIGHT";
        KeyCode[KeyCode["QUOTE"] = 222] = "QUOTE";
        KeyCode[KeyCode["SHIFT_RIGHT"] = 2000] = "SHIFT_RIGHT";
        KeyCode[KeyCode["CTRL_RIGHT"] = 2001] = "CTRL_RIGHT";
        KeyCode[KeyCode["ALT_RIGHT"] = 2002] = "ALT_RIGHT";
        KeyCode[KeyCode["NUM_ENTER"] = 2003] = "NUM_ENTER";
      })(KeyCode || (exports('ey', KeyCode = {})));

      var _vec2 = new Vec2();
      var Touch = exports('ez', function () {
        function Touch(x, y, id) {
          if (id === void 0) {
            id = 0;
          }
          this._point = new Vec2();
          this._prevPoint = new Vec2();
          this._lastModified = 0;
          this._id = 0;
          this._startPoint = new Vec2();
          this._startPointCaptured = false;
          this.setTouchInfo(id, x, y);
        }
        var _proto = Touch.prototype;
        _proto.getLocation = function getLocation(out) {
          if (!out) {
            out = new Vec2();
          }
          out.set(this._point.x, this._point.y);
          return out;
        };
        _proto.getLocationX = function getLocationX() {
          return this._point.x;
        };
        _proto.getLocationY = function getLocationY() {
          return this._point.y;
        };
        _proto.getUILocation = function getUILocation(out) {
          if (!out) {
            out = new Vec2();
          }
          out.set(this._point.x, this._point.y);
          legacyCC.view._convertToUISpace(out);
          return out;
        };
        _proto.getUILocationX = function getUILocationX() {
          var viewport = legacyCC.view.getViewportRect();
          return (this._point.x - viewport.x) / legacyCC.view.getScaleX();
        };
        _proto.getUILocationY = function getUILocationY() {
          var viewport = legacyCC.view.getViewportRect();
          return (this._point.y - viewport.y) / legacyCC.view.getScaleY();
        };
        _proto.getPreviousLocation = function getPreviousLocation(out) {
          if (!out) {
            out = new Vec2();
          }
          out.set(this._prevPoint.x, this._prevPoint.y);
          return out;
        };
        _proto.getUIPreviousLocation = function getUIPreviousLocation(out) {
          if (!out) {
            out = new Vec2();
          }
          out.set(this._prevPoint.x, this._prevPoint.y);
          legacyCC.view._convertToUISpace(out);
          return out;
        };
        _proto.getStartLocation = function getStartLocation(out) {
          if (!out) {
            out = new Vec2();
          }
          out.set(this._startPoint.x, this._startPoint.y);
          return out;
        };
        _proto.getUIStartLocation = function getUIStartLocation(out) {
          if (!out) {
            out = new Vec2();
          }
          out.set(this._startPoint.x, this._startPoint.y);
          legacyCC.view._convertToUISpace(out);
          return out;
        };
        _proto.getDelta = function getDelta(out) {
          if (!out) {
            out = new Vec2();
          }
          out.set(this._point);
          out.subtract(this._prevPoint);
          return out;
        };
        _proto.getUIDelta = function getUIDelta(out) {
          if (!out) {
            out = new Vec2();
          }
          _vec2.set(this._point);
          _vec2.subtract(this._prevPoint);
          out.set(legacyCC.view.getScaleX(), legacyCC.view.getScaleY());
          Vec2.divide(out, _vec2, out);
          return out;
        };
        _proto.getLocationInView = function getLocationInView(out) {
          if (!out) {
            out = new Vec2();
          }
          out.set(this._point.x, legacyCC.view._designResolutionSize.height - this._point.y);
          return out;
        };
        _proto.getPreviousLocationInView = function getPreviousLocationInView(out) {
          if (!out) {
            out = new Vec2();
          }
          out.set(this._prevPoint.x, legacyCC.view._designResolutionSize.height - this._prevPoint.y);
          return out;
        };
        _proto.getStartLocationInView = function getStartLocationInView(out) {
          if (!out) {
            out = new Vec2();
          }
          out.set(this._startPoint.x, legacyCC.view._designResolutionSize.height - this._startPoint.y);
          return out;
        };
        _proto.getID = function getID() {
          return this._id;
        };
        _proto.setTouchInfo = function setTouchInfo(id, x, y) {
          if (id === void 0) {
            id = 0;
          }
          this._prevPoint = this._point;
          this._point = new Vec2(x || 0, y || 0);
          this._id = id;
          if (!this._startPointCaptured) {
            this._startPoint = new Vec2(this._point);
            this._startPointCaptured = true;
          }
        };
        _proto.setPoint = function setPoint(x, y) {
          if (typeof x === 'object') {
            this._point.x = x.x;
            this._point.y = x.y;
          } else {
            this._point.x = x || 0;
            this._point.y = y || 0;
          }
          this._lastModified = legacyCC.game.frameStartTime;
        };
        _proto.setPrevPoint = function setPrevPoint(x, y) {
          if (typeof x === 'object') {
            this._prevPoint = new Vec2(x.x, x.y);
          } else {
            this._prevPoint = new Vec2(x || 0, y || 0);
          }
          this._lastModified = legacyCC.game.frameStartTime;
        };
        _createClass(Touch, [{
          key: "lastModified",
          get: function get() {
            return this._lastModified;
          }
        }]);
        return Touch;
      }());
      legacyCC.Touch = Touch;

      var AccelerometerInputSource = function () {
        function AccelerometerInputSource() {
          this._intervalInMileSeconds = 200;
          this._accelTimer = 0;
          this._eventTarget = new EventTarget();
          this._deviceEventName = void 0;
          this._globalEventClass = void 0;
          this._didAccelerateFunc = void 0;
          this._globalEventClass = window.DeviceMotionEvent || window.DeviceOrientationEvent;
          if (systemInfo.browserType === BrowserType.MOBILE_QQ) {
            this._globalEventClass = window.DeviceOrientationEvent;
          }
          this._deviceEventName = this._globalEventClass === window.DeviceMotionEvent ? 'devicemotion' : 'deviceorientation';
          this._didAccelerateFunc = this._didAccelerate.bind(this);
        }
        var _proto = AccelerometerInputSource.prototype;
        _proto._registerEvent = function _registerEvent() {
          this._accelTimer = performance.now();
          window.addEventListener(this._deviceEventName, this._didAccelerateFunc, false);
        };
        _proto._unregisterEvent = function _unregisterEvent() {
          this._accelTimer = 0;
          window.removeEventListener(this._deviceEventName, this._didAccelerateFunc, false);
        };
        _proto._didAccelerate = function _didAccelerate(event) {
          var now = performance.now();
          if (now - this._accelTimer < this._intervalInMileSeconds) {
            return;
          }
          this._accelTimer = now;
          var x = 0;
          var y = 0;
          var z = 0;
          if (this._globalEventClass === window.DeviceMotionEvent) {
            var deviceMotionEvent = event;
            var _eventAcceleration = deviceMotionEvent.accelerationIncludingGravity;
            x = ((_eventAcceleration === null || _eventAcceleration === void 0 ? void 0 : _eventAcceleration.x) || 0) * 0.1;
            y = ((_eventAcceleration === null || _eventAcceleration === void 0 ? void 0 : _eventAcceleration.y) || 0) * 0.1;
            z = ((_eventAcceleration === null || _eventAcceleration === void 0 ? void 0 : _eventAcceleration.z) || 0) * 0.1;
          } else {
            var deviceOrientationEvent = event;
            x = (deviceOrientationEvent.gamma || 0) / 90 * 0.981;
            y = -((deviceOrientationEvent.beta || 0) / 90) * 0.981;
            z = (deviceOrientationEvent.alpha || 0) / 90 * 0.981;
          }
          if (screenAdapter.isFrameRotated) {
            var tmp = x;
            x = -y;
            y = tmp;
          }
          var LANDSCAPE_LEFT = -90;
          var PORTRAIT_UPSIDE_DOWN = 180;
          var LANDSCAPE_RIGHT = 90;
          var tmpX = x;
          if (window.orientation === LANDSCAPE_RIGHT) {
            x = -y;
            y = tmpX;
          } else if (window.orientation === LANDSCAPE_LEFT) {
            x = y;
            y = -tmpX;
          } else if (window.orientation === PORTRAIT_UPSIDE_DOWN) {
            x = -x;
            y = -y;
          }
          if (systemInfo.os === OS.ANDROID && systemInfo.browserType !== BrowserType.MOBILE_QQ) {
            x = -x;
            y = -y;
          }
          var timestamp = performance.now();
          var acceleration = new Acceleration(x, y, z, timestamp);
          var eventAcceleration = new EventAcceleration(acceleration);
          this._eventTarget.emit(InputEventType.DEVICEMOTION, eventAcceleration);
        };
        _proto.start = function start() {
          var _this = this;
          if (window.DeviceMotionEvent && typeof DeviceMotionEvent.requestPermission === 'function') {
            DeviceMotionEvent.requestPermission().then(function (response) {
              if (response === 'granted') {
                _this._registerEvent();
              }
            })["catch"](function (e) {});
          } else {
            this._registerEvent();
          }
        };
        _proto.stop = function stop() {
          this._unregisterEvent();
        };
        _proto.setInterval = function setInterval(intervalInMileSeconds) {
          this._intervalInMileSeconds = intervalInMileSeconds;
        };
        _proto.on = function on(eventType, callback, target) {
          this._eventTarget.on(eventType, callback, target);
        };
        return AccelerometerInputSource;
      }();

      var InputSource = function InputSource() {};
      var InputSourceAxis1D = function (_InputSource) {
        _inheritsLoose(InputSourceAxis1D, _InputSource);
        function InputSourceAxis1D() {
          return _InputSource.apply(this, arguments) || this;
        }
        var _proto = InputSourceAxis1D.prototype;
        _proto.getValue = function getValue() {
          throw new Error('Method not implemented.');
        };
        return InputSourceAxis1D;
      }(InputSource);
      var InputSourceAxis2D = function (_InputSource2) {
        _inheritsLoose(InputSourceAxis2D, _InputSource2);
        function InputSourceAxis2D() {
          return _InputSource2.apply(this, arguments) || this;
        }
        var _proto2 = InputSourceAxis2D.prototype;
        _proto2.getValue = function getValue() {
          throw new Error('Method not implemented.');
        };
        return InputSourceAxis2D;
      }(InputSource);
      var InputSourceAxis3D = function (_InputSource3) {
        _inheritsLoose(InputSourceAxis3D, _InputSource3);
        function InputSourceAxis3D() {
          return _InputSource3.apply(this, arguments) || this;
        }
        var _proto3 = InputSourceAxis3D.prototype;
        _proto3.getValue = function getValue() {
          throw new Error('Method not implemented.');
        };
        return InputSourceAxis3D;
      }(InputSource);
      var InputSourceQuat = function (_InputSource4) {
        _inheritsLoose(InputSourceQuat, _InputSource4);
        function InputSourceQuat() {
          return _InputSource4.apply(this, arguments) || this;
        }
        var _proto4 = InputSourceQuat.prototype;
        _proto4.getValue = function getValue() {
          throw new Error('Method not implemented.');
        };
        return InputSourceQuat;
      }(InputSource);
      var CompositeInputSourceAxis1D = function (_InputSourceAxis1D) {
        _inheritsLoose(CompositeInputSourceAxis1D, _InputSourceAxis1D);
        function CompositeInputSourceAxis1D(options) {
          var _this;
          _this = _InputSourceAxis1D.call(this) || this;
          _this.positive = void 0;
          _this.negative = void 0;
          _this.positive = options.positive;
          _this.negative = options.negative;
          return _this;
        }
        var _proto5 = CompositeInputSourceAxis1D.prototype;
        _proto5.getValue = function getValue() {
          var positiveValue = this.positive.getValue();
          var negativeValue = this.negative.getValue();
          if (Math.abs(positiveValue) > Math.abs(negativeValue)) {
            return positiveValue;
          }
          return -negativeValue;
        };
        return CompositeInputSourceAxis1D;
      }(InputSourceAxis1D);
      var CompositeInputSourceAxis2D = function (_InputSourceAxis2D) {
        _inheritsLoose(CompositeInputSourceAxis2D, _InputSourceAxis2D);
        function CompositeInputSourceAxis2D(options) {
          var _this2;
          _this2 = _InputSourceAxis2D.call(this) || this;
          _this2.up = void 0;
          _this2.down = void 0;
          _this2.left = void 0;
          _this2.right = void 0;
          _this2.xAxis = void 0;
          _this2.yAxis = void 0;
          _this2.up = options.up;
          _this2.down = options.down;
          _this2.left = options.left;
          _this2.right = options.right;
          _this2.xAxis = new CompositeInputSourceAxis1D({
            positive: _this2.right,
            negative: _this2.left
          });
          _this2.yAxis = new CompositeInputSourceAxis1D({
            positive: _this2.up,
            negative: _this2.down
          });
          return _this2;
        }
        var _proto6 = CompositeInputSourceAxis2D.prototype;
        _proto6.getValue = function getValue() {
          return new Vec2(this.xAxis.getValue(), this.yAxis.getValue());
        };
        return CompositeInputSourceAxis2D;
      }(InputSourceAxis2D);
      (function (_InputSourceAxis3D) {
        _inheritsLoose(CompositeInputSourceAxis3D, _InputSourceAxis3D);
        function CompositeInputSourceAxis3D(options) {
          var _this3;
          _this3 = _InputSourceAxis3D.call(this) || this;
          _this3.up = void 0;
          _this3.down = void 0;
          _this3.left = void 0;
          _this3.right = void 0;
          _this3.forward = void 0;
          _this3.backward = void 0;
          _this3.xAxis = void 0;
          _this3.yAxis = void 0;
          _this3.zAxis = void 0;
          _this3.up = options.up;
          _this3.down = options.down;
          _this3.left = options.left;
          _this3.right = options.right;
          _this3.forward = options.forward;
          _this3.backward = options.backward;
          _this3.xAxis = new CompositeInputSourceAxis1D({
            positive: _this3.right,
            negative: _this3.left
          });
          _this3.yAxis = new CompositeInputSourceAxis1D({
            positive: _this3.up,
            negative: _this3.down
          });
          _this3.zAxis = new CompositeInputSourceAxis1D({
            positive: _this3.forward,
            negative: _this3.backward
          });
          return _this3;
        }
        var _proto7 = CompositeInputSourceAxis3D.prototype;
        _proto7.getValue = function getValue() {
          return new Vec3(this.xAxis.getValue(), this.yAxis.getValue(), this.zAxis.getValue());
        };
        return CompositeInputSourceAxis3D;
      })(InputSourceAxis3D);
      var InputSourceButton = function (_InputSourceAxis1D2) {
        _inheritsLoose(InputSourceButton, _InputSourceAxis1D2);
        function InputSourceButton() {
          return _InputSourceAxis1D2.apply(this, arguments) || this;
        }
        var _proto8 = InputSourceButton.prototype;
        _proto8.getValue = function getValue() {
          return _InputSourceAxis1D2.prototype.getValue.call(this);
        };
        return InputSourceButton;
      }(InputSourceAxis1D);
      var InputSourceDpad = function (_CompositeInputSource) {
        _inheritsLoose(InputSourceDpad, _CompositeInputSource);
        function InputSourceDpad() {
          return _CompositeInputSource.apply(this, arguments) || this;
        }
        return InputSourceDpad;
      }(CompositeInputSourceAxis2D);
      var InputSourceStick = function (_CompositeInputSource2) {
        _inheritsLoose(InputSourceStick, _CompositeInputSource2);
        function InputSourceStick() {
          return _CompositeInputSource2.apply(this, arguments) || this;
        }
        return InputSourceStick;
      }(CompositeInputSourceAxis2D);
      var InputSourceOrientation = function (_InputSourceQuat) {
        _inheritsLoose(InputSourceOrientation, _InputSourceQuat);
        function InputSourceOrientation() {
          return _InputSourceQuat.apply(this, arguments) || this;
        }
        var _proto9 = InputSourceOrientation.prototype;
        _proto9.getValue = function getValue() {
          return _InputSourceQuat.prototype.getValue.call(this);
        };
        return InputSourceOrientation;
      }(InputSourceQuat);
      var InputSourcePosition = function (_InputSourceAxis3D2) {
        _inheritsLoose(InputSourcePosition, _InputSourceAxis3D2);
        function InputSourcePosition() {
          return _InputSourceAxis3D2.apply(this, arguments) || this;
        }
        var _proto10 = InputSourcePosition.prototype;
        _proto10.getValue = function getValue() {
          return _InputSourceAxis3D2.prototype.getValue.call(this);
        };
        return InputSourcePosition;
      }(InputSourceAxis3D);

      var BUTTON_SOUTH = 0;
      var BUTTON_EAST = 1;
      var BUTTON_WEST = 2;
      var BUTTON_NORTH = 3;
      var BUTTON_L1 = 4;
      var BUTTON_R1 = 5;
      var BUTTON_L2 = 6;
      var BUTTON_R2 = 7;
      var BUTTON_SHARE = 8;
      var BUTTON_OPTIONS = 9;
      var BUTTON_L3 = 10;
      var BUTTON_R3 = 11;
      var BUTTON_DPAD_UP = 12;
      var BUTTON_DPAD_DOWN = 13;
      var BUTTON_DPAD_LEFT = 14;
      var BUTTON_DPAD_RIGHT = 15;
      var AXIS_LEFT_STICK_X = 0;
      var AXIS_LEFT_STICK_Y = 1;
      var AXIS_RIGHT_STICK_X = 2;
      var AXIS_RIGHT_STICK_Y = 3;
      var XR_TRIGGER = 0;
      var XR_GRIP = 1;
      var XR_TOUCHPAD = 2;
      var XR_STICK = 3;
      var XR_BUTTON_1 = 4;
      var XR_BUTTON_2 = 5;
      var XR_AXIS_TOUCHPAD_X = 0;
      var XR_AXIS_TOUCHPAD_Y = 1;
      var XR_AXIS_STICK_X = 2;
      var XR_AXIS_STICK_Y = 3;
      var EPSILON$2 = 0.01;
      var XRLeftHandedness = 'left';
      var XRRightHandedness = 'right';
      var devicesTmp = [];
      var Pose$2;
      (function (Pose) {
        Pose[Pose["HAND_LEFT"] = 1] = "HAND_LEFT";
        Pose[Pose["HAND_RIGHT"] = 4] = "HAND_RIGHT";
        Pose[Pose["AIM_LEFT"] = 2] = "AIM_LEFT";
        Pose[Pose["AIM_RIGHT"] = 5] = "AIM_RIGHT";
      })(Pose$2 || (Pose$2 = {}));
      var GamepadInputDevice = function () {
        function GamepadInputDevice(deviceId) {
          var _this$_webPoseState;
          this._buttonNorth = void 0;
          this._buttonEast = void 0;
          this._buttonWest = void 0;
          this._buttonSouth = void 0;
          this._buttonL1 = void 0;
          this._buttonL2 = void 0;
          this._buttonL3 = void 0;
          this._buttonR1 = void 0;
          this._buttonR2 = void 0;
          this._buttonR3 = void 0;
          this._buttonShare = void 0;
          this._buttonOptions = void 0;
          this._dpad = void 0;
          this._leftStick = void 0;
          this._rightStick = void 0;
          this._buttonStart = void 0;
          this._gripLeft = void 0;
          this._gripRight = void 0;
          this._handLeftPosition = void 0;
          this._handLeftOrientation = void 0;
          this._handRightPosition = void 0;
          this._handRightOrientation = void 0;
          this._aimLeftPosition = void 0;
          this._aimLeftOrientation = void 0;
          this._aimRightPosition = void 0;
          this._aimRightOrientation = void 0;
          this._deviceId = -1;
          this._connected = false;
          this._webPoseState = (_this$_webPoseState = {}, _this$_webPoseState[Pose$2.HAND_LEFT] = {
            position: Vec3.ZERO,
            orientation: Quat.IDENTITY
          }, _this$_webPoseState[Pose$2.HAND_RIGHT] = {
            position: Vec3.ZERO,
            orientation: Quat.IDENTITY
          }, _this$_webPoseState[Pose$2.AIM_LEFT] = {
            position: Vec3.ZERO,
            orientation: Quat.IDENTITY
          }, _this$_webPoseState[Pose$2.AIM_RIGHT] = {
            position: Vec3.ZERO,
            orientation: Quat.IDENTITY
          }, _this$_webPoseState);
          this._deviceId = deviceId;
          this._initInputSource();
        }
        GamepadInputDevice._init = function _init() {
          if (!systemInfo.hasFeature(Feature$1.EVENT_GAMEPAD)) {
            return;
          }
          GamepadInputDevice._registerEvent();
        };
        GamepadInputDevice._on = function _on(eventType, cb, target) {
          GamepadInputDevice._eventTarget.on(eventType, cb, target);
        };
        GamepadInputDevice._removeInputDevice = function _removeInputDevice(id) {
          var removeIndex = GamepadInputDevice.all.findIndex(function (device) {
            return device.deviceId === id;
          });
          if (removeIndex === -1) {
            return;
          }
          fastRemoveAt$2(GamepadInputDevice.all, removeIndex);
        };
        GamepadInputDevice._getOrCreateInputDevice = function _getOrCreateInputDevice(id, connected) {
          var device = GamepadInputDevice.all.find(function (device) {
            return device.deviceId === id;
          });
          if (!device) {
            device = new GamepadInputDevice(id);
            GamepadInputDevice.all.push(device);
          }
          device._connected = connected;
          return device;
        };
        GamepadInputDevice._ensureDirectorDefined = function _ensureDirectorDefined(callback) {
          GamepadInputDevice._intervalId = setInterval(function () {
            if (legacyCC.director && legacyCC.Director) {
              clearInterval(GamepadInputDevice._intervalId);
              GamepadInputDevice._intervalId = -1;
              callback();
            }
          }, 50);
        };
        GamepadInputDevice._updateGamepadCnt = function _updateGamepadCnt() {
          var cnt = 0;
          for (var i = 0, l = GamepadInputDevice._cachedWebGamepads.length; i < l; i++) {
            if (GamepadInputDevice._cachedWebGamepads[i]) cnt++;
          }
          GamepadInputDevice._totalGamepadCnt = cnt;
        };
        GamepadInputDevice._registerEvent = function _registerEvent() {
          GamepadInputDevice._ensureDirectorDefined(function () {
            GamepadInputDevice._cachedWebGamepads = GamepadInputDevice._getWebGamePads();
            GamepadInputDevice._updateGamepadCnt();
            legacyCC.director.on(legacyCC.Director.EVENT_BEGIN_FRAME, GamepadInputDevice._scanGamepads);
          });
          window.addEventListener('gamepadconnected', function (e) {
            GamepadInputDevice._cachedWebGamepads[e.gamepad.index] = e.gamepad;
            GamepadInputDevice._updateGamepadCnt();
            var device = GamepadInputDevice._getOrCreateInputDevice(e.gamepad.index, true);
            GamepadInputDevice._eventTarget.emit(InputEventType.GAMEPAD_CHANGE, new EventGamepad(InputEventType.GAMEPAD_CHANGE, device));
          });
          window.addEventListener('gamepaddisconnected', function (e) {
            GamepadInputDevice._cachedWebGamepads[e.gamepad.index] = null;
            GamepadInputDevice._updateGamepadCnt();
            var device = GamepadInputDevice._getOrCreateInputDevice(e.gamepad.index, false);
            GamepadInputDevice._removeInputDevice(e.gamepad.index);
            GamepadInputDevice._eventTarget.emit(InputEventType.GAMEPAD_CHANGE, new EventGamepad(InputEventType.GAMEPAD_CHANGE, device));
          });
        };
        GamepadInputDevice._scanWebGamepads = function _scanWebGamepads(devices) {
          var allDisconnected = GamepadInputDevice._totalGamepadCnt === 0;
          if (allDisconnected) return;
          var webGamepads = GamepadInputDevice._getWebGamePads();
          if (!webGamepads) {
            return;
          }
          for (var i = 0; i < webGamepads.length; ++i) {
            var webGamepad = webGamepads[i];
            if (!webGamepad) {
              continue;
            }
            var cachedWebGamepad = GamepadInputDevice._cachedWebGamepads[webGamepad.index];
            if (cachedWebGamepad) {
              var device = void 0;
              var cachedButtons = cachedWebGamepad.buttons;
              for (var j = 0; j < cachedButtons.length; ++j) {
                var cachedButton = cachedButtons[j];
                var button = webGamepad.buttons[j];
                if (Math.abs(cachedButton.value - button.value) > EPSILON$2) {
                  device = GamepadInputDevice._getOrCreateInputDevice(webGamepad.index, true);
                  break;
                }
              }
              if (device) {
                devices.push(device);
                continue;
              }
              var cachedAxes = cachedWebGamepad.axes;
              for (var _j = 0; _j < cachedAxes.length; ++_j) {
                var cachedAxisValue = cachedAxes[_j];
                var axisValue = webGamepad.axes[_j];
                if (Math.abs(cachedAxisValue - axisValue) > EPSILON$2) {
                  device = GamepadInputDevice._getOrCreateInputDevice(webGamepad.index, true);
                  break;
                }
              }
              if (device) {
                devices.push(device);
                continue;
              }
            }
          }
          GamepadInputDevice._cachedWebGamepads = webGamepads;
        };
        GamepadInputDevice._scanGamepads = function _scanGamepads() {
          devicesTmp.length = 0;
          GamepadInputDevice._scanWebGamepads(devicesTmp);
          GamepadInputDevice._scanWebXRGamepads(devicesTmp);
          for (var i = 0; i < devicesTmp.length; ++i) {
            var device = devicesTmp[i];
            GamepadInputDevice._eventTarget.emit(InputEventType.GAMEPAD_INPUT, new EventGamepad(InputEventType.GAMEPAD_INPUT, device));
          }
          GamepadInputDevice._scanWebXRGamepadsPose();
        };
        GamepadInputDevice._scanWebXRGamepads = function _scanWebXRGamepads(devices) {
          var _GamepadInputDevice$_, _GamepadInputDevice$_2;
          var webxrGamepadMap = GamepadInputDevice._getWebXRGamepadMap();
          if (!webxrGamepadMap) {
            GamepadInputDevice._cachedWebXRGamepadMap = null;
            if (GamepadInputDevice.xr && GamepadInputDevice.xr._connected) {
              GamepadInputDevice.xr._connected = false;
              GamepadInputDevice._eventTarget.emit(InputEventType.GAMEPAD_CHANGE, new EventGamepad(InputEventType.GAMEPAD_CHANGE, GamepadInputDevice.xr));
              devices.push(GamepadInputDevice.xr);
            }
            return;
          }
          if (!GamepadInputDevice.xr) {
            GamepadInputDevice.xr = new GamepadInputDevice(-1);
          }
          var left = webxrGamepadMap.get(XRLeftHandedness);
          var right = webxrGamepadMap.get(XRRightHandedness);
          if (!left && !right) {
            if (GamepadInputDevice.xr._connected) {
              GamepadInputDevice.xr._connected = false;
              GamepadInputDevice._eventTarget.emit(InputEventType.GAMEPAD_CHANGE, new EventGamepad(InputEventType.GAMEPAD_CHANGE, GamepadInputDevice.xr));
            }
          } else if (!GamepadInputDevice.xr._connected) {
            GamepadInputDevice.xr._connected = true;
            GamepadInputDevice._eventTarget.emit(InputEventType.GAMEPAD_CHANGE, new EventGamepad(InputEventType.GAMEPAD_CHANGE, GamepadInputDevice.xr));
          }
          if (GamepadInputDevice.checkGamepadChanged(left, (_GamepadInputDevice$_ = GamepadInputDevice._cachedWebXRGamepadMap) === null || _GamepadInputDevice$_ === void 0 ? void 0 : _GamepadInputDevice$_.get(XRLeftHandedness))) {
            devices.push(GamepadInputDevice.xr);
          } else if (GamepadInputDevice.checkGamepadChanged(right, (_GamepadInputDevice$_2 = GamepadInputDevice._cachedWebXRGamepadMap) === null || _GamepadInputDevice$_2 === void 0 ? void 0 : _GamepadInputDevice$_2.get(XRRightHandedness))) {
            devices.push(GamepadInputDevice.xr);
          }
          if (!GamepadInputDevice._cachedWebXRGamepadMap) {
            GamepadInputDevice._cachedWebXRGamepadMap = new Map();
          }
          GamepadInputDevice._cachedWebXRGamepadMap.set(XRLeftHandedness, GamepadInputDevice._copyCacheGamepadValue(left));
          GamepadInputDevice._cachedWebXRGamepadMap.set(XRRightHandedness, GamepadInputDevice._copyCacheGamepadValue(right));
        };
        GamepadInputDevice.checkGamepadChanged = function checkGamepadChanged(currGamepad, cachedGamepad) {
          if (!currGamepad && !cachedGamepad) {
            return false;
          } else if (!currGamepad || !cachedGamepad) {
            return true;
          }
          var cachedButtons = cachedGamepad.buttons;
          for (var j = 0; j < cachedButtons.length; ++j) {
            var cachedButton = cachedButtons[j];
            var button = currGamepad.buttons[j];
            if (button.value !== 0 || cachedButton !== 0) {
              return true;
            }
          }
          var cachedAxes = cachedGamepad.axes;
          for (var _j2 = 0; _j2 < cachedAxes.length; ++_j2) {
            var cachedAxisValue = cachedAxes[_j2];
            var axisValue = currGamepad.axes[_j2];
            if (axisValue !== 0 || cachedAxisValue !== 0) {
              return true;
            }
          }
          return false;
        };
        GamepadInputDevice._copyCacheGamepadValue = function _copyCacheGamepadValue(gamepad) {
          if (!gamepad) {
            return undefined;
          }
          var cacheGamepad = {
            buttons: new Array(gamepad.buttons.length),
            axes: new Array(gamepad.axes.length)
          };
          for (var j = 0; j < gamepad.buttons.length; ++j) {
            cacheGamepad.buttons[j] = gamepad.buttons[j].value;
          }
          for (var _j3 = 0; _j3 < gamepad.axes.length; ++_j3) {
            cacheGamepad.axes[_j3] = gamepad.axes[_j3];
          }
          return cacheGamepad;
        };
        GamepadInputDevice._scanWebXRGamepadsPose = function _scanWebXRGamepadsPose() {
          var _globalThis$__globalX;
          var infoList = (_globalThis$__globalX = globalThis.__globalXR) === null || _globalThis$__globalX === void 0 ? void 0 : _globalThis$__globalX.webxrHandlePoseInfos;
          if (!infoList || !GamepadInputDevice.xr) {
            return;
          }
          for (var i = 0; i < infoList.length; ++i) {
            var info = infoList[i];
            GamepadInputDevice.xr._updateWebPoseState(info);
          }
          GamepadInputDevice._eventTarget.emit(InputEventType.HANDLE_POSE_INPUT, new EventGamepad(InputEventType.HANDLE_POSE_INPUT, GamepadInputDevice.xr));
        };
        GamepadInputDevice._getWebXRGamepadMap = function _getWebXRGamepadMap() {
          var _globalThis$__globalX2;
          return (_globalThis$__globalX2 = globalThis.__globalXR) === null || _globalThis$__globalX2 === void 0 ? void 0 : _globalThis$__globalX2.webxrGamepadMap;
        };
        GamepadInputDevice._getWebGamePads = function _getWebGamePads() {
          if (typeof navigator.getGamepads === 'function') {
            return navigator.getGamepads();
          } else if (typeof navigator.webkitGetGamepads === 'function') {
            return navigator.webkitGetGamepads();
          }
          return [];
        };
        GamepadInputDevice._getWebGamepad = function _getWebGamepad(deviceId) {
          var webGamepads = GamepadInputDevice._getWebGamePads();
          for (var i = 0; i < webGamepads.length; ++i) {
            var webGamepad = webGamepads[i];
            if (webGamepad && webGamepad.index === deviceId) {
              return webGamepad;
            }
          }
          return undefined;
        };
        var _proto = GamepadInputDevice.prototype;
        _proto._axisToButtons = function _axisToButtons(axisValue) {
          var value = Math.abs(axisValue);
          if (axisValue > 0) {
            return {
              negative: 0,
              positive: value
            };
          } else if (axisValue < 0) {
            return {
              negative: value,
              positive: 0
            };
          } else {
            return {
              negative: 0,
              positive: 0
            };
          }
        };
        _proto._updateWebPoseState = function _updateWebPoseState(info) {
          if (info.code !== Pose$2.HAND_LEFT && info.code !== Pose$2.AIM_LEFT && info.code !== Pose$2.HAND_RIGHT && info.code !== Pose$2.AIM_RIGHT) {
            return;
          }
          this._webPoseState[info.code] = {
            position: new Vec3(info.position.x, info.position.y, info.position.z),
            orientation: new Quat(info.orientation.x, info.orientation.y, info.orientation.z, info.orientation.w)
          };
        };
        _proto._initInputSource = function _initInputSource() {
          var _this = this;
          this._buttonNorth = new InputSourceButton();
          this._buttonNorth.getValue = function () {
            if (_this.deviceId === -1) {
              var _GamepadInputDevice$_3;
              var webxrGamepad = (_GamepadInputDevice$_3 = GamepadInputDevice._getWebXRGamepadMap()) === null || _GamepadInputDevice$_3 === void 0 ? void 0 : _GamepadInputDevice$_3.get(XRLeftHandedness);
              if (webxrGamepad && webxrGamepad.buttons.length > XR_BUTTON_2) {
                return webxrGamepad.buttons[XR_BUTTON_2].value;
              }
              return 0;
            }
            var webGamepad = GamepadInputDevice._getWebGamepad(_this.deviceId);
            if (webGamepad) {
              return webGamepad.buttons[BUTTON_NORTH].value;
            }
            return 0;
          };
          this._buttonEast = new InputSourceButton();
          this._buttonEast.getValue = function () {
            if (_this.deviceId === -1) {
              var _GamepadInputDevice$_4;
              var webxrGamepad = (_GamepadInputDevice$_4 = GamepadInputDevice._getWebXRGamepadMap()) === null || _GamepadInputDevice$_4 === void 0 ? void 0 : _GamepadInputDevice$_4.get(XRRightHandedness);
              if (webxrGamepad && webxrGamepad.buttons.length > XR_BUTTON_2) {
                return webxrGamepad.buttons[XR_BUTTON_2].value;
              }
              return 0;
            }
            var webGamepad = GamepadInputDevice._getWebGamepad(_this.deviceId);
            if (webGamepad) {
              return webGamepad.buttons[BUTTON_EAST].value;
            }
            return 0;
          };
          this._buttonWest = new InputSourceButton();
          this._buttonWest.getValue = function () {
            if (_this.deviceId === -1) {
              var _GamepadInputDevice$_5;
              var webxrGamepad = (_GamepadInputDevice$_5 = GamepadInputDevice._getWebXRGamepadMap()) === null || _GamepadInputDevice$_5 === void 0 ? void 0 : _GamepadInputDevice$_5.get(XRLeftHandedness);
              if (webxrGamepad && webxrGamepad.buttons.length > XR_BUTTON_1) {
                return webxrGamepad.buttons[XR_BUTTON_1].value;
              }
              return 0;
            }
            var webGamepad = GamepadInputDevice._getWebGamepad(_this.deviceId);
            if (webGamepad) {
              return webGamepad.buttons[BUTTON_WEST].value;
            }
            return 0;
          };
          this._buttonSouth = new InputSourceButton();
          this._buttonSouth.getValue = function () {
            if (_this.deviceId === -1) {
              var _GamepadInputDevice$_6;
              var webxrGamepad = (_GamepadInputDevice$_6 = GamepadInputDevice._getWebXRGamepadMap()) === null || _GamepadInputDevice$_6 === void 0 ? void 0 : _GamepadInputDevice$_6.get(XRRightHandedness);
              if (webxrGamepad && webxrGamepad.buttons.length > XR_BUTTON_1) {
                return webxrGamepad.buttons[XR_BUTTON_1].value;
              }
              return 0;
            }
            var webGamepad = GamepadInputDevice._getWebGamepad(_this.deviceId);
            if (webGamepad) {
              return webGamepad.buttons[BUTTON_SOUTH].value;
            }
            return 0;
          };
          this._buttonL1 = new InputSourceButton();
          this._buttonL1.getValue = function () {
            var webGamepad = GamepadInputDevice._getWebGamepad(_this.deviceId);
            if (webGamepad) {
              return webGamepad.buttons[BUTTON_L1].value;
            }
            return 0;
          };
          this._buttonL2 = new InputSourceButton();
          this._buttonL2.getValue = function () {
            if (_this.deviceId === -1) {
              var _GamepadInputDevice$_7;
              var webxrGamepad = (_GamepadInputDevice$_7 = GamepadInputDevice._getWebXRGamepadMap()) === null || _GamepadInputDevice$_7 === void 0 ? void 0 : _GamepadInputDevice$_7.get(XRLeftHandedness);
              if (webxrGamepad && webxrGamepad.buttons.length > XR_TRIGGER) {
                return webxrGamepad.buttons[XR_TRIGGER].value;
              }
              return 0;
            }
            var webGamepad = GamepadInputDevice._getWebGamepad(_this.deviceId);
            if (webGamepad) {
              return webGamepad.buttons[BUTTON_L2].value;
            }
            return 0;
          };
          this._buttonL3 = new InputSourceButton();
          this._buttonL3.getValue = function () {
            if (_this.deviceId === -1) {
              var _GamepadInputDevice$_8;
              var webxrGamepad = (_GamepadInputDevice$_8 = GamepadInputDevice._getWebXRGamepadMap()) === null || _GamepadInputDevice$_8 === void 0 ? void 0 : _GamepadInputDevice$_8.get(XRLeftHandedness);
              if (webxrGamepad) {
                if (webxrGamepad.buttons.length > XR_STICK && webxrGamepad.buttons[XR_STICK].value !== 0) {
                  return webxrGamepad.buttons[XR_STICK].value;
                } else if (webxrGamepad.buttons.length > XR_TOUCHPAD && webxrGamepad.buttons[XR_TOUCHPAD].value !== 0) {
                  return webxrGamepad.buttons[XR_TOUCHPAD].value;
                }
              }
              return 0;
            }
            var webGamepad = GamepadInputDevice._getWebGamepad(_this.deviceId);
            if (webGamepad) {
              return webGamepad.buttons[BUTTON_L3].value;
            }
            return 0;
          };
          this._buttonR1 = new InputSourceButton();
          this._buttonR1.getValue = function () {
            var webGamepad = GamepadInputDevice._getWebGamepad(_this.deviceId);
            if (webGamepad) {
              return webGamepad.buttons[BUTTON_R1].value;
            }
            return 0;
          };
          this._buttonR2 = new InputSourceButton();
          this._buttonR2.getValue = function () {
            if (_this.deviceId === -1) {
              var _GamepadInputDevice$_9;
              var webxrGamepad = (_GamepadInputDevice$_9 = GamepadInputDevice._getWebXRGamepadMap()) === null || _GamepadInputDevice$_9 === void 0 ? void 0 : _GamepadInputDevice$_9.get(XRRightHandedness);
              if (webxrGamepad && webxrGamepad.buttons.length > XR_TRIGGER) {
                return webxrGamepad.buttons[XR_TRIGGER].value;
              }
              return 0;
            }
            var webGamepad = GamepadInputDevice._getWebGamepad(_this.deviceId);
            if (webGamepad) {
              return webGamepad.buttons[BUTTON_R2].value;
            }
            return 0;
          };
          this._buttonR3 = new InputSourceButton();
          this._buttonR3.getValue = function () {
            if (_this.deviceId === -1) {
              var _GamepadInputDevice$_10;
              var webxrGamepad = (_GamepadInputDevice$_10 = GamepadInputDevice._getWebXRGamepadMap()) === null || _GamepadInputDevice$_10 === void 0 ? void 0 : _GamepadInputDevice$_10.get(XRRightHandedness);
              if (webxrGamepad) {
                if (webxrGamepad.buttons.length > XR_STICK && webxrGamepad.buttons[XR_STICK].value !== 0) {
                  return webxrGamepad.buttons[XR_STICK].value;
                } else if (webxrGamepad.buttons.length > XR_TOUCHPAD && webxrGamepad.buttons[XR_TOUCHPAD].value !== 0) {
                  return webxrGamepad.buttons[XR_TOUCHPAD].value;
                }
              }
              return 0;
            }
            var webGamepad = GamepadInputDevice._getWebGamepad(_this.deviceId);
            if (webGamepad) {
              return webGamepad.buttons[BUTTON_R3].value;
            }
            return 0;
          };
          this._buttonShare = new InputSourceButton();
          this._buttonShare.getValue = function () {
            var webGamepad = GamepadInputDevice._getWebGamepad(_this.deviceId);
            if (webGamepad) {
              return webGamepad.buttons[BUTTON_SHARE].value;
            }
            return 0;
          };
          this._buttonOptions = new InputSourceButton();
          this._buttonOptions.getValue = function () {
            var webGamepad = GamepadInputDevice._getWebGamepad(_this.deviceId);
            if (webGamepad) {
              return webGamepad.buttons[BUTTON_OPTIONS].value;
            }
            return 0;
          };
          var dpadUp = new InputSourceButton();
          dpadUp.getValue = function () {
            var webGamepad = GamepadInputDevice._getWebGamepad(_this.deviceId);
            if (webGamepad) {
              return webGamepad.buttons[BUTTON_DPAD_UP].value;
            }
            return 0;
          };
          var dpadDown = new InputSourceButton();
          dpadDown.getValue = function () {
            var webGamepad = GamepadInputDevice._getWebGamepad(_this.deviceId);
            if (webGamepad) {
              return webGamepad.buttons[BUTTON_DPAD_DOWN].value;
            }
            return 0;
          };
          var dpadLeft = new InputSourceButton();
          dpadLeft.getValue = function () {
            var webGamepad = GamepadInputDevice._getWebGamepad(_this.deviceId);
            if (webGamepad) {
              return webGamepad.buttons[BUTTON_DPAD_LEFT].value;
            }
            return 0;
          };
          var dpadRight = new InputSourceButton();
          dpadRight.getValue = function () {
            var webGamepad = GamepadInputDevice._getWebGamepad(_this.deviceId);
            if (webGamepad) {
              return webGamepad.buttons[BUTTON_DPAD_RIGHT].value;
            }
            return 0;
          };
          this._dpad = new InputSourceDpad({
            up: dpadUp,
            down: dpadDown,
            left: dpadLeft,
            right: dpadRight
          });
          var leftStickUp = new InputSourceButton();
          leftStickUp.getValue = function () {
            if (_this.deviceId === -1) {
              var _GamepadInputDevice$_11;
              var webxrGamepad = (_GamepadInputDevice$_11 = GamepadInputDevice._getWebXRGamepadMap()) === null || _GamepadInputDevice$_11 === void 0 ? void 0 : _GamepadInputDevice$_11.get(XRLeftHandedness);
              if (webxrGamepad) {
                if (webxrGamepad.axes.length > XR_AXIS_STICK_Y && webxrGamepad.axes[XR_AXIS_STICK_Y] !== 0) {
                  return _this._axisToButtons(webxrGamepad.axes[XR_AXIS_STICK_Y]).negative;
                } else if (webxrGamepad.axes.length > XR_AXIS_TOUCHPAD_Y && webxrGamepad.axes[XR_AXIS_TOUCHPAD_Y] !== 0) {
                  return _this._axisToButtons(webxrGamepad.axes[XR_AXIS_TOUCHPAD_Y]).negative;
                }
              }
              return 0;
            }
            var webGamepad = GamepadInputDevice._getWebGamepad(_this.deviceId);
            if (webGamepad) {
              return _this._axisToButtons(webGamepad.axes[AXIS_LEFT_STICK_Y]).negative;
            }
            return 0;
          };
          var leftStickDown = new InputSourceButton();
          leftStickDown.getValue = function () {
            if (_this.deviceId === -1) {
              var _GamepadInputDevice$_12;
              var webxrGamepad = (_GamepadInputDevice$_12 = GamepadInputDevice._getWebXRGamepadMap()) === null || _GamepadInputDevice$_12 === void 0 ? void 0 : _GamepadInputDevice$_12.get(XRLeftHandedness);
              if (webxrGamepad) {
                if (webxrGamepad.axes.length > XR_AXIS_STICK_Y && webxrGamepad.axes[XR_AXIS_STICK_Y] !== 0) {
                  return _this._axisToButtons(webxrGamepad.axes[XR_AXIS_STICK_Y]).positive;
                } else if (webxrGamepad.axes.length > XR_AXIS_TOUCHPAD_Y && webxrGamepad.axes[XR_AXIS_TOUCHPAD_Y] !== 0) {
                  return _this._axisToButtons(webxrGamepad.axes[XR_AXIS_TOUCHPAD_Y]).positive;
                }
              }
              return 0;
            }
            var webGamepad = GamepadInputDevice._getWebGamepad(_this.deviceId);
            if (webGamepad) {
              return _this._axisToButtons(webGamepad.axes[AXIS_LEFT_STICK_Y]).positive;
            }
            return 0;
          };
          var leftStickLeft = new InputSourceButton();
          leftStickLeft.getValue = function () {
            if (_this.deviceId === -1) {
              var _GamepadInputDevice$_13;
              var webxrGamepad = (_GamepadInputDevice$_13 = GamepadInputDevice._getWebXRGamepadMap()) === null || _GamepadInputDevice$_13 === void 0 ? void 0 : _GamepadInputDevice$_13.get(XRLeftHandedness);
              if (webxrGamepad) {
                if (webxrGamepad.axes.length > XR_AXIS_STICK_X && webxrGamepad.axes[XR_AXIS_STICK_X] !== 0) {
                  return _this._axisToButtons(webxrGamepad.axes[XR_AXIS_STICK_X]).negative;
                } else if (webxrGamepad.axes.length > XR_AXIS_TOUCHPAD_X && webxrGamepad.axes[XR_AXIS_TOUCHPAD_X] !== 0) {
                  return _this._axisToButtons(webxrGamepad.axes[XR_AXIS_TOUCHPAD_X]).negative;
                }
              }
              return 0;
            }
            var webGamepad = GamepadInputDevice._getWebGamepad(_this.deviceId);
            if (webGamepad) {
              return _this._axisToButtons(webGamepad.axes[AXIS_LEFT_STICK_X]).negative;
            }
            return 0;
          };
          var leftStickRight = new InputSourceButton();
          leftStickRight.getValue = function () {
            if (_this.deviceId === -1) {
              var _GamepadInputDevice$_14;
              var webxrGamepad = (_GamepadInputDevice$_14 = GamepadInputDevice._getWebXRGamepadMap()) === null || _GamepadInputDevice$_14 === void 0 ? void 0 : _GamepadInputDevice$_14.get(XRLeftHandedness);
              if (webxrGamepad) {
                if (webxrGamepad.axes.length > XR_AXIS_STICK_X && webxrGamepad.axes[XR_AXIS_STICK_X] !== 0) {
                  return _this._axisToButtons(webxrGamepad.axes[XR_AXIS_STICK_X]).positive;
                } else if (webxrGamepad.axes.length > XR_AXIS_TOUCHPAD_X && webxrGamepad.axes[XR_AXIS_TOUCHPAD_X] !== 0) {
                  return _this._axisToButtons(webxrGamepad.axes[XR_AXIS_TOUCHPAD_X]).positive;
                }
              }
              return 0;
            }
            var webGamepad = GamepadInputDevice._getWebGamepad(_this.deviceId);
            if (webGamepad) {
              return _this._axisToButtons(webGamepad.axes[AXIS_LEFT_STICK_X]).positive;
            }
            return 0;
          };
          this._leftStick = new InputSourceStick({
            up: leftStickUp,
            down: leftStickDown,
            left: leftStickLeft,
            right: leftStickRight
          });
          var rightStickUp = new InputSourceButton();
          rightStickUp.getValue = function () {
            if (_this.deviceId === -1) {
              var _GamepadInputDevice$_15;
              var webxrGamepad = (_GamepadInputDevice$_15 = GamepadInputDevice._getWebXRGamepadMap()) === null || _GamepadInputDevice$_15 === void 0 ? void 0 : _GamepadInputDevice$_15.get(XRRightHandedness);
              if (webxrGamepad) {
                if (webxrGamepad.axes.length > XR_AXIS_STICK_Y && webxrGamepad.axes[XR_AXIS_STICK_Y] !== 0) {
                  return _this._axisToButtons(webxrGamepad.axes[XR_AXIS_STICK_Y]).negative;
                } else if (webxrGamepad.axes.length > XR_AXIS_TOUCHPAD_Y && webxrGamepad.axes[XR_AXIS_TOUCHPAD_Y] !== 0) {
                  return _this._axisToButtons(webxrGamepad.axes[XR_AXIS_TOUCHPAD_Y]).negative;
                }
              }
              return 0;
            }
            var webGamepad = GamepadInputDevice._getWebGamepad(_this.deviceId);
            if (webGamepad) {
              return _this._axisToButtons(webGamepad.axes[AXIS_RIGHT_STICK_Y]).negative;
            }
            return 0;
          };
          var rightStickDown = new InputSourceButton();
          rightStickDown.getValue = function () {
            if (_this.deviceId === -1) {
              var _GamepadInputDevice$_16;
              var webxrGamepad = (_GamepadInputDevice$_16 = GamepadInputDevice._getWebXRGamepadMap()) === null || _GamepadInputDevice$_16 === void 0 ? void 0 : _GamepadInputDevice$_16.get(XRRightHandedness);
              if (webxrGamepad) {
                if (webxrGamepad.axes.length > XR_AXIS_STICK_Y && webxrGamepad.axes[XR_AXIS_STICK_Y] !== 0) {
                  return _this._axisToButtons(webxrGamepad.axes[XR_AXIS_STICK_Y]).positive;
                } else if (webxrGamepad.axes.length > XR_AXIS_TOUCHPAD_Y && webxrGamepad.axes[XR_AXIS_TOUCHPAD_Y] !== 0) {
                  return _this._axisToButtons(webxrGamepad.axes[XR_AXIS_TOUCHPAD_Y]).positive;
                }
              }
              return 0;
            }
            var webGamepad = GamepadInputDevice._getWebGamepad(_this.deviceId);
            if (webGamepad) {
              return _this._axisToButtons(webGamepad.axes[AXIS_RIGHT_STICK_Y]).positive;
            }
            return 0;
          };
          var rightStickLeft = new InputSourceButton();
          rightStickLeft.getValue = function () {
            if (_this.deviceId === -1) {
              var _GamepadInputDevice$_17;
              var webxrGamepad = (_GamepadInputDevice$_17 = GamepadInputDevice._getWebXRGamepadMap()) === null || _GamepadInputDevice$_17 === void 0 ? void 0 : _GamepadInputDevice$_17.get(XRRightHandedness);
              if (webxrGamepad) {
                if (webxrGamepad.axes.length > XR_AXIS_STICK_X && webxrGamepad.axes[XR_AXIS_STICK_X] !== 0) {
                  return _this._axisToButtons(webxrGamepad.axes[XR_AXIS_STICK_X]).negative;
                } else if (webxrGamepad.axes.length > XR_AXIS_TOUCHPAD_X && webxrGamepad.axes[XR_AXIS_TOUCHPAD_X] !== 0) {
                  return _this._axisToButtons(webxrGamepad.axes[XR_AXIS_TOUCHPAD_X]).negative;
                }
              }
              return 0;
            }
            var webGamepad = GamepadInputDevice._getWebGamepad(_this.deviceId);
            if (webGamepad) {
              return _this._axisToButtons(webGamepad.axes[AXIS_RIGHT_STICK_X]).negative;
            }
            return 0;
          };
          var rightStickRight = new InputSourceButton();
          rightStickRight.getValue = function () {
            if (_this.deviceId === -1) {
              var _GamepadInputDevice$_18;
              var webxrGamepad = (_GamepadInputDevice$_18 = GamepadInputDevice._getWebXRGamepadMap()) === null || _GamepadInputDevice$_18 === void 0 ? void 0 : _GamepadInputDevice$_18.get(XRRightHandedness);
              if (webxrGamepad) {
                if (webxrGamepad.axes.length > XR_AXIS_STICK_X && webxrGamepad.axes[XR_AXIS_STICK_X] !== 0) {
                  return _this._axisToButtons(webxrGamepad.axes[XR_AXIS_STICK_X]).positive;
                } else if (webxrGamepad.axes.length > XR_AXIS_TOUCHPAD_X && webxrGamepad.axes[XR_AXIS_TOUCHPAD_X] !== 0) {
                  return _this._axisToButtons(webxrGamepad.axes[XR_AXIS_TOUCHPAD_X]).positive;
                }
              }
              return 0;
            }
            var webGamepad = GamepadInputDevice._getWebGamepad(_this.deviceId);
            if (webGamepad) {
              return _this._axisToButtons(webGamepad.axes[AXIS_RIGHT_STICK_X]).positive;
            }
            return 0;
          };
          this._rightStick = new InputSourceStick({
            up: rightStickUp,
            down: rightStickDown,
            left: rightStickLeft,
            right: rightStickRight
          });
          this._buttonStart = new InputSourceButton();
          this._buttonStart.getValue = function () {
            return 0;
          };
          this._gripLeft = new InputSourceButton();
          this._gripLeft.getValue = function () {
            if (_this.deviceId === -1) {
              var _GamepadInputDevice$_19;
              var webxrGamepad = (_GamepadInputDevice$_19 = GamepadInputDevice._getWebXRGamepadMap()) === null || _GamepadInputDevice$_19 === void 0 ? void 0 : _GamepadInputDevice$_19.get(XRLeftHandedness);
              if (webxrGamepad && webxrGamepad.buttons.length > XR_GRIP) {
                return webxrGamepad.buttons[XR_GRIP].value;
              }
            }
            return 0;
          };
          this._gripRight = new InputSourceButton();
          this._gripRight.getValue = function () {
            if (_this.deviceId === -1) {
              var _GamepadInputDevice$_20;
              var webxrGamepad = (_GamepadInputDevice$_20 = GamepadInputDevice._getWebXRGamepadMap()) === null || _GamepadInputDevice$_20 === void 0 ? void 0 : _GamepadInputDevice$_20.get(XRRightHandedness);
              if (webxrGamepad && webxrGamepad.buttons.length > XR_GRIP) {
                return webxrGamepad.buttons[XR_GRIP].value;
              }
            }
            return 0;
          };
          this._handLeftPosition = new InputSourcePosition();
          this._handLeftPosition.getValue = function () {
            return _this._webPoseState[Pose$2.HAND_LEFT].position;
          };
          this._handLeftOrientation = new InputSourceOrientation();
          this._handLeftOrientation.getValue = function () {
            return _this._webPoseState[Pose$2.HAND_LEFT].orientation;
          };
          this._handRightPosition = new InputSourcePosition();
          this._handRightPosition.getValue = function () {
            return _this._webPoseState[Pose$2.HAND_RIGHT].position;
          };
          this._handRightOrientation = new InputSourceOrientation();
          this._handRightOrientation.getValue = function () {
            return _this._webPoseState[Pose$2.HAND_RIGHT].orientation;
          };
          this._aimLeftPosition = new InputSourcePosition();
          this._aimLeftPosition.getValue = function () {
            return _this._webPoseState[Pose$2.AIM_LEFT].position;
          };
          this._aimLeftOrientation = new InputSourceOrientation();
          this._aimLeftOrientation.getValue = function () {
            return _this._webPoseState[Pose$2.AIM_LEFT].orientation;
          };
          this._aimRightPosition = new InputSourcePosition();
          this._aimRightPosition.getValue = function () {
            return _this._webPoseState[Pose$2.AIM_RIGHT].position;
          };
          this._aimRightOrientation = new InputSourceOrientation();
          this._aimRightOrientation.getValue = function () {
            return _this._webPoseState[Pose$2.AIM_RIGHT].orientation;
          };
        };
        _createClass(GamepadInputDevice, [{
          key: "buttonNorth",
          get: function get() {
            return this._buttonNorth;
          }
        }, {
          key: "buttonEast",
          get: function get() {
            return this._buttonEast;
          }
        }, {
          key: "buttonWest",
          get: function get() {
            return this._buttonWest;
          }
        }, {
          key: "buttonSouth",
          get: function get() {
            return this._buttonSouth;
          }
        }, {
          key: "buttonL1",
          get: function get() {
            return this._buttonL1;
          }
        }, {
          key: "buttonL2",
          get: function get() {
            return this._buttonL2;
          }
        }, {
          key: "buttonL3",
          get: function get() {
            return this._buttonL3;
          }
        }, {
          key: "buttonR1",
          get: function get() {
            return this._buttonR1;
          }
        }, {
          key: "buttonR2",
          get: function get() {
            return this._buttonR2;
          }
        }, {
          key: "buttonR3",
          get: function get() {
            return this._buttonR3;
          }
        }, {
          key: "buttonShare",
          get: function get() {
            return this._buttonShare;
          }
        }, {
          key: "buttonOptions",
          get: function get() {
            return this._buttonOptions;
          }
        }, {
          key: "dpad",
          get: function get() {
            return this._dpad;
          }
        }, {
          key: "leftStick",
          get: function get() {
            return this._leftStick;
          }
        }, {
          key: "rightStick",
          get: function get() {
            return this._rightStick;
          }
        }, {
          key: "buttonStart",
          get: function get() {
            return this._buttonStart;
          }
        }, {
          key: "gripLeft",
          get: function get() {
            return this._gripLeft;
          }
        }, {
          key: "gripRight",
          get: function get() {
            return this._gripRight;
          }
        }, {
          key: "handLeftPosition",
          get: function get() {
            return this._handLeftPosition;
          }
        }, {
          key: "handLeftOrientation",
          get: function get() {
            return this._handLeftOrientation;
          }
        }, {
          key: "handRightPosition",
          get: function get() {
            return this._handRightPosition;
          }
        }, {
          key: "handRightOrientation",
          get: function get() {
            return this._handRightOrientation;
          }
        }, {
          key: "aimLeftPosition",
          get: function get() {
            return this._aimLeftPosition;
          }
        }, {
          key: "aimLeftOrientation",
          get: function get() {
            return this._aimLeftOrientation;
          }
        }, {
          key: "aimRightPosition",
          get: function get() {
            return this._aimRightPosition;
          }
        }, {
          key: "aimRightOrientation",
          get: function get() {
            return this._aimRightOrientation;
          }
        }, {
          key: "deviceId",
          get: function get() {
            return this._deviceId;
          }
        }, {
          key: "connected",
          get: function get() {
            return this._connected;
          }
        }]);
        return GamepadInputDevice;
      }();
      GamepadInputDevice.all = [];
      GamepadInputDevice.xr = null;
      GamepadInputDevice._eventTarget = new EventTarget();
      GamepadInputDevice._cachedWebGamepads = [];
      GamepadInputDevice._cachedWebXRGamepadMap = null;
      GamepadInputDevice._intervalId = -1;
      GamepadInputDevice._totalGamepadCnt = 0;

      var Button$1;
      (function (Button) {
        Button[Button["BUTTON_EAST"] = 0] = "BUTTON_EAST";
        Button[Button["BUTTON_SOUTH"] = 1] = "BUTTON_SOUTH";
        Button[Button["BUTTON_WEST"] = 2] = "BUTTON_WEST";
        Button[Button["BUTTON_NORTH"] = 3] = "BUTTON_NORTH";
        Button[Button["BUTTON_TRIGGER_LEFT"] = 4] = "BUTTON_TRIGGER_LEFT";
        Button[Button["BUTTON_TRIGGER_RIGHT"] = 5] = "BUTTON_TRIGGER_RIGHT";
        Button[Button["TRIGGER_LEFT"] = 6] = "TRIGGER_LEFT";
        Button[Button["TRIGGER_RIGHT"] = 7] = "TRIGGER_RIGHT";
        Button[Button["GRIP_LEFT"] = 8] = "GRIP_LEFT";
        Button[Button["GRIP_RIGHT"] = 9] = "GRIP_RIGHT";
        Button[Button["BUTTON_LEFT_STICK"] = 10] = "BUTTON_LEFT_STICK";
        Button[Button["LEFT_STICK_UP"] = 11] = "LEFT_STICK_UP";
        Button[Button["LEFT_STICK_DOWN"] = 12] = "LEFT_STICK_DOWN";
        Button[Button["LEFT_STICK_LEFT"] = 13] = "LEFT_STICK_LEFT";
        Button[Button["LEFT_STICK_RIGHT"] = 14] = "LEFT_STICK_RIGHT";
        Button[Button["BUTTON_RIGHT_STICK"] = 15] = "BUTTON_RIGHT_STICK";
        Button[Button["RIGHT_STICK_UP"] = 16] = "RIGHT_STICK_UP";
        Button[Button["RIGHT_STICK_DOWN"] = 17] = "RIGHT_STICK_DOWN";
        Button[Button["RIGHT_STICK_LEFT"] = 18] = "RIGHT_STICK_LEFT";
        Button[Button["RIGHT_STICK_RIGHT"] = 19] = "RIGHT_STICK_RIGHT";
        Button[Button["ROKID_MENU"] = 20] = "ROKID_MENU";
        Button[Button["ROKID_START"] = 21] = "ROKID_START";
      })(Button$1 || (Button$1 = {}));
      var KeyEventType;
      (function (KeyEventType) {
        KeyEventType[KeyEventType["KET_CLICK"] = 0] = "KET_CLICK";
        KeyEventType[KeyEventType["KET_STICK"] = 1] = "KET_STICK";
        KeyEventType[KeyEventType["KET_GRAB"] = 2] = "KET_GRAB";
      })(KeyEventType || (KeyEventType = {}));
      var StickAxisCode;
      (function (StickAxisCode) {
        StickAxisCode[StickAxisCode["UNDEFINE"] = 0] = "UNDEFINE";
        StickAxisCode[StickAxisCode["X"] = 1] = "X";
        StickAxisCode[StickAxisCode["Y"] = 2] = "Y";
        StickAxisCode[StickAxisCode["LEFT_STICK_X"] = 3] = "LEFT_STICK_X";
        StickAxisCode[StickAxisCode["LEFT_STICK_Y"] = 4] = "LEFT_STICK_Y";
        StickAxisCode[StickAxisCode["RIGHT_STICK_X"] = 5] = "RIGHT_STICK_X";
        StickAxisCode[StickAxisCode["RIGHT_STICK_Y"] = 6] = "RIGHT_STICK_Y";
        StickAxisCode[StickAxisCode["LEFT_TRIGGER"] = 7] = "LEFT_TRIGGER";
        StickAxisCode[StickAxisCode["RIGHT_TIRGGER"] = 8] = "RIGHT_TIRGGER";
        StickAxisCode[StickAxisCode["LEFT_GRIP"] = 9] = "LEFT_GRIP";
        StickAxisCode[StickAxisCode["RIGHT_GRIP"] = 10] = "RIGHT_GRIP";
      })(StickAxisCode || (StickAxisCode = {}));
      var _nativeButtonMap = {
        1: Button$1.BUTTON_EAST,
        2: Button$1.BUTTON_SOUTH,
        3: Button$1.BUTTON_NORTH,
        4: Button$1.BUTTON_WEST,
        9: Button$1.BUTTON_LEFT_STICK,
        10: Button$1.BUTTON_RIGHT_STICK,
        11: Button$1.ROKID_MENU,
        12: Button$1.ROKID_START,
        13: Button$1.BUTTON_TRIGGER_LEFT,
        14: Button$1.BUTTON_TRIGGER_RIGHT
      };
      var HandleInputDevice = function () {
        function HandleInputDevice() {
          var _this$_nativeButtonSt,
            _this = this;
          this._eventTarget = new EventTarget();
          this._buttonNorth = void 0;
          this._buttonEast = void 0;
          this._buttonWest = void 0;
          this._buttonSouth = void 0;
          this._buttonTriggerLeft = void 0;
          this._buttonTriggerRight = void 0;
          this._triggerLeft = void 0;
          this._triggerRight = void 0;
          this._gripLeft = void 0;
          this._gripRight = void 0;
          this._leftStick = void 0;
          this._rightStick = void 0;
          this._buttonLeftStick = void 0;
          this._buttonRightStick = void 0;
          this._buttonOptions = void 0;
          this._buttonStart = void 0;
          this._handLeftPosition = void 0;
          this._handLeftOrientation = void 0;
          this._handRightPosition = void 0;
          this._handRightOrientation = void 0;
          this._aimLeftPosition = void 0;
          this._aimLeftOrientation = void 0;
          this._aimRightPosition = void 0;
          this._aimRightOrientation = void 0;
          this._nativeButtonState = (_this$_nativeButtonSt = {}, _this$_nativeButtonSt[Button$1.BUTTON_SOUTH] = 0, _this$_nativeButtonSt[Button$1.BUTTON_EAST] = 0, _this$_nativeButtonSt[Button$1.BUTTON_WEST] = 0, _this$_nativeButtonSt[Button$1.BUTTON_NORTH] = 0, _this$_nativeButtonSt[Button$1.BUTTON_TRIGGER_LEFT] = 0, _this$_nativeButtonSt[Button$1.BUTTON_TRIGGER_RIGHT] = 0, _this$_nativeButtonSt[Button$1.TRIGGER_LEFT] = 0, _this$_nativeButtonSt[Button$1.TRIGGER_RIGHT] = 0, _this$_nativeButtonSt[Button$1.GRIP_LEFT] = 0, _this$_nativeButtonSt[Button$1.GRIP_RIGHT] = 0, _this$_nativeButtonSt[Button$1.LEFT_STICK_UP] = 0, _this$_nativeButtonSt[Button$1.LEFT_STICK_DOWN] = 0, _this$_nativeButtonSt[Button$1.LEFT_STICK_LEFT] = 0, _this$_nativeButtonSt[Button$1.LEFT_STICK_RIGHT] = 0, _this$_nativeButtonSt[Button$1.RIGHT_STICK_UP] = 0, _this$_nativeButtonSt[Button$1.RIGHT_STICK_DOWN] = 0, _this$_nativeButtonSt[Button$1.RIGHT_STICK_LEFT] = 0, _this$_nativeButtonSt[Button$1.RIGHT_STICK_RIGHT] = 0, _this$_nativeButtonSt[Button$1.BUTTON_LEFT_STICK] = 0, _this$_nativeButtonSt[Button$1.BUTTON_RIGHT_STICK] = 0, _this$_nativeButtonSt[Button$1.ROKID_MENU] = 0, _this$_nativeButtonSt[Button$1.ROKID_START] = 0, _this$_nativeButtonSt);
          this._initInputSource();
          window.addEventListener('xr-remote-input', function (evt) {
            var remoteInputEvent = evt;
            var keyEventType = remoteInputEvent.detail.keyEventType;
            var stickAxisCode = remoteInputEvent.detail.stickAxisCode;
            var stickAxisValue = remoteInputEvent.detail.stickAxisValue;
            var stickKeyCode = remoteInputEvent.detail.stickKeyCode;
            var isButtonPressed = remoteInputEvent.detail.isButtonPressed;
            if (keyEventType === KeyEventType.KET_CLICK) {
              var button = _nativeButtonMap[stickKeyCode];
              _this._nativeButtonState[button] = isButtonPressed ? 1 : 0;
            } else if (keyEventType === KeyEventType.KET_STICK || keyEventType === KeyEventType.KET_GRAB) {
              var negativeButton;
              var positiveButton;
              var axisValue;
              switch (stickAxisCode) {
                case StickAxisCode.LEFT_STICK_X:
                  negativeButton = Button$1.LEFT_STICK_LEFT;
                  positiveButton = Button$1.LEFT_STICK_RIGHT;
                  axisValue = _this._axisToButtons(stickAxisValue);
                  break;
                case StickAxisCode.LEFT_STICK_Y:
                  negativeButton = Button$1.LEFT_STICK_DOWN;
                  positiveButton = Button$1.LEFT_STICK_UP;
                  axisValue = _this._axisToButtons(stickAxisValue);
                  break;
                case StickAxisCode.RIGHT_STICK_X:
                  negativeButton = Button$1.RIGHT_STICK_LEFT;
                  positiveButton = Button$1.RIGHT_STICK_RIGHT;
                  axisValue = _this._axisToButtons(stickAxisValue);
                  break;
                case StickAxisCode.RIGHT_STICK_Y:
                  negativeButton = Button$1.RIGHT_STICK_DOWN;
                  positiveButton = Button$1.RIGHT_STICK_UP;
                  axisValue = _this._axisToButtons(stickAxisValue);
                  break;
                case StickAxisCode.LEFT_TRIGGER:
                  _this._nativeButtonState[Button$1.TRIGGER_LEFT] = stickAxisValue;
                  break;
                case StickAxisCode.RIGHT_TIRGGER:
                  _this._nativeButtonState[Button$1.TRIGGER_RIGHT] = stickAxisValue;
                  break;
                case StickAxisCode.LEFT_GRIP:
                  _this._nativeButtonState[Button$1.GRIP_LEFT] = stickAxisValue;
                  break;
                case StickAxisCode.RIGHT_GRIP:
                  _this._nativeButtonState[Button$1.GRIP_RIGHT] = stickAxisValue;
                  break;
              }
              if (negativeButton && positiveButton && axisValue) {
                _this._nativeButtonState[negativeButton] = axisValue.negative;
                _this._nativeButtonState[positiveButton] = axisValue.positive;
              }
            }
            _this._eventTarget.emit(InputEventType.HANDLE_INPUT, new EventHandle(InputEventType.HANDLE_INPUT, _this));
          });
        }
        var _proto = HandleInputDevice.prototype;
        _proto._axisToButtons = function _axisToButtons(axisValue) {
          var value = Math.abs(axisValue);
          if (axisValue > 0) {
            return {
              negative: 0,
              positive: value
            };
          } else if (axisValue < 0) {
            return {
              negative: value,
              positive: 0
            };
          } else {
            return {
              negative: 0,
              positive: 0
            };
          }
        };
        _proto._on = function _on(eventType, callback, target) {
          this._eventTarget.on(eventType, callback, target);
        };
        _proto._initInputSource = function _initInputSource() {
          var _this2 = this;
          this._buttonNorth = new InputSourceButton();
          this._buttonNorth.getValue = function () {
            return _this2._nativeButtonState[Button$1.BUTTON_NORTH];
          };
          this._buttonEast = new InputSourceButton();
          this._buttonEast.getValue = function () {
            return _this2._nativeButtonState[Button$1.BUTTON_EAST];
          };
          this._buttonWest = new InputSourceButton();
          this._buttonWest.getValue = function () {
            return _this2._nativeButtonState[Button$1.BUTTON_WEST];
          };
          this._buttonSouth = new InputSourceButton();
          this._buttonSouth.getValue = function () {
            return _this2._nativeButtonState[Button$1.BUTTON_SOUTH];
          };
          this._buttonTriggerLeft = new InputSourceButton();
          this._buttonTriggerLeft.getValue = function () {
            return _this2._nativeButtonState[Button$1.BUTTON_TRIGGER_LEFT];
          };
          this._buttonTriggerRight = new InputSourceButton();
          this._buttonTriggerRight.getValue = function () {
            return _this2._nativeButtonState[Button$1.BUTTON_TRIGGER_RIGHT];
          };
          this._triggerLeft = new InputSourceButton();
          this._triggerLeft.getValue = function () {
            return _this2._nativeButtonState[Button$1.TRIGGER_LEFT];
          };
          this._triggerRight = new InputSourceButton();
          this._triggerRight.getValue = function () {
            return _this2._nativeButtonState[Button$1.TRIGGER_RIGHT];
          };
          this._gripLeft = new InputSourceButton();
          this._gripLeft.getValue = function () {
            return _this2._nativeButtonState[Button$1.GRIP_LEFT];
          };
          this._gripRight = new InputSourceButton();
          this._gripRight.getValue = function () {
            return _this2._nativeButtonState[Button$1.GRIP_RIGHT];
          };
          this._buttonLeftStick = new InputSourceButton();
          this._buttonLeftStick.getValue = function () {
            return _this2._nativeButtonState[Button$1.BUTTON_LEFT_STICK];
          };
          var leftStickUp = new InputSourceButton();
          leftStickUp.getValue = function () {
            return _this2._nativeButtonState[Button$1.LEFT_STICK_UP];
          };
          var leftStickDown = new InputSourceButton();
          leftStickDown.getValue = function () {
            return _this2._nativeButtonState[Button$1.LEFT_STICK_DOWN];
          };
          var leftStickLeft = new InputSourceButton();
          leftStickLeft.getValue = function () {
            return _this2._nativeButtonState[Button$1.LEFT_STICK_LEFT];
          };
          var leftStickRight = new InputSourceButton();
          leftStickRight.getValue = function () {
            return _this2._nativeButtonState[Button$1.LEFT_STICK_RIGHT];
          };
          this._leftStick = new InputSourceStick({
            up: leftStickUp,
            down: leftStickDown,
            left: leftStickLeft,
            right: leftStickRight
          });
          this._buttonRightStick = new InputSourceButton();
          this._buttonRightStick.getValue = function () {
            return _this2._nativeButtonState[Button$1.BUTTON_RIGHT_STICK];
          };
          var rightStickUp = new InputSourceButton();
          rightStickUp.getValue = function () {
            return _this2._nativeButtonState[Button$1.RIGHT_STICK_UP];
          };
          var rightStickDown = new InputSourceButton();
          rightStickDown.getValue = function () {
            return _this2._nativeButtonState[Button$1.RIGHT_STICK_DOWN];
          };
          var rightStickLeft = new InputSourceButton();
          rightStickLeft.getValue = function () {
            return _this2._nativeButtonState[Button$1.RIGHT_STICK_LEFT];
          };
          var rightStickRight = new InputSourceButton();
          rightStickRight.getValue = function () {
            return _this2._nativeButtonState[Button$1.RIGHT_STICK_RIGHT];
          };
          this._rightStick = new InputSourceStick({
            up: rightStickUp,
            down: rightStickDown,
            left: rightStickLeft,
            right: rightStickRight
          });
          this._buttonOptions = new InputSourceButton();
          this._buttonOptions.getValue = function () {
            return _this2._nativeButtonState[Button$1.ROKID_MENU];
          };
          this._buttonStart = new InputSourceButton();
          this._buttonStart.getValue = function () {
            return _this2._nativeButtonState[Button$1.ROKID_START];
          };
          this._handLeftPosition = new InputSourcePosition();
          this._handLeftPosition.getValue = function () {
            return Vec3.ZERO;
          };
          this._handLeftOrientation = new InputSourceOrientation();
          this._handLeftOrientation.getValue = function () {
            return Quat.IDENTITY;
          };
          this._handRightPosition = new InputSourcePosition();
          this._handRightPosition.getValue = function () {
            return Vec3.ZERO;
          };
          this._handRightOrientation = new InputSourceOrientation();
          this._handRightOrientation.getValue = function () {
            return Quat.IDENTITY;
          };
          this._aimLeftPosition = new InputSourcePosition();
          this._aimLeftPosition.getValue = function () {
            return Vec3.ZERO;
          };
          this._aimLeftOrientation = new InputSourceOrientation();
          this._aimLeftOrientation.getValue = function () {
            return Quat.IDENTITY;
          };
          this._aimRightPosition = new InputSourcePosition();
          this._aimRightPosition.getValue = function () {
            return Vec3.ZERO;
          };
          this._aimRightOrientation = new InputSourceOrientation();
          this._aimRightOrientation.getValue = function () {
            return Quat.IDENTITY;
          };
        };
        _createClass(HandleInputDevice, [{
          key: "buttonNorth",
          get: function get() {
            return this._buttonNorth;
          }
        }, {
          key: "buttonEast",
          get: function get() {
            return this._buttonEast;
          }
        }, {
          key: "buttonWest",
          get: function get() {
            return this._buttonWest;
          }
        }, {
          key: "buttonSouth",
          get: function get() {
            return this._buttonSouth;
          }
        }, {
          key: "buttonTriggerLeft",
          get: function get() {
            return this._buttonTriggerLeft;
          }
        }, {
          key: "buttonTriggerRight",
          get: function get() {
            return this._buttonTriggerRight;
          }
        }, {
          key: "triggerLeft",
          get: function get() {
            return this._triggerLeft;
          }
        }, {
          key: "triggerRight",
          get: function get() {
            return this._triggerRight;
          }
        }, {
          key: "gripLeft",
          get: function get() {
            return this._gripLeft;
          }
        }, {
          key: "gripRight",
          get: function get() {
            return this._gripRight;
          }
        }, {
          key: "leftStick",
          get: function get() {
            return this._leftStick;
          }
        }, {
          key: "rightStick",
          get: function get() {
            return this._rightStick;
          }
        }, {
          key: "buttonLeftStick",
          get: function get() {
            return this._buttonLeftStick;
          }
        }, {
          key: "buttonRightStick",
          get: function get() {
            return this._buttonRightStick;
          }
        }, {
          key: "buttonOptions",
          get: function get() {
            return this._buttonOptions;
          }
        }, {
          key: "buttonStart",
          get: function get() {
            return this._buttonStart;
          }
        }, {
          key: "handLeftPosition",
          get: function get() {
            return this._handLeftPosition;
          }
        }, {
          key: "handLeftOrientation",
          get: function get() {
            return this._handLeftOrientation;
          }
        }, {
          key: "handRightPosition",
          get: function get() {
            return this._handRightPosition;
          }
        }, {
          key: "handRightOrientation",
          get: function get() {
            return this._handRightOrientation;
          }
        }, {
          key: "aimLeftPosition",
          get: function get() {
            return this._aimLeftPosition;
          }
        }, {
          key: "aimLeftOrientation",
          get: function get() {
            return this._aimLeftOrientation;
          }
        }, {
          key: "aimRightPosition",
          get: function get() {
            return this._aimRightPosition;
          }
        }, {
          key: "aimRightOrientation",
          get: function get() {
            return this._aimRightOrientation;
          }
        }]);
        return HandleInputDevice;
      }();

      var Pose$1;
      (function (Pose) {
        Pose[Pose["VIEW_LEFT"] = 0] = "VIEW_LEFT";
        Pose[Pose["VIEW_RIGHT"] = 3] = "VIEW_RIGHT";
        Pose[Pose["HEAD_MIDDLE"] = 6] = "HEAD_MIDDLE";
      })(Pose$1 || (Pose$1 = {}));
      var HMDInputDevice = function () {
        function HMDInputDevice() {
          var _this$_webPoseState;
          this._eventTarget = new EventTarget();
          this._intervalId = -1;
          this._viewLeftPosition = void 0;
          this._viewLeftOrientation = void 0;
          this._viewRightPosition = void 0;
          this._viewRightOrientation = void 0;
          this._headMiddlePosition = void 0;
          this._headMiddleOrientation = void 0;
          this._webPoseState = (_this$_webPoseState = {}, _this$_webPoseState[Pose$1.VIEW_LEFT] = {
            position: Vec3.ZERO,
            orientation: Quat.IDENTITY
          }, _this$_webPoseState[Pose$1.VIEW_RIGHT] = {
            position: Vec3.ZERO,
            orientation: Quat.IDENTITY
          }, _this$_webPoseState[Pose$1.HEAD_MIDDLE] = {
            position: Vec3.ZERO,
            orientation: Quat.IDENTITY
          }, _this$_webPoseState);
          this._initInputSource();
          this._registerEvent();
        }
        var _proto = HMDInputDevice.prototype;
        _proto._ensureDirectorDefined = function _ensureDirectorDefined() {
          var _this = this;
          return new Promise(function (resolve) {
            _this._intervalId = setInterval(function () {
              if (legacyCC.director && legacyCC.Director) {
                clearInterval(_this._intervalId);
                _this._intervalId = -1;
                resolve();
              }
            }, 50);
          });
        };
        _proto._registerEvent = function _registerEvent() {
          var _this2 = this;
          this._ensureDirectorDefined().then(function () {
            legacyCC.director.on(legacyCC.Director.EVENT_BEGIN_FRAME, _this2._scanHmd, _this2);
          })["catch"](function (e) {});
        };
        _proto._scanHmd = function _scanHmd() {
          var _globalThis$__globalX;
          var infoList = (_globalThis$__globalX = globalThis.__globalXR) === null || _globalThis$__globalX === void 0 ? void 0 : _globalThis$__globalX.webxrHmdPoseInfos;
          if (!infoList) {
            return;
          }
          for (var i = 0; i < infoList.length; ++i) {
            var info = infoList[i];
            this._updateWebPoseState(info);
          }
          this._eventTarget.emit(InputEventType.HMD_POSE_INPUT, new EventHMD(InputEventType.HMD_POSE_INPUT, this));
        };
        _proto._on = function _on(eventType, callback, target) {
          this._eventTarget.on(eventType, callback, target);
        };
        _proto._updateWebPoseState = function _updateWebPoseState(info) {
          if (info.code !== Pose$1.VIEW_LEFT && info.code !== Pose$1.VIEW_RIGHT && info.code !== Pose$1.HEAD_MIDDLE) {
            return;
          }
          this._webPoseState[info.code] = {
            position: new Vec3(info.position.x, info.position.y, info.position.z),
            orientation: new Quat(info.orientation.x, info.orientation.y, info.orientation.z, info.orientation.w)
          };
        };
        _proto._initInputSource = function _initInputSource() {
          var _this3 = this;
          this._viewLeftPosition = new InputSourcePosition();
          this._viewLeftPosition.getValue = function () {
            return _this3._webPoseState[Pose$1.VIEW_LEFT].position;
          };
          this._viewLeftOrientation = new InputSourceOrientation();
          this._viewLeftOrientation.getValue = function () {
            return _this3._webPoseState[Pose$1.VIEW_LEFT].orientation;
          };
          this._viewRightPosition = new InputSourcePosition();
          this._viewRightPosition.getValue = function () {
            return _this3._webPoseState[Pose$1.VIEW_RIGHT].position;
          };
          this._viewRightOrientation = new InputSourceOrientation();
          this._viewRightOrientation.getValue = function () {
            return _this3._webPoseState[Pose$1.VIEW_RIGHT].orientation;
          };
          this._headMiddlePosition = new InputSourcePosition();
          this._headMiddlePosition.getValue = function () {
            return _this3._webPoseState[Pose$1.HEAD_MIDDLE].position;
          };
          this._headMiddleOrientation = new InputSourceOrientation();
          this._headMiddleOrientation.getValue = function () {
            return _this3._webPoseState[Pose$1.HEAD_MIDDLE].orientation;
          };
        };
        _createClass(HMDInputDevice, [{
          key: "viewLeftPosition",
          get: function get() {
            return this._viewLeftPosition;
          }
        }, {
          key: "viewLeftOrientation",
          get: function get() {
            return this._viewLeftOrientation;
          }
        }, {
          key: "viewRightPosition",
          get: function get() {
            return this._viewRightPosition;
          }
        }, {
          key: "viewRightOrientation",
          get: function get() {
            return this._viewRightOrientation;
          }
        }, {
          key: "headMiddlePosition",
          get: function get() {
            return this._headMiddlePosition;
          }
        }, {
          key: "headMiddleOrientation",
          get: function get() {
            return this._headMiddleOrientation;
          }
        }]);
        return HMDInputDevice;
      }();

      var HandheldInputDevice = function () {
        function HandheldInputDevice() {
          this._eventTarget = new EventTarget();
          this._handheldPosition = void 0;
          this._handheldOrientation = void 0;
          this._initInputSource();
        }
        var _proto = HandheldInputDevice.prototype;
        _proto._on = function _on(eventType, callback, target) {
          this._eventTarget.on(eventType, callback, target);
        };
        _proto._initInputSource = function _initInputSource() {
          this._handheldPosition = new InputSourcePosition();
          this._handheldPosition.getValue = function () {
            return Vec3.ZERO;
          };
          this._handheldOrientation = new InputSourceOrientation();
          this._handheldOrientation.getValue = function () {
            return Quat.IDENTITY;
          };
        };
        _createClass(HandheldInputDevice, [{
          key: "handheldPosition",
          get: function get() {
            return this._handheldPosition;
          }
        }, {
          key: "handheldOrientation",
          get: function get() {
            return this._handheldOrientation;
          }
        }]);
        return HandheldInputDevice;
      }();

      var code2KeyCode = {
        Backspace: KeyCode.BACKSPACE,
        Tab: KeyCode.TAB,
        Enter: KeyCode.ENTER,
        ShiftLeft: KeyCode.SHIFT_LEFT,
        ControlLeft: KeyCode.CTRL_LEFT,
        AltLeft: KeyCode.ALT_LEFT,
        ShiftRight: KeyCode.SHIFT_RIGHT,
        ControlRight: KeyCode.CTRL_RIGHT,
        AltRight: KeyCode.ALT_RIGHT,
        Pause: KeyCode.PAUSE,
        CapsLock: KeyCode.CAPS_LOCK,
        Escape: KeyCode.ESCAPE,
        Space: KeyCode.SPACE,
        PageUp: KeyCode.PAGE_UP,
        PageDown: KeyCode.PAGE_DOWN,
        End: KeyCode.END,
        Home: KeyCode.HOME,
        ArrowLeft: KeyCode.ARROW_LEFT,
        ArrowUp: KeyCode.ARROW_UP,
        ArrowRight: KeyCode.ARROW_RIGHT,
        ArrowDown: KeyCode.ARROW_DOWN,
        Insert: KeyCode.INSERT,
        Delete: KeyCode.DELETE,
        Digit0: KeyCode.DIGIT_0,
        Digit1: KeyCode.DIGIT_1,
        Digit2: KeyCode.DIGIT_2,
        Digit3: KeyCode.DIGIT_3,
        Digit4: KeyCode.DIGIT_4,
        Digit5: KeyCode.DIGIT_5,
        Digit6: KeyCode.DIGIT_6,
        Digit7: KeyCode.DIGIT_7,
        Digit8: KeyCode.DIGIT_8,
        Digit9: KeyCode.DIGIT_9,
        KeyA: KeyCode.KEY_A,
        KeyB: KeyCode.KEY_B,
        KeyC: KeyCode.KEY_C,
        KeyD: KeyCode.KEY_D,
        KeyE: KeyCode.KEY_E,
        KeyF: KeyCode.KEY_F,
        KeyG: KeyCode.KEY_G,
        KeyH: KeyCode.KEY_H,
        KeyI: KeyCode.KEY_I,
        KeyJ: KeyCode.KEY_J,
        KeyK: KeyCode.KEY_K,
        KeyL: KeyCode.KEY_L,
        KeyM: KeyCode.KEY_M,
        KeyN: KeyCode.KEY_N,
        KeyO: KeyCode.KEY_O,
        KeyP: KeyCode.KEY_P,
        KeyQ: KeyCode.KEY_Q,
        KeyR: KeyCode.KEY_R,
        KeyS: KeyCode.KEY_S,
        KeyT: KeyCode.KEY_T,
        KeyU: KeyCode.KEY_U,
        KeyV: KeyCode.KEY_V,
        KeyW: KeyCode.KEY_W,
        KeyX: KeyCode.KEY_X,
        KeyY: KeyCode.KEY_Y,
        KeyZ: KeyCode.KEY_Z,
        Numpad0: KeyCode.NUM_0,
        Numpad1: KeyCode.NUM_1,
        Numpad2: KeyCode.NUM_2,
        Numpad3: KeyCode.NUM_3,
        Numpad4: KeyCode.NUM_4,
        Numpad5: KeyCode.NUM_5,
        Numpad6: KeyCode.NUM_6,
        Numpad7: KeyCode.NUM_7,
        Numpad8: KeyCode.NUM_8,
        Numpad9: KeyCode.NUM_9,
        NumpadMultiply: KeyCode.NUM_MULTIPLY,
        NumpadAdd: KeyCode.NUM_PLUS,
        NumpadSubtract: KeyCode.NUM_SUBTRACT,
        NumpadDecimal: KeyCode.NUM_DECIMAL,
        NumpadDivide: KeyCode.NUM_DIVIDE,
        NumpadEnter: KeyCode.NUM_ENTER,
        F1: KeyCode.F1,
        F2: KeyCode.F2,
        F3: KeyCode.F3,
        F4: KeyCode.F4,
        F5: KeyCode.F5,
        F6: KeyCode.F6,
        F7: KeyCode.F7,
        F8: KeyCode.F8,
        F9: KeyCode.F9,
        F10: KeyCode.F10,
        F11: KeyCode.F11,
        F12: KeyCode.F12,
        NumLock: KeyCode.NUM_LOCK,
        ScrollLock: KeyCode.SCROLL_LOCK,
        Semicolon: KeyCode.SEMICOLON,
        Equal: KeyCode.EQUAL,
        Comma: KeyCode.COMMA,
        Minus: KeyCode.DASH,
        Period: KeyCode.PERIOD,
        Slash: KeyCode.SLASH,
        Backquote: KeyCode.BACK_QUOTE,
        BracketLeft: KeyCode.BRACKET_LEFT,
        Backslash: KeyCode.BACKSLASH,
        BracketRight: KeyCode.BRACKET_RIGHT,
        Quote: KeyCode.QUOTE
      };

      function getKeyCode(code) {
        return code2KeyCode[code] || KeyCode.NONE;
      }
      var KeyboardInputSource = function () {
        function KeyboardInputSource() {
          this._eventTarget = new EventTarget();
          this._registerEvent();
        }
        var _proto = KeyboardInputSource.prototype;
        _proto.dispatchKeyboardDownEvent = function dispatchKeyboardDownEvent(nativeKeyboardEvent) {
          this._handleKeyboardDown(nativeKeyboardEvent);
        };
        _proto.dispatchKeyboardUpEvent = function dispatchKeyboardUpEvent(nativeKeyboardEvent) {
          this._handleKeyboardUp(nativeKeyboardEvent);
        };
        _proto.on = function on(eventType, callback, target) {
          this._eventTarget.on(eventType, callback, target);
        };
        _proto._registerEvent = function _registerEvent() {
          var canvas = document.getElementById('GameCanvas');
          canvas === null || canvas === void 0 ? void 0 : canvas.addEventListener('keydown', this._handleKeyboardDown.bind(this));
          canvas === null || canvas === void 0 ? void 0 : canvas.addEventListener('keyup', this._handleKeyboardUp.bind(this));
        };
        _proto._getInputEvent = function _getInputEvent(event, eventType) {
          var keyCode = getKeyCode(event.code);
          var eventKeyboard = new EventKeyboard(keyCode, eventType);
          return eventKeyboard;
        };
        _proto._handleKeyboardDown = function _handleKeyboardDown(event) {
          event.stopPropagation();
          event.preventDefault();
          if (!event.repeat) {
            var keyDownInputEvent = this._getInputEvent(event, InputEventType.KEY_DOWN);
            this._eventTarget.emit(InputEventType.KEY_DOWN, keyDownInputEvent);
          } else {
            var keyPressingInputEvent = this._getInputEvent(event, InputEventType.KEY_PRESSING);
            this._eventTarget.emit(InputEventType.KEY_PRESSING, keyPressingInputEvent);
          }
        };
        _proto._handleKeyboardUp = function _handleKeyboardUp(event) {
          var inputEvent = this._getInputEvent(event, InputEventType.KEY_UP);
          event.stopPropagation();
          event.preventDefault();
          this._eventTarget.emit(InputEventType.KEY_UP, inputEvent);
        };
        return KeyboardInputSource;
      }();

      var MouseInputSource = function () {
        function MouseInputSource() {
          this._canvas = void 0;
          this._eventTarget = new EventTarget();
          this._pointLocked = false;
          this._isPressed = false;
          this._preMousePos = new Vec2();
          this._handleMouseDown = void 0;
          this._handleMouseMove = void 0;
          this._handleMouseUp = void 0;
          if (systemInfo.hasFeature(Feature$1.EVENT_MOUSE)) {
            this._canvas = document.getElementById('GameCanvas');
            if (!this._canvas && !TEST && !EDITOR) {
              console.warn('failed to access canvas');
            }
            this._handleMouseDown = this._createCallback(InputEventType.MOUSE_DOWN);
            this._handleMouseMove = this._createCallback(InputEventType.MOUSE_MOVE);
            this._handleMouseUp = this._createCallback(InputEventType.MOUSE_UP);
            {
              this._registerEvent();
            }
          }
        }
        var _proto = MouseInputSource.prototype;
        _proto.dispatchMouseDownEvent = function dispatchMouseDownEvent(nativeMouseEvent) {
          this._handleMouseDown(nativeMouseEvent);
        };
        _proto.dispatchMouseMoveEvent = function dispatchMouseMoveEvent(nativeMouseEvent) {
          this._handleMouseMove(nativeMouseEvent);
        };
        _proto.dispatchMouseUpEvent = function dispatchMouseUpEvent(nativeMouseEvent) {
          this._handleMouseUp(nativeMouseEvent);
        };
        _proto.dispatchScrollEvent = function dispatchScrollEvent(nativeMouseEvent) {
          this._handleMouseWheel(nativeMouseEvent);
        };
        _proto.on = function on(eventType, callback, target) {
          this._eventTarget.on(eventType, callback, target);
        };
        _proto._getCanvasRect = function _getCanvasRect() {
          var canvas = this._canvas;
          var box = canvas === null || canvas === void 0 ? void 0 : canvas.getBoundingClientRect();
          if (box) {
            return new Rect$1(box.x, box.y, box.width, box.height);
          }
          return new Rect$1(0, 0, 0, 0);
        };
        _proto._getLocation = function _getLocation(mouseEvent) {
          var canvasRect = this._getCanvasRect();
          var dpr = screenAdapter.devicePixelRatio;
          var x = this._pointLocked ? this._preMousePos.x / dpr + mouseEvent.movementX : mouseEvent.clientX - canvasRect.x;
          var y = this._pointLocked ? this._preMousePos.y / dpr - mouseEvent.movementY : canvasRect.y + canvasRect.height - mouseEvent.clientY;
          x *= dpr;
          y *= dpr;
          return new Vec2(x, y);
        };
        _proto._registerEvent = function _registerEvent() {
          var _this = this,
            _this$_canvas,
            _this$_canvas2,
            _this$_canvas3,
            _this$_canvas4;
          window.addEventListener('mousedown', function () {
            _this._isPressed = true;
          });
          (_this$_canvas = this._canvas) === null || _this$_canvas === void 0 ? void 0 : _this$_canvas.addEventListener('mousedown', this._handleMouseDown);
          (_this$_canvas2 = this._canvas) === null || _this$_canvas2 === void 0 ? void 0 : _this$_canvas2.addEventListener('mousemove', this._handleMouseMove);
          window.addEventListener('mouseup', this._handleMouseUp);
          (_this$_canvas3 = this._canvas) === null || _this$_canvas3 === void 0 ? void 0 : _this$_canvas3.addEventListener('mouseup', this._handleMouseUp);
          (_this$_canvas4 = this._canvas) === null || _this$_canvas4 === void 0 ? void 0 : _this$_canvas4.addEventListener('wheel', this._handleMouseWheel.bind(this));
          this._registerPointerLockEvent();
        };
        _proto._registerPointerLockEvent = function _registerPointerLockEvent() {
          var _this2 = this;
          var lockChangeAlert = function lockChangeAlert() {
            var canvas = _this2._canvas;
            if (document.pointerLockElement === canvas || document.mozPointerLockElement === canvas) {
              _this2._pointLocked = true;
            } else {
              _this2._pointLocked = false;
            }
          };
          if ('onpointerlockchange' in document) {
            document.addEventListener('pointerlockchange', lockChangeAlert, false);
          } else if ('onmozpointerlockchange' in document) {
            document.addEventListener('mozpointerlockchange', lockChangeAlert, false);
          }
        };
        _proto._createCallback = function _createCallback(eventType) {
          var _this3 = this;
          return function (mouseEvent) {
            var _this3$_canvas;
            var location = _this3._getLocation(mouseEvent);
            var button = mouseEvent.button,
              buttons = mouseEvent.buttons;
            var targetButton = button;
            switch (eventType) {
              case InputEventType.MOUSE_DOWN:
                (_this3$_canvas = _this3._canvas) === null || _this3$_canvas === void 0 ? void 0 : _this3$_canvas.focus();
                _this3._isPressed = true;
                break;
              case InputEventType.MOUSE_UP:
                _this3._isPressed = false;
                break;
              case InputEventType.MOUSE_MOVE:
                if (1 & buttons) {
                  targetButton = EventMouse.BUTTON_LEFT;
                } else if (2 & buttons) {
                  targetButton = EventMouse.BUTTON_RIGHT;
                } else if (4 & buttons) {
                  targetButton = EventMouse.BUTTON_MIDDLE;
                } else {
                  targetButton = EventMouse.BUTTON_MISSING;
                }
                break;
            }
            var eventMouse = new EventMouse(eventType, false, _this3._preMousePos);
            eventMouse.setLocation(location.x, location.y);
            eventMouse.setButton(targetButton);
            eventMouse.movementX = mouseEvent.movementX;
            eventMouse.movementY = mouseEvent.movementY;
            _this3._preMousePos.set(location.x, location.y);
            mouseEvent.stopPropagation();
            if (mouseEvent.target === _this3._canvas) {
              mouseEvent.preventDefault();
            }
            _this3._eventTarget.emit(eventType, eventMouse);
          };
        };
        _proto._handleMouseWheel = function _handleMouseWheel(mouseEvent) {
          var eventType = InputEventType.MOUSE_WHEEL;
          var location = this._getLocation(mouseEvent);
          var button = mouseEvent.button;
          var eventMouse = new EventMouse(eventType, false, this._preMousePos);
          eventMouse.setLocation(location.x, location.y);
          eventMouse.setButton(button);
          eventMouse.movementX = mouseEvent.movementX;
          eventMouse.movementY = mouseEvent.movementY;
          var wheelSensitivityFactor = 5;
          eventMouse.setScrollData(mouseEvent.deltaX * wheelSensitivityFactor, -mouseEvent.deltaY * wheelSensitivityFactor);
          this._preMousePos.set(location.x, location.y);
          mouseEvent.stopPropagation();
          if (mouseEvent.target === this._canvas) {
            mouseEvent.preventDefault();
          }
          this._eventTarget.emit(eventType, eventMouse);
        };
        return MouseInputSource;
      }();

      var tempVec2 = new Vec2();
      var TouchManager = function () {
        function TouchManager() {
          this._touchMap = void 0;
          this._maxTouches = 8;
          this._touchMap = new Map();
        }
        var _proto = TouchManager.prototype;
        _proto._cloneTouch = function _cloneTouch(touch) {
          var touchID = touch.getID();
          touch.getStartLocation(tempVec2);
          var clonedTouch = new Touch(tempVec2.x, tempVec2.y, touchID);
          touch.getLocation(tempVec2);
          clonedTouch.setPoint(tempVec2.x, tempVec2.y);
          touch.getPreviousLocation(tempVec2);
          clonedTouch.setPrevPoint(tempVec2);
          return clonedTouch;
        };
        _proto._createTouch = function _createTouch(touchID, x, y) {
          if (this._touchMap.has(touchID)) {
            console.log('Cannot create the same touch object.');
            return undefined;
          }
          var checkResult = this._checkTouchMapSizeMoreThanMax(touchID);
          if (checkResult) {
            console.log('The touches is more than MAX_TOUCHES.');
            return undefined;
          }
          var touch = new Touch(x, y, touchID);
          this._touchMap.set(touchID, touch);
          this._updateTouch(touch, x, y);
          return this._cloneTouch(touch);
        };
        _proto.releaseTouch = function releaseTouch(touchID) {
          if (!this._touchMap.has(touchID)) {
            return;
          }
          this._touchMap["delete"](touchID);
        };
        _proto.getTouch = function getTouch(touchID, x, y) {
          var touch = this._touchMap.get(touchID);
          if (!touch) {
            touch = this._createTouch(touchID, x, y);
          } else {
            this._updateTouch(touch, x, y);
          }
          return touch ? this._cloneTouch(touch) : undefined;
        };
        _proto.getAllTouches = function getAllTouches() {
          var _this = this;
          var touches = [];
          this._touchMap.forEach(function (touch) {
            if (touch) {
              var clonedTouch = _this._cloneTouch(touch);
              touches.push(clonedTouch);
            }
          });
          return touches;
        };
        _proto._updateTouch = function _updateTouch(touch, x, y) {
          touch.getLocation(tempVec2);
          touch.setPrevPoint(tempVec2);
          touch.setPoint(x, y);
        };
        _proto._checkTouchMapSizeMoreThanMax = function _checkTouchMapSizeMoreThanMax(touchID) {
          var _this2 = this;
          if (this._touchMap.has(touchID)) {
            return false;
          }
          var maxSize = macro.ENABLE_MULTI_TOUCH ? this._maxTouches : 1;
          if (this._touchMap.size < maxSize) {
            return false;
          }
          var now = performance.now();
          this._touchMap.forEach(function (touch) {
            if (now - touch.lastModified > macro.TOUCH_TIMEOUT) {
              console.log("The touches is more than MAX_TOUCHES, release touch id " + touch.getID() + ".");
              _this2.releaseTouch(touch.getID());
            }
          });
          return maxSize >= this._touchMap.size;
        };
        return TouchManager;
      }();
      var touchManager = new TouchManager();

      var TouchInputSource = function () {
        function TouchInputSource() {
          this._canvas = void 0;
          this._eventTarget = new EventTarget();
          if (systemInfo.hasFeature(Feature$1.INPUT_TOUCH)) {
            this._canvas = document.getElementById('GameCanvas');
            if (!this._canvas && !TEST && !EDITOR) {
              console.warn('failed to access canvas');
            }
            {
              this._registerEvent();
            }
          }
        }
        var _proto = TouchInputSource.prototype;
        _proto._registerEvent = function _registerEvent() {
          var _this$_canvas, _this$_canvas2, _this$_canvas3, _this$_canvas4;
          (_this$_canvas = this._canvas) === null || _this$_canvas === void 0 ? void 0 : _this$_canvas.addEventListener('touchstart', this._createCallback(InputEventType.TOUCH_START));
          (_this$_canvas2 = this._canvas) === null || _this$_canvas2 === void 0 ? void 0 : _this$_canvas2.addEventListener('touchmove', this._createCallback(InputEventType.TOUCH_MOVE));
          (_this$_canvas3 = this._canvas) === null || _this$_canvas3 === void 0 ? void 0 : _this$_canvas3.addEventListener('touchend', this._createCallback(InputEventType.TOUCH_END));
          (_this$_canvas4 = this._canvas) === null || _this$_canvas4 === void 0 ? void 0 : _this$_canvas4.addEventListener('touchcancel', this._createCallback(InputEventType.TOUCH_CANCEL));
        };
        _proto._createCallback = function _createCallback(eventType) {
          var _this = this;
          return function (event) {
            var canvasRect = _this._getCanvasRect();
            var handleTouches = [];
            var length = event.changedTouches.length;
            for (var i = 0; i < length; ++i) {
              var changedTouch = event.changedTouches[i];
              var touchID = changedTouch.identifier;
              if (touchID === null) {
                continue;
              }
              var location = _this._getLocation(changedTouch, canvasRect);
              var touch = touchManager.getTouch(touchID, location.x, location.y);
              if (!touch) {
                continue;
              }
              if (eventType === InputEventType.TOUCH_END || eventType === InputEventType.TOUCH_CANCEL) {
                touchManager.releaseTouch(touchID);
              }
              handleTouches.push(touch);
            }
            event.stopPropagation();
            if (event.target === _this._canvas) {
              event.preventDefault();
            }
            if (eventType === InputEventType.TOUCH_START) {
              var _this$_canvas5;
              (_this$_canvas5 = _this._canvas) === null || _this$_canvas5 === void 0 ? void 0 : _this$_canvas5.focus();
            }
            if (handleTouches.length > 0) {
              var eventTouch = new EventTouch(handleTouches, false, eventType, macro.ENABLE_MULTI_TOUCH ? touchManager.getAllTouches() : handleTouches);
              _this._eventTarget.emit(eventType, eventTouch);
            }
          };
        };
        _proto._getCanvasRect = function _getCanvasRect() {
          var canvas = this._canvas;
          var box = canvas === null || canvas === void 0 ? void 0 : canvas.getBoundingClientRect();
          if (box) {
            return new Rect$1(box.x, box.y, box.width, box.height);
          }
          return new Rect$1(0, 0, 0, 0);
        };
        _proto._getLocation = function _getLocation(touch, canvasRect) {
          if (globalThis.__globalXR && globalThis.__globalXR.ar && globalThis.__globalXR.ar.isWebXR()) {
            return new Vec2(touch.clientX, touch.clientY);
          }
          var x = touch.clientX - canvasRect.x;
          var y = canvasRect.y + canvasRect.height - touch.clientY;
          if (screenAdapter.isFrameRotated) {
            var tmp = x;
            x = canvasRect.height - y;
            y = tmp;
          }
          var dpr = screenAdapter.devicePixelRatio;
          x *= dpr;
          y *= dpr;
          return new Vec2(x, y);
        };
        _proto.on = function on(eventType, callback, target) {
          this._eventTarget.on(eventType, callback, target);
        };
        return TouchInputSource;
      }();

      var _pointerEventTypeMap;
      var EventDispatcherPriority;
      (function (EventDispatcherPriority) {
        EventDispatcherPriority[EventDispatcherPriority["GLOBAL"] = 0] = "GLOBAL";
        EventDispatcherPriority[EventDispatcherPriority["UI"] = 1] = "UI";
      })(EventDispatcherPriority || (EventDispatcherPriority = {}));
      var InputEventDispatcher = function () {
        function InputEventDispatcher(inputEventTarget) {
          this.priority = EventDispatcherPriority.GLOBAL;
          this._inputEventTarget = void 0;
          this._inputEventTarget = inputEventTarget;
        }
        var _proto = InputEventDispatcher.prototype;
        _proto.dispatchEvent = function dispatchEvent(event) {
          this._inputEventTarget.emit(event.type, event);
          return true;
        };
        return InputEventDispatcher;
      }();
      var pointerEventTypeMap = (_pointerEventTypeMap = {}, _pointerEventTypeMap[InputEventType.MOUSE_DOWN] = InputEventType.TOUCH_START, _pointerEventTypeMap[InputEventType.MOUSE_MOVE] = InputEventType.TOUCH_MOVE, _pointerEventTypeMap[InputEventType.MOUSE_UP] = InputEventType.TOUCH_END, _pointerEventTypeMap);
      var Input = exports('eB', function () {
        function Input() {
          this._dispatchImmediately = !NATIVE;
          this._eventTarget = new EventTarget();
          this._touchInput = new TouchInputSource();
          this._mouseInput = new MouseInputSource();
          this._keyboardInput = new KeyboardInputSource();
          this._accelerometerInput = new AccelerometerInputSource();
          this._handleInput = new HandleInputDevice();
          this._hmdInput = new HMDInputDevice();
          this._handheldInput = new HandheldInputDevice();
          this._eventTouchList = [];
          this._eventMouseList = [];
          this._eventKeyboardList = [];
          this._eventAccelerationList = [];
          this._eventGamepadList = [];
          this._eventHandleList = [];
          this._eventHMDList = [];
          this._eventHandheldList = [];
          this._needSimulateTouchMoveEvent = false;
          this._inputEventDispatcher = void 0;
          this._eventDispatcherList = [];
          this._registerEvent();
          this._inputEventDispatcher = new InputEventDispatcher(this._eventTarget);
          this._registerEventDispatcher(this._inputEventDispatcher);
          GamepadInputDevice._init();
        }
        var _proto2 = Input.prototype;
        _proto2._dispatchMouseDownEvent = function _dispatchMouseDownEvent(nativeMouseEvent) {
          var _this$_mouseInput$dis, _this$_mouseInput;
          (_this$_mouseInput$dis = (_this$_mouseInput = this._mouseInput).dispatchMouseDownEvent) === null || _this$_mouseInput$dis === void 0 ? void 0 : _this$_mouseInput$dis.call(_this$_mouseInput, nativeMouseEvent);
        };
        _proto2._dispatchMouseMoveEvent = function _dispatchMouseMoveEvent(nativeMouseEvent) {
          var _this$_mouseInput$dis2, _this$_mouseInput2;
          (_this$_mouseInput$dis2 = (_this$_mouseInput2 = this._mouseInput).dispatchMouseMoveEvent) === null || _this$_mouseInput$dis2 === void 0 ? void 0 : _this$_mouseInput$dis2.call(_this$_mouseInput2, nativeMouseEvent);
        };
        _proto2._dispatchMouseUpEvent = function _dispatchMouseUpEvent(nativeMouseEvent) {
          var _this$_mouseInput$dis3, _this$_mouseInput3;
          (_this$_mouseInput$dis3 = (_this$_mouseInput3 = this._mouseInput).dispatchMouseUpEvent) === null || _this$_mouseInput$dis3 === void 0 ? void 0 : _this$_mouseInput$dis3.call(_this$_mouseInput3, nativeMouseEvent);
        };
        _proto2._dispatchMouseScrollEvent = function _dispatchMouseScrollEvent(nativeMouseEvent) {
          var _this$_mouseInput$dis4, _this$_mouseInput4;
          (_this$_mouseInput$dis4 = (_this$_mouseInput4 = this._mouseInput).dispatchScrollEvent) === null || _this$_mouseInput$dis4 === void 0 ? void 0 : _this$_mouseInput$dis4.call(_this$_mouseInput4, nativeMouseEvent);
        };
        _proto2._dispatchKeyboardDownEvent = function _dispatchKeyboardDownEvent(nativeKeyboardEvent) {
          var _this$_keyboardInput$, _this$_keyboardInput;
          (_this$_keyboardInput$ = (_this$_keyboardInput = this._keyboardInput).dispatchKeyboardDownEvent) === null || _this$_keyboardInput$ === void 0 ? void 0 : _this$_keyboardInput$.call(_this$_keyboardInput, nativeKeyboardEvent);
        };
        _proto2._dispatchKeyboardUpEvent = function _dispatchKeyboardUpEvent(nativeKeyboardEvent) {
          var _this$_keyboardInput$2, _this$_keyboardInput2;
          (_this$_keyboardInput$2 = (_this$_keyboardInput2 = this._keyboardInput).dispatchKeyboardUpEvent) === null || _this$_keyboardInput$2 === void 0 ? void 0 : _this$_keyboardInput$2.call(_this$_keyboardInput2, nativeKeyboardEvent);
        };
        _proto2.on = function on(eventType, callback, target) {
          this._eventTarget.on(eventType, callback, target);
          return callback;
        };
        _proto2.once = function once(eventType, callback, target) {
          this._eventTarget.once(eventType, callback, target);
          return callback;
        };
        _proto2.off = function off(eventType, callback, target) {
          this._eventTarget.off(eventType, callback, target);
        };
        _proto2.setAccelerometerEnabled = function setAccelerometerEnabled(isEnable) {
          if (isEnable) {
            this._accelerometerInput.start();
          } else {
            this._accelerometerInput.stop();
          }
        };
        _proto2.setAccelerometerInterval = function setAccelerometerInterval(intervalInMileSeconds) {
          this._accelerometerInput.setInterval(intervalInMileSeconds);
        };
        _proto2._simulateEventTouch = function _simulateEventTouch(eventMouse) {
          var eventType = pointerEventTypeMap[eventMouse.type];
          var touchID = 0;
          var touch = touchManager.getTouch(touchID, eventMouse.getLocationX(), eventMouse.getLocationY());
          if (!touch) {
            return;
          }
          var changedTouches = [touch];
          var eventTouch = new EventTouch(changedTouches, false, eventType, eventType === InputEventType.TOUCH_END ? [] : changedTouches);
          eventTouch.windowId = eventMouse.windowId;
          if (eventType === InputEventType.TOUCH_END) {
            touchManager.releaseTouch(touchID);
          }
          this._dispatchOrPushEventTouch(eventTouch, this._eventTouchList);
        };
        _proto2._registerEventDispatcher = function _registerEventDispatcher(eventDispatcher) {
          this._eventDispatcherList.push(eventDispatcher);
          this._eventDispatcherList.sort(function (a, b) {
            return b.priority - a.priority;
          });
        };
        _proto2._emitEvent = function _emitEvent(event) {
          var length = this._eventDispatcherList.length;
          for (var i = 0; i < length; ++i) {
            var dispatcher = this._eventDispatcherList[i];
            try {
              if (!dispatcher.dispatchEvent(event)) {
                break;
              }
            } catch (e) {
              console.error("Error occurs in an event listener: " + event.type);
              console.error(e);
            }
          }
        };
        _proto2._registerEvent = function _registerEvent() {
          var _this = this;
          if (sys.hasFeature(sys.Feature.INPUT_TOUCH)) {
            var eventTouchList = this._eventTouchList;
            this._touchInput.on(InputEventType.TOUCH_START, function (event) {
              _this._dispatchOrPushEventTouch(event, eventTouchList);
            });
            this._touchInput.on(InputEventType.TOUCH_MOVE, function (event) {
              _this._dispatchOrPushEventTouch(event, eventTouchList);
            });
            this._touchInput.on(InputEventType.TOUCH_END, function (event) {
              _this._dispatchOrPushEventTouch(event, eventTouchList);
            });
            this._touchInput.on(InputEventType.TOUCH_CANCEL, function (event) {
              _this._dispatchOrPushEventTouch(event, eventTouchList);
            });
          }
          if (sys.hasFeature(sys.Feature.EVENT_MOUSE)) {
            var eventMouseList = this._eventMouseList;
            this._mouseInput.on(InputEventType.MOUSE_DOWN, function (event) {
              _this._needSimulateTouchMoveEvent = true;
              _this._simulateEventTouch(event);
              _this._dispatchOrPushEvent(event, eventMouseList);
            });
            this._mouseInput.on(InputEventType.MOUSE_MOVE, function (event) {
              if (_this._needSimulateTouchMoveEvent) {
                _this._simulateEventTouch(event);
              }
              _this._dispatchOrPushEvent(event, eventMouseList);
            });
            this._mouseInput.on(InputEventType.MOUSE_UP, function (event) {
              _this._needSimulateTouchMoveEvent = false;
              _this._simulateEventTouch(event);
              _this._dispatchOrPushEvent(event, eventMouseList);
            });
            this._mouseInput.on(InputEventType.MOUSE_WHEEL, function (event) {
              _this._dispatchOrPushEvent(event, eventMouseList);
            });
          }
          if (sys.hasFeature(sys.Feature.EVENT_KEYBOARD)) {
            var eventKeyboardList = this._eventKeyboardList;
            this._keyboardInput.on(InputEventType.KEY_DOWN, function (event) {
              _this._dispatchOrPushEvent(event, eventKeyboardList);
            });
            this._keyboardInput.on(InputEventType.KEY_PRESSING, function (event) {
              _this._dispatchOrPushEvent(event, eventKeyboardList);
            });
            this._keyboardInput.on(InputEventType.KEY_UP, function (event) {
              _this._dispatchOrPushEvent(event, eventKeyboardList);
            });
          }
          if (sys.hasFeature(sys.Feature.EVENT_ACCELEROMETER)) {
            var eventAccelerationList = this._eventAccelerationList;
            this._accelerometerInput.on(InputEventType.DEVICEMOTION, function (event) {
              _this._dispatchOrPushEvent(event, eventAccelerationList);
            });
          }
          if (sys.hasFeature(sys.Feature.EVENT_GAMEPAD)) {
            var eventGamepadList = this._eventGamepadList;
            GamepadInputDevice._on(InputEventType.GAMEPAD_CHANGE, function (event) {
              _this._dispatchOrPushEvent(event, eventGamepadList);
            });
            GamepadInputDevice._on(InputEventType.GAMEPAD_INPUT, function (event) {
              _this._dispatchOrPushEvent(event, eventGamepadList);
            });
            GamepadInputDevice._on(InputEventType.HANDLE_POSE_INPUT, function (event) {
              _this._dispatchOrPushEvent(event, eventGamepadList);
            });
          }
          if (sys.hasFeature(sys.Feature.EVENT_HANDLE)) {
            var eventHandleList = this._eventHandleList;
            this._handleInput._on(InputEventType.HANDLE_INPUT, function (event) {
              _this._dispatchOrPushEvent(event, eventHandleList);
            });
            this._handleInput._on(InputEventType.HANDLE_POSE_INPUT, function (event) {
              _this._dispatchOrPushEvent(event, eventHandleList);
            });
          }
          if (sys.hasFeature(sys.Feature.EVENT_HMD)) {
            var eventHMDList = this._eventHMDList;
            this._hmdInput._on(InputEventType.HMD_POSE_INPUT, function (event) {
              _this._dispatchOrPushEvent(event, eventHMDList);
            });
          }
          if (sys.hasFeature(sys.Feature.EVENT_HANDHELD)) {
            var eventHandheldList = this._eventHandheldList;
            this._handheldInput._on(InputEventType.HANDHELD_POSE_INPUT, function (event) {
              _this._dispatchOrPushEvent(event, eventHandheldList);
            });
          }
        };
        _proto2._clearEvents = function _clearEvents() {
          this._eventMouseList.length = 0;
          this._eventTouchList.length = 0;
          this._eventKeyboardList.length = 0;
          this._eventAccelerationList.length = 0;
          this._eventGamepadList.length = 0;
          this._eventHandleList.length = 0;
          this._eventHMDList.length = 0;
        };
        _proto2._dispatchOrPushEvent = function _dispatchOrPushEvent(event, eventList) {
          if (this._dispatchImmediately) {
            this._emitEvent(event);
          } else {
            eventList.push(event);
          }
        };
        _proto2._dispatchOrPushEventTouch = function _dispatchOrPushEventTouch(eventTouch, touchEventList) {
          if (this._dispatchImmediately) {
            var touches = eventTouch.getTouches();
            var touchesLength = touches.length;
            for (var i = 0; i < touchesLength; ++i) {
              eventTouch.touch = touches[i];
              eventTouch.propagationStopped = eventTouch.propagationImmediateStopped = false;
              this._emitEvent(eventTouch);
            }
          } else {
            touchEventList.push(eventTouch);
          }
        };
        _proto2._frameDispatchEvents = function _frameDispatchEvents() {
          var eventHMDList = this._eventHMDList;
          for (var i = 0, length = eventHMDList.length; i < length; ++i) {
            var eventHMD = eventHMDList[i];
            this._emitEvent(eventHMD);
          }
          var eventHandheldList = this._eventHandheldList;
          for (var _i = 0, _length = eventHandheldList.length; _i < _length; ++_i) {
            var eventHandheld = eventHandheldList[_i];
            this._emitEvent(eventHandheld);
          }
          var eventMouseList = this._eventMouseList;
          for (var _i2 = 0, _length2 = eventMouseList.length; _i2 < _length2; ++_i2) {
            var eventMouse = eventMouseList[_i2];
            this._emitEvent(eventMouse);
          }
          var eventTouchList = this._eventTouchList;
          for (var _i3 = 0, _length3 = eventTouchList.length; _i3 < _length3; ++_i3) {
            var eventTouch = eventTouchList[_i3];
            var touches = eventTouch.getTouches();
            var touchesLength = touches.length;
            for (var j = 0; j < touchesLength; ++j) {
              eventTouch.touch = touches[j];
              eventTouch.propagationStopped = eventTouch.propagationImmediateStopped = false;
              this._emitEvent(eventTouch);
            }
          }
          var eventKeyboardList = this._eventKeyboardList;
          for (var _i4 = 0, _length4 = eventKeyboardList.length; _i4 < _length4; ++_i4) {
            var eventKeyboard = eventKeyboardList[_i4];
            this._emitEvent(eventKeyboard);
          }
          var eventAccelerationList = this._eventAccelerationList;
          for (var _i5 = 0, _length5 = eventAccelerationList.length; _i5 < _length5; ++_i5) {
            var eventAcceleration = eventAccelerationList[_i5];
            this._emitEvent(eventAcceleration);
          }
          var eventGamepadList = this._eventGamepadList;
          for (var _i6 = 0, _length6 = eventGamepadList.length; _i6 < _length6; ++_i6) {
            var eventGamepad = eventGamepadList[_i6];
            this._emitEvent(eventGamepad);
          }
          var eventHandleList = this._eventHandleList;
          for (var _i7 = 0, _length7 = eventHandleList.length; _i7 < _length7; ++_i7) {
            var eventHandle = eventHandleList[_i7];
            this._emitEvent(eventHandle);
          }
          this._clearEvents();
        };
        return Input;
      }());
      Input.EventType = InputEventType;
      var input$1 = exports('eA', new Input());

      var SystemEvent = exports('eD', function (_EventTarget) {
        _inheritsLoose(SystemEvent, _EventTarget);
        function SystemEvent() {
          var _this;
          _this = _EventTarget.call(this) || this;
          input$1.on(InputEventType.MOUSE_DOWN, function (e) {
            _this.emit(SystemEventType.MOUSE_DOWN, e);
          });
          input$1.on(InputEventType.MOUSE_MOVE, function (e) {
            _this.emit(SystemEventType.MOUSE_MOVE, e);
          });
          input$1.on(InputEventType.MOUSE_UP, function (e) {
            _this.emit(SystemEventType.MOUSE_UP, e);
          });
          input$1.on(InputEventType.MOUSE_WHEEL, function (e) {
            _this.emit(SystemEventType.MOUSE_WHEEL, e);
          });
          input$1.on(InputEventType.TOUCH_START, function (e) {
            _this.emit(SystemEventType.TOUCH_START, e.touch, e);
          });
          input$1.on(InputEventType.TOUCH_MOVE, function (e) {
            _this.emit(SystemEventType.TOUCH_MOVE, e.touch, e);
          });
          input$1.on(InputEventType.TOUCH_END, function (e) {
            _this.emit(SystemEventType.TOUCH_END, e.touch, e);
          });
          input$1.on(InputEventType.TOUCH_CANCEL, function (e) {
            _this.emit(SystemEventType.TOUCH_CANCEL, e.touch, e);
          });
          input$1.on(InputEventType.KEY_DOWN, function (e) {
            _this.emit(SystemEventType.KEY_DOWN, e);
          });
          input$1.on(InputEventType.KEY_PRESSING, function (e) {
            _this.emit(SystemEventType.KEY_DOWN, e);
          });
          input$1.on(InputEventType.KEY_UP, function (e) {
            _this.emit(SystemEventType.KEY_UP, e);
          });
          input$1.on(InputEventType.DEVICEMOTION, function (e) {
            _this.emit(SystemEventType.DEVICEMOTION, e);
          });
          return _this;
        }
        var _proto = SystemEvent.prototype;
        _proto.setAccelerometerEnabled = function setAccelerometerEnabled(isEnabled) {
          input$1.setAccelerometerEnabled(isEnabled);
        };
        _proto.setAccelerometerInterval = function setAccelerometerInterval(interval) {
          input$1.setAccelerometerInterval(interval);
        };
        _proto.on = function on(type, callback, target, once) {
          _EventTarget.prototype.on.call(this, type, callback, target, once);
          return callback;
        };
        _proto.off = function off(type, callback, target) {
          _EventTarget.prototype.off.call(this, type, callback, target);
        };
        return SystemEvent;
      }(EventTarget));
      SystemEvent.EventType = SystemEventType;
      legacyCC.SystemEvent = SystemEvent;
      var systemEvent = exports('eC', new SystemEvent());
      legacyCC.systemEvent = systemEvent;

      var _dsInfo$1 = new DescriptorSetInfo(null);
      var MAX_PASS_COUNT = 8;
      var SubModel = function () {
        function SubModel() {
          this._device = null;
          this._passes = null;
          this._shaders = null;
          this._subMesh = null;
          this._patches = null;
          this._globalPatches = null;
          this._priority = RenderPriority.DEFAULT;
          this._inputAssembler = null;
          this._descriptorSet = null;
          this._worldBoundDescriptorSet = null;
          this._reflectionTex = null;
          this._reflectionSampler = null;
          this._instancedAttributeBlock = {
            buffer: null,
            views: [],
            attributes: []
          };
          this._instancedWorldMatrixIndex = -1;
          this._instancedSHIndex = -1;
          this._useReflectionProbeType = 0;
        }
        var _proto = SubModel.prototype;
        _proto.initialize = function initialize(subMesh, passes, patches) {
          if (patches === void 0) {
            patches = null;
          }
          var root = legacyCC.director.root;
          this._device = deviceManager.gfxDevice;
          _dsInfo$1.layout = passes[0].localSetLayout;
          this._inputAssembler = this._device.createInputAssembler(subMesh.iaInfo);
          this._descriptorSet = this._device.createDescriptorSet(_dsInfo$1);
          var pipeline = legacyCC.director.root.pipeline;
          var occlusionPass = pipeline.pipelineSceneData.getOcclusionQueryPass();
          if (occlusionPass) {
            var occlusionDSInfo = new DescriptorSetInfo(null);
            occlusionDSInfo.layout = occlusionPass.localSetLayout;
            this._worldBoundDescriptorSet = this._device.createDescriptorSet(occlusionDSInfo);
          }
          this._subMesh = subMesh;
          this._patches = patches ? patches.sort() : null;
          this._passes = passes;
          this._flushPassInfo();
          this.priority = RenderPriority.DEFAULT;
          var r = legacyCC.rendering;
          if ((!r || !r.enableEffectImport) && passes[0].phase === getPhaseID('reflection') || isEnableEffect() && passes[0].phaseID === r.getPhaseID(r.getPassID('default'), 'reflection')) {
            var texWidth = root.mainWindow.width;
            var texHeight = root.mainWindow.height;
            var minSize = 512;
            if (texHeight < texWidth) {
              texWidth = minSize * texWidth / texHeight;
              texHeight = minSize;
            } else {
              texWidth = minSize;
              texHeight = minSize * texHeight / texWidth;
            }
            this._reflectionTex = this._device.createTexture(new TextureInfo(TextureType.TEX2D, TextureUsageBit.STORAGE | TextureUsageBit.TRANSFER_SRC | TextureUsageBit.SAMPLED, Format.RGBA8, texWidth, texHeight));
            this.descriptorSet.bindTexture(UNIFORM_REFLECTION_TEXTURE_BINDING, this._reflectionTex);
            this._reflectionSampler = this._device.getSampler(new SamplerInfo(Filter$1.LINEAR, Filter$1.LINEAR, Filter$1.NONE, Address.CLAMP, Address.CLAMP, Address.CLAMP));
            this.descriptorSet.bindSampler(UNIFORM_REFLECTION_TEXTURE_BINDING, this._reflectionSampler);
            this.descriptorSet.bindTexture(UNIFORM_REFLECTION_STORAGE_BINDING, this._reflectionTex);
          }
        };
        _proto.destroy = function destroy() {
          var _this$_worldBoundDesc;
          this._descriptorSet.destroy();
          this._descriptorSet = null;
          this._inputAssembler.destroy();
          this._inputAssembler = null;
          (_this$_worldBoundDesc = this._worldBoundDescriptorSet) === null || _this$_worldBoundDesc === void 0 ? void 0 : _this$_worldBoundDesc.destroy();
          this._worldBoundDescriptorSet = null;
          this.priority = RenderPriority.DEFAULT;
          this._patches = null;
          this._globalPatches = null;
          this._subMesh = null;
          this._passes = null;
          this._shaders = null;
          if (this._reflectionTex) this._reflectionTex.destroy();
          this._reflectionTex = null;
          this._reflectionSampler = null;
        };
        _proto.update = function update() {
          var _this$_worldBoundDesc2;
          for (var i = 0; i < this._passes.length; ++i) {
            var pass = this._passes[i];
            pass.update();
          }
          this._descriptorSet.update();
          (_this$_worldBoundDesc2 = this._worldBoundDescriptorSet) === null || _this$_worldBoundDesc2 === void 0 ? void 0 : _this$_worldBoundDesc2.update();
        };
        _proto.onPipelineStateChanged = function onPipelineStateChanged() {
          var root = legacyCC.director.root;
          var pipeline = root.pipeline;
          var pipelinePatches = Object.entries(pipeline.macros);
          if (!this._globalPatches && pipelinePatches.length === 0) {
            return;
          } else if (pipelinePatches.length) {
            if (this._globalPatches && pipelinePatches.length === this._globalPatches.length) {
              var globalPatches = Object.entries(this._globalPatches);
              var patchesStateUnchanged = JSON.stringify(pipelinePatches.sort()) === JSON.stringify(globalPatches.sort());
              if (patchesStateUnchanged) return;
            }
          }
          this._globalPatches = pipeline.macros;
          var passes = this._passes;
          if (!passes) {
            return;
          }
          for (var i = 0; i < passes.length; i++) {
            var pass = passes[i];
            pass.beginChangeStatesSilently();
            pass.tryCompile();
            pass.endChangeStatesSilently();
          }
          this._flushPassInfo();
        };
        _proto.onMacroPatchesStateChanged = function onMacroPatchesStateChanged(patches) {
          if (!patches && !this._patches) {
            return;
          } else if (patches) {
            patches = patches.sort();
            if (this._patches && patches.length === this._patches.length) {
              var patchesStateUnchanged = JSON.stringify(patches) === JSON.stringify(this._patches);
              if (patchesStateUnchanged) return;
            }
          }
          this._patches = patches;
          var passes = this._passes;
          if (!passes) {
            return;
          }
          for (var i = 0; i < passes.length; i++) {
            var pass = passes[i];
            pass.beginChangeStatesSilently();
            pass.tryCompile();
            pass.endChangeStatesSilently();
          }
          this._flushPassInfo();
        };
        _proto.onGeometryChanged = function onGeometryChanged() {
          if (!this._subMesh) {
            return;
          }
          var drawInfo = this._subMesh.drawInfo;
          if (this._inputAssembler && drawInfo) {
            var dirtyDrawInfo = this._inputAssembler.drawInfo;
            Object.keys(drawInfo).forEach(function (key) {
              dirtyDrawInfo[key] = drawInfo[key];
            });
            this._inputAssembler.drawInfo = dirtyDrawInfo;
          }
        };
        _proto.getInstancedAttributeIndex = function getInstancedAttributeIndex(name) {
          var attributes = this.instancedAttributeBlock.attributes;
          for (var i = 0; i < attributes.length; i++) {
            if (attributes[i].name === name) {
              return i;
            }
          }
          return -1;
        };
        _proto.updateInstancedWorldMatrix = function updateInstancedWorldMatrix(mat, idx) {
          var attrs = this.instancedAttributeBlock.views;
          var v1 = attrs[idx];
          var v2 = attrs[idx + 1];
          var v3 = attrs[idx + 2];
          v1[0] = mat.m00;
          v1[1] = mat.m01;
          v1[2] = mat.m02;
          v1[3] = mat.m12;
          v2[0] = mat.m04;
          v2[1] = mat.m05;
          v2[2] = mat.m06;
          v2[3] = mat.m13;
          v3[0] = mat.m08;
          v3[1] = mat.m09;
          v3[2] = mat.m10;
          v3[3] = mat.m14;
        };
        _proto.updateInstancedSH = function updateInstancedSH(data, idx) {
          var attrs = this.instancedAttributeBlock.views;
          var count = (UBOSH.SH_QUADRATIC_R_OFFSET - UBOSH.SH_LINEAR_CONST_R_OFFSET) / 4;
          var offset = 0;
          for (var i = idx; i < idx + count; i++) {
            for (var k = 0; k < 4; k++) {
              attrs[i][k] = data[offset++];
            }
          }
        };
        _proto.UpdateInstancedAttributes = function UpdateInstancedAttributes(attributes) {
          this.instancedWorldMatrixIndex = -1;
          this.instancedSHIndex = -1;
          var pass = this.passes[0];
          if (!pass.device.hasFeature(Feature.INSTANCED_ARRAYS)) {
            return;
          }
          var size = 0;
          for (var j = 0; j < attributes.length; j++) {
            var attribute = attributes[j];
            if (!attribute.isInstanced) {
              continue;
            }
            size += FormatInfos[attribute.format].size;
          }
          var attrs = this.instancedAttributeBlock;
          attrs.buffer = new Uint8Array(size);
          attrs.views.length = attrs.attributes.length = 0;
          var offset = 0;
          for (var _j = 0; _j < attributes.length; _j++) {
            var _attribute = attributes[_j];
            if (!_attribute.isInstanced) {
              continue;
            }
            var attr = new Attribute();
            attr.format = _attribute.format;
            attr.name = _attribute.name;
            attr.isNormalized = _attribute.isNormalized;
            attr.location = _attribute.location;
            attrs.attributes.push(attr);
            var info = FormatInfos[_attribute.format];
            var typeViewArray = new (getTypedArrayConstructor(info))(attrs.buffer.buffer, offset, info.count);
            attrs.views.push(typeViewArray);
            offset += info.size;
          }
          if (pass.batchingScheme === BatchingSchemes.INSTANCING) {
            pass.getInstancedBuffer().destroy();
          }
          this.instancedWorldMatrixIndex = this.getInstancedAttributeIndex(INST_MAT_WORLD);
          this.instancedSHIndex = this.getInstancedAttributeIndex(INST_SH);
        };
        _proto._flushPassInfo = function _flushPassInfo() {
          var passes = this._passes;
          if (!passes) {
            return;
          }
          if (!this._shaders) {
            this._shaders = [];
          }
          this._shaders.length = passes.length;
          for (var i = 0, len = passes.length; i < len; i++) {
            this._shaders[i] = passes[i].getShaderVariant(this.patches);
          }
        };
        _createClass(SubModel, [{
          key: "passes",
          get: function get() {
            return this._passes;
          },
          set: function set(passes) {
            var passLengh = passes.length;
            if (passLengh > MAX_PASS_COUNT) {
              errorID(12004, MAX_PASS_COUNT);
              return;
            }
            this._passes = passes;
            this._flushPassInfo();
            if (this._descriptorSet) {
              this._descriptorSet.destroy();
              _dsInfo$1.layout = passes[0].localSetLayout;
              this._descriptorSet = this._device.createDescriptorSet(_dsInfo$1);
            }
          }
        }, {
          key: "shaders",
          get: function get() {
            return this._shaders;
          }
        }, {
          key: "subMesh",
          get: function get() {
            return this._subMesh;
          },
          set: function set(subMesh) {
            this._inputAssembler.destroy();
            this._inputAssembler = this._device.createInputAssembler(subMesh.iaInfo);
            this._subMesh = subMesh;
          }
        }, {
          key: "priority",
          get: function get() {
            return this._priority;
          },
          set: function set(val) {
            this._priority = val;
          }
        }, {
          key: "inputAssembler",
          get: function get() {
            return this._inputAssembler;
          }
        }, {
          key: "descriptorSet",
          get: function get() {
            return this._descriptorSet;
          }
        }, {
          key: "worldBoundDescriptorSet",
          get: function get() {
            return this._worldBoundDescriptorSet;
          }
        }, {
          key: "patches",
          get: function get() {
            return this._patches;
          }
        }, {
          key: "instancedAttributeBlock",
          get: function get() {
            return this._instancedAttributeBlock;
          }
        }, {
          key: "instancedWorldMatrixIndex",
          get: function get() {
            return this._instancedWorldMatrixIndex;
          },
          set: function set(val) {
            this._instancedWorldMatrixIndex = val;
          }
        }, {
          key: "instancedSHIndex",
          get: function get() {
            return this._instancedSHIndex;
          },
          set: function set(val) {
            this._instancedSHIndex = val;
          }
        }, {
          key: "useReflectionProbeType",
          get: function get() {
            return this._useReflectionProbeType;
          },
          set: function set(val) {
            this._useReflectionProbeType = val;
          }
        }]);
        return SubModel;
      }();

      var ReflectionProbeType; exports('ah', ReflectionProbeType);
      (function (ReflectionProbeType) {
        ReflectionProbeType[ReflectionProbeType["NONE"] = 0] = "NONE";
        ReflectionProbeType[ReflectionProbeType["BAKED_CUBEMAP"] = 1] = "BAKED_CUBEMAP";
        ReflectionProbeType[ReflectionProbeType["PLANAR_REFLECTION"] = 2] = "PLANAR_REFLECTION";
        ReflectionProbeType[ReflectionProbeType["BLEND_PROBES"] = 3] = "BLEND_PROBES";
        ReflectionProbeType[ReflectionProbeType["BLEND_PROBES_AND_SKYBOX"] = 4] = "BLEND_PROBES_AND_SKYBOX";
      })(ReflectionProbeType || (exports('ah', ReflectionProbeType = {})));

      var m4_1$6 = new Mat4();
      var shadowMapPatches = [{
        name: 'CC_RECEIVE_SHADOW',
        value: true
      }];
      var staticLightMapPatches = [{
        name: 'CC_USE_LIGHTMAP',
        value: 1
      }];
      var stationaryLightMapPatches = [{
        name: 'CC_USE_LIGHTMAP',
        value: 2
      }];
      var highpLightMapPatches = [{
        name: 'CC_LIGHT_MAP_VERSION',
        value: 2
      }];
      var lightProbePatches = [{
        name: 'CC_USE_LIGHT_PROBE',
        value: true
      }];
      var CC_USE_REFLECTION_PROBE = 'CC_USE_REFLECTION_PROBE';
      var CC_DISABLE_DIRECTIONAL_LIGHT = 'CC_DISABLE_DIRECTIONAL_LIGHT';
      var ModelType;
      (function (ModelType) {
        ModelType[ModelType["DEFAULT"] = 0] = "DEFAULT";
        ModelType[ModelType["SKINNING"] = 1] = "SKINNING";
        ModelType[ModelType["BAKED_SKINNING"] = 2] = "BAKED_SKINNING";
        ModelType[ModelType["BATCH_2D"] = 3] = "BATCH_2D";
        ModelType[ModelType["PARTICLE_BATCH"] = 4] = "PARTICLE_BATCH";
        ModelType[ModelType["LINE"] = 5] = "LINE";
      })(ModelType || (ModelType = {}));
      var lightmapSamplerHash = new SamplerInfo(Filter$1.LINEAR, Filter$1.LINEAR, Filter$1.NONE, Address.CLAMP, Address.CLAMP, Address.CLAMP);
      var lightmapSamplerWithMipHash = new SamplerInfo(Filter$1.LINEAR, Filter$1.LINEAR, Filter$1.LINEAR, Address.CLAMP, Address.CLAMP, Address.CLAMP);
      var Model = function () {
        function Model() {
          this.type = ModelType.DEFAULT;
          this.scene = null;
          this.isDynamicBatching = false;
          this._worldBounds = null;
          this._modelBounds = null;
          this._subModels = [];
          this._node = null;
          this._transform = null;
          this._device = void 0;
          this._inited = false;
          this._descriptorSetCount = 1;
          this._updateStamp = -1;
          this._localDataUpdated = true;
          this._localData = new Float32Array(UBOLocal.COUNT);
          this._localBuffer = null;
          this._localSHData = null;
          this._localSHBuffer = null;
          this._lightmap = null;
          this._lightmapUVParam = new Vec4();
          this._tetrahedronIndex = -1;
          this._lastWorldBoundCenter = new Vec3(Infinity, Infinity, Infinity);
          this._useLightProbe = false;
          this._worldBoundBuffer = null;
          this._receiveShadow = false;
          this._castShadow = false;
          this._receiveDirLight = true;
          this._shadowBias = 0;
          this._shadowNormalBias = 0;
          this._reflectionProbeId = -1;
          this._reflectionProbeBlendId = -1;
          this._reflectionProbeBlendWeight = 0;
          this._enabled = true;
          this._visFlags = Layers.Enum.NONE;
          this._priority = 0;
          this._bakeToReflectionProbe = true;
          this._reflectionProbeType = ReflectionProbeType.NONE;
          this._device = deviceManager.gfxDevice;
        }
        var _proto = Model.prototype;
        _proto.initialize = function initialize() {
          if (this._inited) {
            return;
          }
          this._receiveShadow = true;
          this.castShadow = false;
          this.enabled = true;
          this.visFlags = Layers.Enum.NONE;
          this._inited = true;
          this._bakeToReflectionProbe = true;
          this._reflectionProbeType = ReflectionProbeType.NONE;
        };
        _proto.destroy = function destroy() {
          var subModels = this._subModels;
          for (var i = 0; i < subModels.length; i++) {
            this._subModels[i].destroy();
          }
          if (this._localBuffer) {
            this._localBuffer.destroy();
            this._localBuffer = null;
          }
          if (this._localSHBuffer) {
            this._localSHBuffer.destroy();
            this._localSHBuffer = null;
          }
          if (this._worldBoundBuffer) {
            this._worldBoundBuffer.destroy();
            this._worldBoundBuffer = null;
          }
          this._worldBounds = null;
          this._modelBounds = null;
          this._subModels.length = 0;
          this._inited = false;
          this._localDataUpdated = true;
          this._transform = null;
          this._node = null;
          this.isDynamicBatching = false;
        };
        _proto.attachToScene = function attachToScene(scene) {
          this.scene = scene;
          this._localDataUpdated = true;
        };
        _proto.detachFromScene = function detachFromScene() {
          this.scene = null;
        };
        _proto.updateTransform = function updateTransform(stamp) {
          var node = this.transform;
          if (node.hasChangedFlags || node.isTransformDirty()) {
            node.updateWorldTransform();
            this._localDataUpdated = true;
            var worldBounds = this._worldBounds;
            if (this._modelBounds && worldBounds) {
              this._modelBounds.transform(node._mat, node._pos, node._rot, node._scale, worldBounds);
            }
          }
        };
        _proto.updateWorldBound = function updateWorldBound() {
          var node = this.transform;
          if (node !== null) {
            node.updateWorldTransform();
            this._localDataUpdated = true;
            var worldBounds = this._worldBounds;
            if (this._modelBounds && worldBounds) {
              this._modelBounds.transform(node._mat, node._pos, node._rot, node._scale, worldBounds);
            }
          }
        };
        _proto.updateUBOs = function updateUBOs(stamp) {
          var subModels = this._subModels;
          for (var i = 0; i < subModels.length; i++) {
            subModels[i].update();
          }
          this._updateStamp = stamp;
          this.updateSHUBOs();
          var forceUpdateUBO = this.node.scene.globals.shadows.enabled && this.node.scene.globals.shadows.type === ShadowType.Planar;
          if (!this._localDataUpdated) {
            return;
          }
          this._localDataUpdated = false;
          var worldMatrix = this.transform._mat;
          var hasNonInstancingPass = false;
          for (var _i = 0; _i < subModels.length; _i++) {
            var subModel = subModels[_i];
            var idx = subModel.instancedWorldMatrixIndex;
            if (idx >= 0) {
              subModel.updateInstancedWorldMatrix(worldMatrix, idx);
            } else {
              hasNonInstancingPass = true;
            }
          }
          if ((hasNonInstancingPass || forceUpdateUBO) && this._localBuffer) {
            Mat4.toArray(this._localData, worldMatrix, UBOLocal.MAT_WORLD_OFFSET);
            Mat4.invert(m4_1$6, worldMatrix);
            Mat4.transpose(m4_1$6, m4_1$6);
            Mat4.toArray(this._localData, m4_1$6, UBOLocal.MAT_WORLD_IT_OFFSET);
            this._localBuffer.update(this._localData);
          }
        };
        _proto.invalidateLocalData = function invalidateLocalData() {
          this._localDataUpdated = true;
        };
        _proto.showTetrahedron = function showTetrahedron() {
          return this.isLightProbeAvailable();
        };
        _proto.isLightProbeAvailable = function isLightProbeAvailable() {
          if (!this._useLightProbe) {
            return false;
          }
          var lightProbes = legacyCC.director.root.pipeline.pipelineSceneData.lightProbes;
          if (!lightProbes || lightProbes.empty()) {
            return false;
          }
          if (!this._worldBounds) {
            return false;
          }
          return true;
        };
        _proto.updateSHBuffer = function updateSHBuffer() {
          if (!this._localSHData) {
            return;
          }
          var subModels = this._subModels;
          var hasNonInstancingPass = false;
          for (var i = 0; i < subModels.length; i++) {
            var subModel = subModels[i];
            var idx = subModel.instancedSHIndex;
            if (idx >= 0) {
              subModel.updateInstancedSH(this._localSHData, idx);
            } else {
              hasNonInstancingPass = true;
            }
          }
          if (hasNonInstancingPass && this._localSHBuffer) {
            this._localSHBuffer.update(this._localSHData);
          }
        };
        _proto.clearSHUBOs = function clearSHUBOs() {
          if (!this._localSHData) {
            return;
          }
          for (var i = 0; i < UBOSH.COUNT; i++) {
            this._localSHData[i] = 0.0;
          }
          this.updateSHBuffer();
        };
        _proto.updateSHUBOs = function updateSHUBOs() {
          if (!this.isLightProbeAvailable()) {
            return;
          }
          var center = this._worldBounds.center;
          if (center.equals(this._lastWorldBoundCenter, EPSILON$3)) {
            return;
          }
          var coefficients = [];
          var weights = new Vec4(0.0, 0.0, 0.0, 0.0);
          var lightProbes = legacyCC.director.root.pipeline.pipelineSceneData.lightProbes;
          this._lastWorldBoundCenter.set(center);
          this._tetrahedronIndex = lightProbes.data.getInterpolationWeights(center, this._tetrahedronIndex, weights);
          var result = lightProbes.data.getInterpolationSHCoefficients(this._tetrahedronIndex, weights, coefficients);
          if (!result) {
            return;
          }
          if (!this._localSHData) {
            return;
          }
          legacyCC.internal.SH.reduceRinging(coefficients, lightProbes.reduceRinging);
          legacyCC.internal.SH.updateUBOData(this._localSHData, UBOSH.SH_LINEAR_CONST_R_OFFSET, coefficients);
          this.updateSHBuffer();
        };
        _proto.createBoundingShape = function createBoundingShape(minPos, maxPos) {
          if (!minPos || !maxPos) {
            return;
          }
          if (!this._modelBounds) {
            this._modelBounds = AABB.create();
          }
          if (!this._worldBounds) {
            this._worldBounds = AABB.create();
          }
          AABB.fromPoints(this._modelBounds, minPos, maxPos);
          AABB.copy(this._worldBounds, this._modelBounds);
        };
        _proto._createSubModel = function _createSubModel() {
          return new SubModel();
        };
        _proto.initSubModel = function initSubModel(idx, subMeshData, mat) {
          this.initialize();
          if (this._subModels[idx] == null) {
            this._subModels[idx] = this._createSubModel();
          } else {
            this._subModels[idx].destroy();
          }
          this._subModels[idx].initialize(subMeshData, mat.passes, this.getMacroPatches(idx));
          this._updateAttributesAndBinding(idx);
        };
        _proto.setSubModelMesh = function setSubModelMesh(idx, subMesh) {
          if (!this._subModels[idx]) {
            return;
          }
          this._subModels[idx].subMesh = subMesh;
        };
        _proto.setSubModelMaterial = function setSubModelMaterial(idx, mat) {
          if (!this._subModels[idx]) {
            return;
          }
          this._subModels[idx].passes = mat.passes;
          this._updateAttributesAndBinding(idx);
        };
        _proto.onGlobalPipelineStateChanged = function onGlobalPipelineStateChanged() {
          var subModels = this._subModels;
          for (var i = 0; i < subModels.length; i++) {
            subModels[i].onPipelineStateChanged();
          }
        };
        _proto.onMacroPatchesStateChanged = function onMacroPatchesStateChanged() {
          var subModels = this._subModels;
          for (var i = 0; i < subModels.length; i++) {
            subModels[i].onMacroPatchesStateChanged(this.getMacroPatches(i));
          }
        };
        _proto.onGeometryChanged = function onGeometryChanged() {
          var subModels = this._subModels;
          for (var i = 0; i < subModels.length; i++) {
            subModels[i].onGeometryChanged();
          }
        };
        _proto.initLightingmap = function initLightingmap(texture, uvParam) {
          this._lightmap = texture;
          this._lightmapUVParam = uvParam;
        };
        _proto.updateLightingmap = function updateLightingmap(texture, uvParam) {
          Vec4.toArray(this._localData, uvParam, UBOLocal.LIGHTINGMAP_UVPARAM);
          this._localDataUpdated = true;
          this._lightmap = texture;
          this._lightmapUVParam = uvParam;
          this.onMacroPatchesStateChanged();
          if (!texture) {
            texture = builtinResMgr.get('empty-texture');
          }
          var gfxTexture = texture.getGFXTexture();
          if (gfxTexture) {
            var sampler = this._device.getSampler(texture.mipmaps.length > 1 ? lightmapSamplerWithMipHash : lightmapSamplerHash);
            var subModels = this._subModels;
            for (var i = 0; i < subModels.length; i++) {
              var descriptorSet = subModels[i].descriptorSet;
              descriptorSet.bindTexture(UNIFORM_LIGHTMAP_TEXTURE_BINDING, gfxTexture);
              descriptorSet.bindSampler(UNIFORM_LIGHTMAP_TEXTURE_BINDING, sampler);
              descriptorSet.update();
            }
          }
        };
        _proto.updateReflectionProbeCubemap = function updateReflectionProbeCubemap(texture) {
          this._localDataUpdated = true;
          this.onMacroPatchesStateChanged();
          if (!texture) {
            texture = builtinResMgr.get('default-cube-texture');
          }
          var gfxTexture = texture.getGFXTexture();
          if (gfxTexture) {
            var reflectionSampler = this._device.getSampler(texture.getSamplerInfo());
            var subModels = this._subModels;
            for (var i = 0; i < subModels.length; i++) {
              var descriptorSet = subModels[i].descriptorSet;
              if (descriptorSet) {
                descriptorSet.bindSampler(UNIFORM_REFLECTION_PROBE_CUBEMAP_BINDING, reflectionSampler);
                descriptorSet.bindTexture(UNIFORM_REFLECTION_PROBE_CUBEMAP_BINDING, gfxTexture);
                descriptorSet.update();
              }
            }
          }
        };
        _proto.updateReflectionProbeBlendCubemap = function updateReflectionProbeBlendCubemap(texture) {
          this._localDataUpdated = true;
          this.onMacroPatchesStateChanged();
          if (!texture) {
            texture = builtinResMgr.get('default-cube-texture');
          }
          var gfxTexture = texture.getGFXTexture();
          if (gfxTexture) {
            var reflectionSampler = this._device.getSampler(texture.getSamplerInfo());
            var subModels = this._subModels;
            for (var i = 0; i < subModels.length; i++) {
              var descriptorSet = subModels[i].descriptorSet;
              if (descriptorSet) {
                descriptorSet.bindSampler(UNIFORM_REFLECTION_PROBE_BLEND_CUBEMAP_BINDING, reflectionSampler);
                descriptorSet.bindTexture(UNIFORM_REFLECTION_PROBE_BLEND_CUBEMAP_BINDING, gfxTexture);
                descriptorSet.update();
              }
            }
          }
        };
        _proto.updateReflectionProbePlanarMap = function updateReflectionProbePlanarMap(texture) {
          this._localDataUpdated = true;
          this.onMacroPatchesStateChanged();
          var sampler = this._device.getSampler(new SamplerInfo(Filter$1.LINEAR, Filter$1.LINEAR, Filter$1.NONE, Address.CLAMP, Address.CLAMP, Address.CLAMP));
          if (!texture) {
            texture = builtinResMgr.get('empty-texture').getGFXTexture();
          }
          if (texture) {
            var subModels = this._subModels;
            for (var i = 0; i < subModels.length; i++) {
              var descriptorSet = subModels[i].descriptorSet;
              if (descriptorSet) {
                descriptorSet.bindTexture(UNIFORM_REFLECTION_PROBE_TEXTURE_BINDING, texture);
                descriptorSet.bindSampler(UNIFORM_REFLECTION_PROBE_TEXTURE_BINDING, sampler);
                descriptorSet.update();
              }
            }
          }
        };
        _proto.updateReflectionProbeDataMap = function updateReflectionProbeDataMap(texture) {
          this._localDataUpdated = true;
          this.onMacroPatchesStateChanged();
          if (!texture) {
            texture = builtinResMgr.get('empty-texture');
          }
          var gfxTexture = texture.getGFXTexture();
          if (gfxTexture) {
            var subModels = this._subModels;
            for (var i = 0; i < subModels.length; i++) {
              var descriptorSet = subModels[i].descriptorSet;
              if (descriptorSet) {
                descriptorSet.bindTexture(UNIFORM_REFLECTION_PROBE_DATA_MAP_BINDING, gfxTexture);
                descriptorSet.bindSampler(UNIFORM_REFLECTION_PROBE_DATA_MAP_BINDING, texture.getGFXSampler());
                descriptorSet.update();
              }
            }
          }
        };
        _proto.updateLocalShadowBias = function updateLocalShadowBias() {
          var sv = this._localData;
          sv[UBOLocal.LOCAL_SHADOW_BIAS + 0] = this._shadowBias;
          sv[UBOLocal.LOCAL_SHADOW_BIAS + 1] = this._shadowNormalBias;
          this._localDataUpdated = true;
        };
        _proto.updateReflectionProbeId = function updateReflectionProbeId() {
          var sv = this._localData;
          sv[UBOLocal.LOCAL_SHADOW_BIAS + 2] = this._reflectionProbeId;
          sv[UBOLocal.LOCAL_SHADOW_BIAS + 3] = this._reflectionProbeBlendId;
          var probe = null;
          var blendProbe = null;
          if (legacyCC.internal.reflectionProbeManager) {
            probe = legacyCC.internal.reflectionProbeManager.getProbeById(this._reflectionProbeId);
            blendProbe = legacyCC.internal.reflectionProbeManager.getProbeById(this._reflectionProbeBlendId);
          }
          if (probe) {
            if (probe.probeType === ProbeType.PLANAR) {
              sv[UBOLocal.REFLECTION_PROBE_DATA1] = probe.node.up.x;
              sv[UBOLocal.REFLECTION_PROBE_DATA1 + 1] = probe.node.up.y;
              sv[UBOLocal.REFLECTION_PROBE_DATA1 + 2] = probe.node.up.z;
              sv[UBOLocal.REFLECTION_PROBE_DATA1 + 3] = 1.0;
              sv[UBOLocal.REFLECTION_PROBE_DATA2] = 1.0;
              sv[UBOLocal.REFLECTION_PROBE_DATA2 + 1] = 0.0;
              sv[UBOLocal.REFLECTION_PROBE_DATA2 + 2] = 0.0;
              sv[UBOLocal.REFLECTION_PROBE_DATA2 + 3] = 1.0;
            } else {
              sv[UBOLocal.REFLECTION_PROBE_DATA1] = probe.node.worldPosition.x;
              sv[UBOLocal.REFLECTION_PROBE_DATA1 + 1] = probe.node.worldPosition.y;
              sv[UBOLocal.REFLECTION_PROBE_DATA1 + 2] = probe.node.worldPosition.z;
              sv[UBOLocal.REFLECTION_PROBE_DATA1 + 3] = 0.0;
              sv[UBOLocal.REFLECTION_PROBE_DATA2] = probe.size.x;
              sv[UBOLocal.REFLECTION_PROBE_DATA2 + 1] = probe.size.y;
              sv[UBOLocal.REFLECTION_PROBE_DATA2 + 2] = probe.size.z;
              var mipAndUseRGBE = probe.isRGBE() ? 1000 : 0;
              sv[UBOLocal.REFLECTION_PROBE_DATA2 + 3] = probe.cubemap ? probe.cubemap.mipmapLevel + mipAndUseRGBE : 1.0 + mipAndUseRGBE;
            }
            if (this._reflectionProbeType === ReflectionProbeType.BLEND_PROBES || this._reflectionProbeType === ReflectionProbeType.BLEND_PROBES_AND_SKYBOX) {
              if (blendProbe) {
                sv[UBOLocal.REFLECTION_PROBE_BLEND_DATA1] = blendProbe.node.worldPosition.x;
                sv[UBOLocal.REFLECTION_PROBE_BLEND_DATA1 + 1] = blendProbe.node.worldPosition.y;
                sv[UBOLocal.REFLECTION_PROBE_BLEND_DATA1 + 2] = blendProbe.node.worldPosition.z;
                sv[UBOLocal.REFLECTION_PROBE_BLEND_DATA1 + 3] = this.reflectionProbeBlendWeight;
                sv[UBOLocal.REFLECTION_PROBE_BLEND_DATA2] = blendProbe.size.x;
                sv[UBOLocal.REFLECTION_PROBE_BLEND_DATA2 + 1] = blendProbe.size.y;
                sv[UBOLocal.REFLECTION_PROBE_BLEND_DATA2 + 2] = blendProbe.size.z;
                var _mipAndUseRGBE = blendProbe.isRGBE() ? 1000 : 0;
                sv[UBOLocal.REFLECTION_PROBE_BLEND_DATA2 + 3] = blendProbe.cubemap ? blendProbe.cubemap.mipmapLevel + _mipAndUseRGBE : 1.0 + _mipAndUseRGBE;
              } else if (this._reflectionProbeType === ReflectionProbeType.BLEND_PROBES_AND_SKYBOX) {
                sv[UBOLocal.REFLECTION_PROBE_BLEND_DATA1 + 3] = this.reflectionProbeBlendWeight;
              }
            }
          }
          this._localDataUpdated = true;
        };
        _proto.getMacroPatches = function getMacroPatches(subModelIndex) {
          var patches = this.receiveShadow ? shadowMapPatches : null;
          if (this._lightmap != null) {
            if (this.node && this.node.scene && !this.node.scene.globals.disableLightmap) {
              var mainLightIsStationary = this.node.scene.globals.bakedWithStationaryMainLight;
              var lightmapPathes = mainLightIsStationary ? stationaryLightMapPatches : staticLightMapPatches;
              patches = patches ? patches.concat(lightmapPathes) : lightmapPathes;
              if (this.node.scene.globals.bakedWithHighpLightmap) {
                patches = patches.concat(highpLightMapPatches);
              }
            }
          }
          if (this._useLightProbe) {
            patches = patches ? patches.concat(lightProbePatches) : lightProbePatches;
          }
          var reflectionProbePatches = [{
            name: CC_USE_REFLECTION_PROBE,
            value: this._reflectionProbeType
          }];
          patches = patches ? patches.concat(reflectionProbePatches) : reflectionProbePatches;
          var receiveDirLightPatches = [{
            name: CC_DISABLE_DIRECTIONAL_LIGHT,
            value: !this._receiveDirLight
          }];
          patches = patches ? patches.concat(receiveDirLightPatches) : receiveDirLightPatches;
          return patches;
        };
        _proto._updateAttributesAndBinding = function _updateAttributesAndBinding(subModelIndex) {
          var subModel = this._subModels[subModelIndex];
          if (!subModel) {
            return;
          }
          this._initLocalDescriptors(subModelIndex);
          this._updateLocalDescriptors(subModelIndex, subModel.descriptorSet);
          this._initLocalSHDescriptors(subModelIndex);
          this._updateLocalSHDescriptors(subModelIndex, subModel.descriptorSet);
          this._initWorldBoundDescriptors(subModelIndex);
          if (subModel.worldBoundDescriptorSet) {
            this._updateWorldBoundDescriptors(subModelIndex, subModel.worldBoundDescriptorSet);
          }
          var attributes = [];
          var attributeSet = new Set();
          for (var _iterator = _createForOfIteratorHelperLoose(subModel.passes), _step; !(_step = _iterator()).done;) {
            var pass = _step.value;
            var shader = pass.getShaderVariant(subModel.patches);
            for (var _iterator2 = _createForOfIteratorHelperLoose(shader.attributes), _step2; !(_step2 = _iterator2()).done;) {
              var attr = _step2.value;
              if (!attributeSet.has(attr.name)) {
                attributes.push(attr);
                attributeSet.add(attr.name);
              }
            }
          }
          this._updateInstancedAttributes(attributes, subModel);
        };
        _proto._updateInstancedAttributes = function _updateInstancedAttributes(attributes, subModel) {
          subModel.UpdateInstancedAttributes(attributes);
          this._localDataUpdated = true;
        };
        _proto._initLocalDescriptors = function _initLocalDescriptors(subModelIndex) {
          if (!this._localBuffer) {
            this._localBuffer = this._device.createBuffer(new BufferInfo(BufferUsageBit.UNIFORM | BufferUsageBit.TRANSFER_DST, MemoryUsageBit.DEVICE, UBOLocal.SIZE, UBOLocal.SIZE));
          }
        };
        _proto._initLocalSHDescriptors = function _initLocalSHDescriptors(subModelIndex) {
          if (!this._useLightProbe) {
            return;
          }
          if (!this._localSHData) {
            this._localSHData = new Float32Array(UBOSH.COUNT);
          }
          if (!this._localSHBuffer) {
            this._localSHBuffer = this._device.createBuffer(new BufferInfo(BufferUsageBit.UNIFORM | BufferUsageBit.TRANSFER_DST, MemoryUsageBit.DEVICE, UBOSH.SIZE, UBOSH.SIZE));
          }
        };
        _proto._initWorldBoundDescriptors = function _initWorldBoundDescriptors(subModelIndex) {
          if (!this._worldBoundBuffer) {
            this._worldBoundBuffer = this._device.createBuffer(new BufferInfo(BufferUsageBit.UNIFORM | BufferUsageBit.TRANSFER_DST, MemoryUsageBit.DEVICE, UBOWorldBound.SIZE, UBOWorldBound.SIZE));
          }
        };
        _proto._updateLocalDescriptors = function _updateLocalDescriptors(subModelIndex, descriptorSet) {
          if (this._localBuffer) descriptorSet.bindBuffer(UBOLocal.BINDING, this._localBuffer);
        };
        _proto._updateLocalSHDescriptors = function _updateLocalSHDescriptors(subModelIndex, descriptorSet) {
          if (this._localSHBuffer) descriptorSet.bindBuffer(UBOSH.BINDING, this._localSHBuffer);
        };
        _proto._updateWorldBoundDescriptors = function _updateWorldBoundDescriptors(subModelIndex, descriptorSet) {
          if (this._worldBoundBuffer) descriptorSet.bindBuffer(UBOWorldBound.BINDING, this._worldBoundBuffer);
        };
        _createClass(Model, [{
          key: "subModels",
          get: function get() {
            return this._subModels;
          }
        }, {
          key: "inited",
          get: function get() {
            return this._inited;
          }
        }, {
          key: "worldBounds",
          get: function get() {
            return this._worldBounds;
          }
        }, {
          key: "modelBounds",
          get: function get() {
            return this._modelBounds;
          }
        }, {
          key: "localBuffer",
          get: function get() {
            return this._localBuffer;
          }
        }, {
          key: "localSHBuffer",
          get: function get() {
            return this._localSHBuffer;
          }
        }, {
          key: "worldBoundBuffer",
          get: function get() {
            return this._worldBoundBuffer;
          }
        }, {
          key: "updateStamp",
          get: function get() {
            return this._updateStamp;
          }
        }, {
          key: "useLightProbe",
          get: function get() {
            return this._useLightProbe;
          },
          set: function set(val) {
            this._useLightProbe = val;
            this.onMacroPatchesStateChanged();
          }
        }, {
          key: "tetrahedronIndex",
          get: function get() {
            return this._tetrahedronIndex;
          },
          set: function set(index) {
            this._tetrahedronIndex = index;
          }
        }, {
          key: "shadowBias",
          get: function get() {
            return this._shadowBias;
          },
          set: function set(val) {
            this._shadowBias = val;
          }
        }, {
          key: "shadowNormalBias",
          get: function get() {
            return this._shadowNormalBias;
          },
          set: function set(val) {
            this._shadowNormalBias = val;
          }
        }, {
          key: "receiveShadow",
          get: function get() {
            return this._receiveShadow;
          },
          set: function set(val) {
            this._receiveShadow = val;
            this.onMacroPatchesStateChanged();
          }
        }, {
          key: "castShadow",
          get: function get() {
            return this._castShadow;
          },
          set: function set(val) {
            this._castShadow = val;
          }
        }, {
          key: "receiveDirLight",
          get: function get() {
            return this._receiveDirLight;
          },
          set: function set(val) {
            this._receiveDirLight = val;
            this.onMacroPatchesStateChanged();
          }
        }, {
          key: "node",
          get: function get() {
            return this._node;
          },
          set: function set(n) {
            this._node = n;
          }
        }, {
          key: "transform",
          get: function get() {
            return this._transform;
          },
          set: function set(n) {
            this._transform = n;
          }
        }, {
          key: "visFlags",
          get: function get() {
            return this._visFlags;
          },
          set: function set(val) {
            this._visFlags = val;
          }
        }, {
          key: "enabled",
          get: function get() {
            return this._enabled;
          },
          set: function set(val) {
            this._enabled = val;
          }
        }, {
          key: "priority",
          get: function get() {
            return this._priority;
          },
          set: function set(val) {
            this._priority = val;
          }
        }, {
          key: "bakeToReflectionProbe",
          get: function get() {
            return this._bakeToReflectionProbe;
          },
          set: function set(val) {
            this._bakeToReflectionProbe = val;
          }
        }, {
          key: "reflectionProbeType",
          get: function get() {
            return this._reflectionProbeType;
          },
          set: function set(val) {
            this._reflectionProbeType = val;
            var subModels = this._subModels;
            for (var i = 0; i < subModels.length; i++) {
              subModels[i].useReflectionProbeType = val;
            }
            this.onMacroPatchesStateChanged();
          }
        }, {
          key: "reflectionProbeId",
          get: function get() {
            return this._reflectionProbeId;
          },
          set: function set(val) {
            this._reflectionProbeId = val;
          }
        }, {
          key: "reflectionProbeBlendId",
          get: function get() {
            return this._reflectionProbeBlendId;
          },
          set: function set(val) {
            this._reflectionProbeBlendId = val;
          }
        }, {
          key: "reflectionProbeBlendWeight",
          get: function get() {
            return this._reflectionProbeBlendWeight;
          },
          set: function set(val) {
            this._reflectionProbeBlendWeight = val;
          }
        }]);
        return Model;
      }();

      var _forward$2 = new Vec3(0, 0, -1);
      var _v3 = new Vec3();
      var DirectionalLight$1 = function (_Light) {
        _inheritsLoose(DirectionalLight, _Light);
        function DirectionalLight() {
          var _this;
          _this = _Light.call(this) || this;
          _this._dir = new Vec3(1.0, -1.0, -1.0);
          _this._illuminanceHDR = Ambient.SUN_ILLUM;
          _this._illuminanceLDR = 1.0;
          _this._shadowEnabled = false;
          _this._shadowPcf = PCFType.HARD;
          _this._shadowBias = 0.00001;
          _this._shadowNormalBias = 0.0;
          _this._shadowSaturation = 1.0;
          _this._shadowDistance = 50;
          _this._shadowInvisibleOcclusionRange = 200;
          _this._csmLevel = CSMLevel.LEVEL_4;
          _this._csmNeedUpdate = false;
          _this._csmLayerLambda = 0.75;
          _this._csmOptimizationMode = CSMOptimizationMode.DisableRotationFix;
          _this._csmLayersTransition = false;
          _this._csmTransitionRange = 0.05;
          _this._shadowFixedArea = false;
          _this._shadowNear = 0.1;
          _this._shadowFar = 10.0;
          _this._shadowOrthoSize = 5;
          _this._type = LightType.DIRECTIONAL;
          return _this;
        }
        var _proto = DirectionalLight.prototype;
        _proto.initialize = function initialize() {
          _Light.prototype.initialize.call(this);
          this.illuminance = Ambient.SUN_ILLUM;
          this.direction = new Vec3(1.0, -1.0, -1.0);
        };
        _proto.update = function update() {
          if (this._node && this._node.hasChangedFlags) {
            this.direction = Vec3.transformQuat(_v3, _forward$2, this._node.worldRotation);
          }
        };
        _proto.activate = function activate() {
          var root = legacyCC.director.root;
          var pipeline = root.pipeline;
          if (this._shadowEnabled) {
            if (this._shadowFixedArea || !pipeline.pipelineSceneData.csmSupported) {
              pipeline.macros.CC_DIR_LIGHT_SHADOW_TYPE = 1;
            } else if (this.csmLevel > 1 && pipeline.pipelineSceneData.csmSupported) {
              pipeline.macros.CC_DIR_LIGHT_SHADOW_TYPE = 2;
              pipeline.macros.CC_CASCADED_LAYERS_TRANSITION = this._csmLayersTransition;
            } else {
              pipeline.macros.CC_DIR_LIGHT_SHADOW_TYPE = 1;
            }
            pipeline.macros.CC_DIR_SHADOW_PCF_TYPE = this._shadowPcf;
          } else {
            pipeline.macros.CC_DIR_LIGHT_SHADOW_TYPE = 0;
          }
          root.onGlobalPipelineStateChanged();
        };
        _createClass(DirectionalLight, [{
          key: "direction",
          get: function get() {
            return this._dir;
          },
          set: function set(dir) {
            Vec3.normalize(this._dir, dir);
          }
        }, {
          key: "illuminance",
          get: function get() {
            var isHDR = legacyCC.director.root.pipeline.pipelineSceneData.isHDR;
            if (isHDR) {
              return this._illuminanceHDR;
            } else {
              return this._illuminanceLDR;
            }
          },
          set: function set(value) {
            var isHDR = legacyCC.director.root.pipeline.pipelineSceneData.isHDR;
            if (isHDR) {
              this.illuminanceHDR = value;
            } else {
              this.illuminanceLDR = value;
            }
          }
        }, {
          key: "illuminanceHDR",
          get: function get() {
            return this._illuminanceHDR;
          },
          set: function set(value) {
            this._illuminanceHDR = value;
          }
        }, {
          key: "illuminanceLDR",
          get: function get() {
            return this._illuminanceLDR;
          },
          set: function set(value) {
            this._illuminanceLDR = value;
          }
        }, {
          key: "shadowEnabled",
          get: function get() {
            return this._shadowEnabled;
          },
          set: function set(val) {
            this._shadowEnabled = val;
            this.activate();
          }
        }, {
          key: "shadowPcf",
          get: function get() {
            return this._shadowPcf;
          },
          set: function set(val) {
            this._shadowPcf = val;
            this.activate();
          }
        }, {
          key: "shadowBias",
          get: function get() {
            return this._shadowBias;
          },
          set: function set(val) {
            this._shadowBias = val;
          }
        }, {
          key: "shadowNormalBias",
          get: function get() {
            return this._shadowNormalBias;
          },
          set: function set(val) {
            this._shadowNormalBias = val;
          }
        }, {
          key: "shadowSaturation",
          get: function get() {
            return this._shadowSaturation;
          },
          set: function set(val) {
            this._shadowSaturation = val;
          }
        }, {
          key: "shadowDistance",
          get: function get() {
            return this._shadowDistance;
          },
          set: function set(val) {
            this._shadowDistance = Math.min(val, Shadows.MAX_FAR);
          }
        }, {
          key: "shadowInvisibleOcclusionRange",
          get: function get() {
            return this._shadowInvisibleOcclusionRange;
          },
          set: function set(val) {
            this._shadowInvisibleOcclusionRange = Math.min(val, Shadows.MAX_FAR);
          }
        }, {
          key: "csmLevel",
          get: function get() {
            return this._csmLevel;
          },
          set: function set(val) {
            this._csmLevel = val;
            this.activate();
          }
        }, {
          key: "csmNeedUpdate",
          get: function get() {
            return this._csmNeedUpdate;
          },
          set: function set(val) {
            this._csmNeedUpdate = val;
          }
        }, {
          key: "csmLayerLambda",
          get: function get() {
            return this._csmLayerLambda;
          },
          set: function set(val) {
            this._csmLayerLambda = val;
          }
        }, {
          key: "csmOptimizationMode",
          get: function get() {
            return this._csmOptimizationMode;
          },
          set: function set(val) {
            this._csmOptimizationMode = val;
          }
        }, {
          key: "shadowFixedArea",
          get: function get() {
            return this._shadowFixedArea;
          },
          set: function set(val) {
            this._shadowFixedArea = val;
            this.activate();
          }
        }, {
          key: "shadowNear",
          get: function get() {
            return this._shadowNear;
          },
          set: function set(val) {
            this._shadowNear = val;
          }
        }, {
          key: "shadowFar",
          get: function get() {
            return this._shadowFar;
          },
          set: function set(val) {
            this._shadowFar = Math.min(val, Shadows.MAX_FAR);
          }
        }, {
          key: "shadowOrthoSize",
          get: function get() {
            return this._shadowOrthoSize;
          },
          set: function set(val) {
            this._shadowOrthoSize = val;
          }
        }, {
          key: "csmLayersTransition",
          get: function get() {
            return this._csmLayersTransition;
          },
          set: function set(val) {
            this._csmLayersTransition = val;
            this.activate();
          }
        }, {
          key: "csmTransitionRange",
          get: function get() {
            return this._csmTransitionRange;
          },
          set: function set(val) {
            this._csmTransitionRange = val;
          }
        }]);
        return DirectionalLight;
      }(Light$1);

      var SphereLight$1 = function (_Light) {
        _inheritsLoose(SphereLight, _Light);
        function SphereLight() {
          var _this;
          _this = _Light.call(this) || this;
          _this._needUpdate = false;
          _this._size = 0.15;
          _this._range = 1.0;
          _this._luminanceHDR = 0;
          _this._luminanceLDR = 0;
          _this._pos = void 0;
          _this._aabb = void 0;
          _this._aabb = AABB.create();
          _this._pos = new Vec3();
          _this._type = LightType.SPHERE;
          return _this;
        }
        var _proto = SphereLight.prototype;
        _proto.initialize = function initialize() {
          _Light.prototype.initialize.call(this);
          var size = 0.15;
          this.size = size;
          this.range = 1.0;
          this.luminanceHDR = 1700 / nt2lm(size);
          this.luminanceLDR = 1.0;
        };
        _proto.update = function update() {
          if (this._node && (this._node.hasChangedFlags || this._needUpdate)) {
            this._node.getWorldPosition(this._pos);
            var range = this._range;
            AABB.set(this._aabb, this._pos.x, this._pos.y, this._pos.z, range, range, range);
            this._needUpdate = false;
          }
        };
        _createClass(SphereLight, [{
          key: "position",
          get: function get() {
            return this._pos;
          }
        }, {
          key: "size",
          get: function get() {
            return this._size;
          },
          set: function set(size) {
            this._size = size;
          }
        }, {
          key: "range",
          get: function get() {
            return this._range;
          },
          set: function set(range) {
            this._range = range;
            this._needUpdate = true;
          }
        }, {
          key: "luminance",
          get: function get() {
            var isHDR = legacyCC.director.root.pipeline.pipelineSceneData.isHDR;
            if (isHDR) {
              return this._luminanceHDR;
            } else {
              return this._luminanceLDR;
            }
          },
          set: function set(value) {
            var isHDR = legacyCC.director.root.pipeline.pipelineSceneData.isHDR;
            if (isHDR) {
              this.luminanceHDR = value;
            } else {
              this.luminanceLDR = value;
            }
          }
        }, {
          key: "luminanceHDR",
          get: function get() {
            return this._luminanceHDR;
          },
          set: function set(value) {
            this._luminanceHDR = value;
          }
        }, {
          key: "luminanceLDR",
          set: function set(value) {
            this._luminanceLDR = value;
          }
        }, {
          key: "aabb",
          get: function get() {
            return this._aabb;
          }
        }]);
        return SphereLight;
      }(Light$1);

      var _forward$1 = new Vec3(0, 0, -1);
      var _qt = new Quat();
      var _matView = new Mat4();
      var _matProj = new Mat4();
      var _matViewProj = new Mat4();
      var _matViewProjInv = new Mat4();
      var SpotLight$1 = function (_Light) {
        _inheritsLoose(SpotLight, _Light);
        function SpotLight() {
          var _this;
          _this = _Light.call(this) || this;
          _this._dir = new Vec3(1.0, -1.0, -1.0);
          _this._range = 5.0;
          _this._spotAngle = Math.cos(Math.PI / 6);
          _this._pos = void 0;
          _this._aabb = void 0;
          _this._frustum = void 0;
          _this._angle = 0;
          _this._needUpdate = false;
          _this._size = 0.15;
          _this._luminanceHDR = 0;
          _this._luminanceLDR = 0;
          _this._shadowEnabled = false;
          _this._shadowPcf = PCFType.HARD;
          _this._shadowBias = 0.00001;
          _this._shadowNormalBias = 0.0;
          _this._aabb = AABB.create();
          _this._frustum = Frustum.create();
          _this._pos = new Vec3();
          _this._type = LightType.SPOT;
          return _this;
        }
        var _proto = SpotLight.prototype;
        _proto.initialize = function initialize() {
          _Light.prototype.initialize.call(this);
          var size = 0.15;
          this.size = size;
          this.luminanceHDR = 1700 / nt2lm(size);
          this.luminanceLDR = 1.0;
          this.range = Math.cos(Math.PI / 6);
          this._dir.set(new Vec3(1.0, -1.0, -1.0));
        };
        _proto.update = function update() {
          if (this._node && (this._node.hasChangedFlags || this._needUpdate)) {
            this._node.getWorldPosition(this._pos);
            Vec3.transformQuat(this._dir, _forward$1, this._node.getWorldRotation(_qt));
            Vec3.normalize(this._dir, this._dir);
            AABB.set(this._aabb, this._pos.x, this._pos.y, this._pos.z, this._range, this._range, this._range);
            this._node.getWorldRT(_matView);
            Mat4.invert(_matView, _matView);
            Mat4.perspective(_matProj, this._angle, 1.0, 0.001, this._range);
            Mat4.multiply(_matViewProj, _matProj, _matView);
            this._frustum.update(_matViewProj, _matViewProjInv);
            this._needUpdate = false;
          }
        };
        _createClass(SpotLight, [{
          key: "position",
          get: function get() {
            return this._pos;
          }
        }, {
          key: "size",
          get: function get() {
            return this._size;
          },
          set: function set(size) {
            this._size = size;
          }
        }, {
          key: "range",
          get: function get() {
            return this._range;
          },
          set: function set(range) {
            this._range = range;
            this._needUpdate = true;
          }
        }, {
          key: "luminance",
          get: function get() {
            var isHDR = legacyCC.director.root.pipeline.pipelineSceneData.isHDR;
            if (isHDR) {
              return this._luminanceHDR;
            } else {
              return this._luminanceLDR;
            }
          },
          set: function set(value) {
            var isHDR = legacyCC.director.root.pipeline.pipelineSceneData.isHDR;
            if (isHDR) {
              this.luminanceHDR = value;
            } else {
              this.luminanceLDR = value;
            }
          }
        }, {
          key: "luminanceHDR",
          get: function get() {
            return this._luminanceHDR;
          },
          set: function set(value) {
            this._luminanceHDR = value;
          }
        }, {
          key: "luminanceLDR",
          get: function get() {
            return this._luminanceLDR;
          },
          set: function set(value) {
            this._luminanceLDR = value;
          }
        }, {
          key: "direction",
          get: function get() {
            return this._dir;
          }
        }, {
          key: "spotAngle",
          get: function get() {
            return this._spotAngle;
          },
          set: function set(val) {
            this._angle = val;
            this._spotAngle = Math.cos(val * 0.5);
            this._needUpdate = true;
          }
        }, {
          key: "angle",
          get: function get() {
            return this._angle;
          }
        }, {
          key: "aabb",
          get: function get() {
            return this._aabb;
          }
        }, {
          key: "frustum",
          get: function get() {
            return this._frustum;
          }
        }, {
          key: "shadowEnabled",
          get: function get() {
            return this._shadowEnabled;
          },
          set: function set(val) {
            this._shadowEnabled = val;
          }
        }, {
          key: "shadowPcf",
          get: function get() {
            return this._shadowPcf;
          },
          set: function set(val) {
            this._shadowPcf = val;
          }
        }, {
          key: "shadowBias",
          get: function get() {
            return this._shadowBias;
          },
          set: function set(val) {
            this._shadowBias = val;
          }
        }, {
          key: "shadowNormalBias",
          get: function get() {
            return this._shadowNormalBias;
          },
          set: function set(val) {
            this._shadowNormalBias = val;
          }
        }]);
        return SpotLight;
      }(Light$1);

      var PointLight$1 = function (_Light) {
        _inheritsLoose(PointLight, _Light);
        function PointLight() {
          var _this;
          _this = _Light.call(this) || this;
          _this._needUpdate = false;
          _this._range = 1.0;
          _this._luminanceHDR = 0;
          _this._luminanceLDR = 0;
          _this._pos = void 0;
          _this._aabb = void 0;
          _this._aabb = AABB.create();
          _this._pos = new Vec3();
          _this._type = LightType.POINT;
          return _this;
        }
        var _proto = PointLight.prototype;
        _proto.initialize = function initialize() {
          _Light.prototype.initialize.call(this);
          this.range = 1.0;
          this.luminanceHDR = 1700 / nt2lm(1.0);
          this.luminanceLDR = 1.0;
        };
        _proto.update = function update() {
          if (this._node && (this._node.hasChangedFlags || this._needUpdate)) {
            this._node.getWorldPosition(this._pos);
            var range = this._range;
            AABB.set(this._aabb, this._pos.x, this._pos.y, this._pos.z, range, range, range);
            this._needUpdate = false;
          }
        };
        _createClass(PointLight, [{
          key: "position",
          get: function get() {
            return this._pos;
          }
        }, {
          key: "range",
          get: function get() {
            return this._range;
          },
          set: function set(range) {
            this._range = range;
            this._needUpdate = true;
          }
        }, {
          key: "luminance",
          get: function get() {
            var isHDR = legacyCC.director.root.pipeline.pipelineSceneData.isHDR;
            if (isHDR) {
              return this._luminanceHDR;
            } else {
              return this._luminanceLDR;
            }
          },
          set: function set(value) {
            var isHDR = legacyCC.director.root.pipeline.pipelineSceneData.isHDR;
            if (isHDR) {
              this.luminanceHDR = value;
            } else {
              this.luminanceLDR = value;
            }
          }
        }, {
          key: "luminanceHDR",
          get: function get() {
            return this._luminanceHDR;
          },
          set: function set(value) {
            this._luminanceHDR = value;
          }
        }, {
          key: "luminanceLDR",
          set: function set(value) {
            this._luminanceLDR = value;
          }
        }, {
          key: "aabb",
          get: function get() {
            return this._aabb;
          }
        }]);
        return PointLight;
      }(Light$1);

      var _forward = new Vec3(0, 0, -1);
      var RangedDirectionalLight$1 = function (_Light) {
        _inheritsLoose(RangedDirectionalLight, _Light);
        function RangedDirectionalLight() {
          var _this;
          _this = _Light.call(this) || this;
          _this._dir = new Vec3(0, 0, -1);
          _this._pos = new Vec3(0, 0, 0);
          _this._scale = new Vec3(1, 1, 1);
          _this._right = new Vec3(1, 0, 0);
          _this._illuminanceHDR = Ambient.SUN_ILLUM;
          _this._illuminanceLDR = 1.0;
          _this._type = LightType.RANGED_DIRECTIONAL;
          return _this;
        }
        var _proto = RangedDirectionalLight.prototype;
        _proto.initialize = function initialize() {
          _Light.prototype.initialize.call(this);
          this.illuminance = Ambient.SUN_ILLUM;
        };
        _proto.update = function update() {
          if (this._node && this._node.hasChangedFlags) {
            this._node.getWorldPosition(this._pos);
            this._node.getWorldScale(this._scale);
            Vec3.transformQuat(this._dir, _forward, this._node.worldRotation);
            Vec3.transformQuat(this._right, Vec3.RIGHT, this._node.worldRotation);
          }
        };
        _createClass(RangedDirectionalLight, [{
          key: "direction",
          get: function get() {
            return this._dir;
          }
        }, {
          key: "right",
          get: function get() {
            return this._right;
          }
        }, {
          key: "position",
          get: function get() {
            return this._pos;
          }
        }, {
          key: "scale",
          get: function get() {
            return this._scale;
          }
        }, {
          key: "illuminance",
          get: function get() {
            var isHDR = legacyCC.director.root.pipeline.pipelineSceneData.isHDR;
            if (isHDR) {
              return this._illuminanceHDR;
            } else {
              return this._illuminanceLDR;
            }
          },
          set: function set(value) {
            var isHDR = legacyCC.director.root.pipeline.pipelineSceneData.isHDR;
            if (isHDR) {
              this.illuminanceHDR = value;
            } else {
              this.illuminanceLDR = value;
            }
          }
        }, {
          key: "illuminanceHDR",
          get: function get() {
            return this._illuminanceHDR;
          },
          set: function set(value) {
            this._illuminanceHDR = value;
          }
        }, {
          key: "illuminanceLDR",
          get: function get() {
            return this._illuminanceLDR;
          },
          set: function set(value) {
            this._illuminanceLDR = value;
          }
        }]);
        return RangedDirectionalLight;
      }(Light$1);

      var LODData = function () {
        function LODData() {
          this.screenUsagePercentage = 1.0;
          this._models = [];
        }
        var _proto = LODData.prototype;
        _proto.addModel = function addModel(model) {
          this._models.splice(0, 0, model);
        };
        _proto.eraseModel = function eraseModel(model) {
          var removeIndex = this._models.indexOf(model);
          if (removeIndex >= 0) {
            this._models.splice(removeIndex, 1);
          }
        };
        _proto.clearModels = function clearModels() {
          this._models.length = 0;
        };
        _createClass(LODData, [{
          key: "models",
          get: function get() {
            return this._models;
          }
        }]);
        return LODData;
      }();
      var LODGroup$1 = function () {
        function LODGroup() {
          this.scene = void 0;
          this.node = null;
          this._device = void 0;
          this.enabled = true;
          this._localBoundaryCenter = new Vec3(0, 0, 0);
          this._objectSize = 1;
          this._lodDataArray = [];
          this._lockedLODLevelVec = [];
          this._isLockLevelChanged = false;
          this._device = deviceManager.gfxDevice;
        }
        var _proto2 = LODGroup.prototype;
        _proto2.attachToScene = function attachToScene(scene) {
          this.scene = scene;
        };
        _proto2.detachFromScene = function detachFromScene() {
          this.scene = null;
        };
        _proto2.lockLODLevels = function lockLODLevels(lockLev) {
          if (lockLev.length !== this._lockedLODLevelVec.length) {
            this._isLockLevelChanged = true;
          } else {
            var size = lockLev.length;
            var index = 0;
            for (; index < size; index++) {
              if (lockLev[index] !== this._lockedLODLevelVec[index]) {
                this._isLockLevelChanged = true;
                break;
              }
            }
          }
          this._lockedLODLevelVec = lockLev.slice();
        };
        _proto2.isLockLevelChanged = function isLockLevelChanged() {
          return this._isLockLevelChanged;
        };
        _proto2.resetLockChangeFlag = function resetLockChangeFlag() {
          this._isLockLevelChanged = false;
        };
        _proto2.getLockedLODLevels = function getLockedLODLevels() {
          return this._lockedLODLevelVec;
        };
        _proto2.clearLODs = function clearLODs() {
          this._lodDataArray.length = 0;
        };
        _proto2.insertLOD = function insertLOD(index, lod) {
          this._lodDataArray.splice(index, 0, lod);
        };
        _proto2.updateLOD = function updateLOD(index, lod) {
          this._lodDataArray[index] = lod;
        };
        _proto2.eraseLOD = function eraseLOD(index) {
          this._lodDataArray.splice(index, 1);
        };
        _proto2.getVisibleLODLevel = function getVisibleLODLevel(camera) {
          var screenUsagePercentage = this.getScreenUsagePercentage(camera);
          var lodIndex = -1;
          for (var i = 0; i < this.lodCount; ++i) {
            var lod = this.lodDataArray[i];
            if (screenUsagePercentage >= lod.screenUsagePercentage) {
              lodIndex = i;
              break;
            }
          }
          return lodIndex;
        };
        _proto2.getScreenUsagePercentage = function getScreenUsagePercentage(camera) {
          if (!this.node) return 0;
          var distance;
          if (camera.projectionType === CameraProjection.PERSPECTIVE) {
            distance = Vec3.len(this.localBoundaryCenter.transformMat4(this.node.worldMatrix).subtract(camera.node.worldPosition));
          }
          return this.distanceToScreenUsagePercentage(camera, distance, this.getWorldSpaceSize());
        };
        _proto2.distanceToScreenUsagePercentage = function distanceToScreenUsagePercentage(camera, distance, size) {
          if (camera.projectionType === CameraProjection.PERSPECTIVE) {
            assertIsTrue(typeof distance === 'number', 'distance must be present for perspective projection');
            return size * camera.matProj.m05 / (distance * 2.0);
          } else {
            return size * camera.matProj.m05 * 0.5;
          }
        };
        _proto2.getWorldSpaceSize = function getWorldSpaceSize() {
          var scale = this.node.scale;
          var maxScale = Math.max(Math.abs(scale.x), Math.abs(scale.y), Math.abs(scale.z));
          return maxScale * this.objectSize;
        };
        _createClass(LODGroup, [{
          key: "localBoundaryCenter",
          get: function get() {
            return this._localBoundaryCenter.clone();
          },
          set: function set(val) {
            this._localBoundaryCenter.set(val);
          }
        }, {
          key: "lodCount",
          get: function get() {
            return this._lodDataArray.length;
          }
        }, {
          key: "objectSize",
          get: function get() {
            return this._objectSize;
          },
          set: function set(val) {
            this._objectSize = val;
          }
        }, {
          key: "lodDataArray",
          get: function get() {
            return this._lodDataArray;
          }
        }]);
        return LODGroup;
      }();

      var index = /*#__PURE__*/Object.freeze({
        __proto__: null,
        get CameraFOVAxis () { return CameraFOVAxis; },
        get CameraProjection () { return CameraProjection; },
        get CameraAperture () { return CameraAperture; },
        get CameraISO () { return CameraISO; },
        get CameraShutter () { return CameraShutter; },
        get CameraType () { return CameraType; },
        get TrackingType () { return TrackingType; },
        get CameraUsage () { return CameraUsage; },
        SKYBOX_FLAG: SKYBOX_FLAG,
        Camera: Camera$1,
        get ModelType () { return ModelType; },
        Model: Model,
        SubModel: SubModel,
        Ambient: Ambient,
        EnvironmentLightingType: EnvironmentLightingType,
        Skybox: Skybox,
        ShadowSize: ShadowSize,
        ShadowType: ShadowType,
        PCFType: PCFType,
        CSMLevel: CSMLevel,
        CSMOptimizationMode: CSMOptimizationMode,
        Shadows: Shadows,
        FogType: FogType,
        FOG_TYPE_NONE: FOG_TYPE_NONE,
        Fog: Fog,
        Octree: Octree,
        Skin: Skin,
        ColorTemperatureToRGB: ColorTemperatureToRGB,
        get LightType () { return LightType; },
        nt2lm: nt2lm,
        Light: Light$1,
        DirectionalLight: DirectionalLight$1,
        SphereLight: SphereLight$1,
        SpotLight: SpotLight$1,
        PointLight: PointLight$1,
        RangedDirectionalLight: RangedDirectionalLight$1,
        get ProbeClearFlag () { return ProbeClearFlag; },
        get ProbeType () { return ProbeType; },
        ReflectionProbe: ReflectionProbe$1,
        LODData: LODData,
        LODGroup: LODGroup$1,
        ToneMappingType: ToneMappingType,
        PostSettings: PostSettings
      });

      var RenderScene = function () {
        RenderScene.registerCreateFunc = function registerCreateFunc(root) {
          root._createSceneFun = function (_root) {
            return new RenderScene(_root);
          };
        };
        function RenderScene(root) {
          this._root = void 0;
          this._name = '';
          this._cameras = [];
          this._models = [];
          this._lodGroups = [];
          this._batches = [];
          this._directionalLights = [];
          this._sphereLights = [];
          this._spotLights = [];
          this._pointLights = [];
          this._rangedDirLights = [];
          this._mainLight = null;
          this._modelId = 0;
          this._lodStateCache = null;
          this._root = root;
        }
        var _proto = RenderScene.prototype;
        _proto.initialize = function initialize(info) {
          this._name = info.name;
          this._lodStateCache = new LodStateCache(this);
          return true;
        };
        _proto.update = function update(stamp) {
          var mainLight = this._mainLight;
          if (mainLight) {
            mainLight.update();
          }
          var sphereLights = this._sphereLights;
          for (var i = 0; i < sphereLights.length; i++) {
            var light = sphereLights[i];
            light.update();
          }
          var spotLights = this._spotLights;
          for (var _i = 0; _i < spotLights.length; _i++) {
            var _light = spotLights[_i];
            _light.update();
          }
          var pointLights = this._pointLights;
          for (var _i2 = 0; _i2 < pointLights.length; _i2++) {
            var _light2 = pointLights[_i2];
            _light2.update();
          }
          var rangedDirLights = this._rangedDirLights;
          for (var _i3 = 0; _i3 < rangedDirLights.length; _i3++) {
            var _light3 = rangedDirLights[_i3];
            _light3.update();
          }
          var models = this._models;
          for (var _i4 = 0; _i4 < models.length; _i4++) {
            var model = models[_i4];
            if (model.enabled) {
              model.updateTransform(stamp);
              model.updateUBOs(stamp);
            }
          }
          this._lodStateCache.updateLodState();
        };
        _proto.destroy = function destroy() {
          this.removeCameras();
          this.removeSphereLights();
          this.removeSpotLights();
          this.removeRangedDirLights();
          this.removeModels();
          this.removeLODGroups();
          this._lodStateCache.clearCache();
        };
        _proto.isCulledByLod = function isCulledByLod(camera, model) {
          return this._lodStateCache.isLodModelCulled(camera, model);
        };
        _proto.addCamera = function addCamera(cam) {
          cam.attachToScene(this);
          this._cameras.push(cam);
          this._lodStateCache.addCamera(cam);
        };
        _proto.removeCamera = function removeCamera(camera) {
          for (var i = 0; i < this._cameras.length; ++i) {
            if (this._cameras[i] === camera) {
              this._cameras.splice(i, 1);
              camera.detachFromScene();
              this._lodStateCache.removeCamera(camera);
              return;
            }
          }
        };
        _proto.removeCameras = function removeCameras() {
          for (var _iterator = _createForOfIteratorHelperLoose(this._cameras), _step; !(_step = _iterator()).done;) {
            var camera = _step.value;
            camera.detachFromScene();
            this._lodStateCache.removeCamera(camera);
          }
          this._cameras.splice(0);
        };
        _proto.setMainLight = function setMainLight(dl) {
          this._mainLight = dl;
          if (this._mainLight) this._mainLight.activate();
        };
        _proto.unsetMainLight = function unsetMainLight(dl) {
          if (this._mainLight === dl) {
            var dlList = this._directionalLights;
            if (dlList.length) {
              this.setMainLight(dlList[dlList.length - 1]);
              if (this._mainLight.node) {
                this._mainLight.node.hasChangedFlags |= TransformBit.ROTATION;
              }
              return;
            }
            this.setMainLight(null);
          }
        };
        _proto.addDirectionalLight = function addDirectionalLight(dl) {
          dl.attachToScene(this);
          this._directionalLights.push(dl);
        };
        _proto.removeDirectionalLight = function removeDirectionalLight(dl) {
          for (var i = 0; i < this._directionalLights.length; ++i) {
            if (this._directionalLights[i] === dl) {
              dl.detachFromScene();
              this._directionalLights.splice(i, 1);
              return;
            }
          }
        };
        _proto.addSphereLight = function addSphereLight(pl) {
          pl.attachToScene(this);
          this._sphereLights.push(pl);
        };
        _proto.removeSphereLight = function removeSphereLight(pl) {
          for (var i = 0; i < this._sphereLights.length; ++i) {
            if (this._sphereLights[i] === pl) {
              pl.detachFromScene();
              this._sphereLights.splice(i, 1);
              return;
            }
          }
        };
        _proto.addSpotLight = function addSpotLight(sl) {
          sl.attachToScene(this);
          this._spotLights.push(sl);
        };
        _proto.removeSpotLight = function removeSpotLight(sl) {
          for (var i = 0; i < this._spotLights.length; ++i) {
            if (this._spotLights[i] === sl) {
              sl.detachFromScene();
              this._spotLights.splice(i, 1);
              return;
            }
          }
        };
        _proto.removeSphereLights = function removeSphereLights() {
          for (var i = 0; i < this._sphereLights.length; ++i) {
            this._sphereLights[i].detachFromScene();
          }
          this._sphereLights.length = 0;
        };
        _proto.removeSpotLights = function removeSpotLights() {
          for (var i = 0; i < this._spotLights.length; ++i) {
            this._spotLights[i].detachFromScene();
          }
          this._spotLights.length = 0;
        };
        _proto.addPointLight = function addPointLight(pl) {
          pl.attachToScene(this);
          this._pointLights.push(pl);
        };
        _proto.removePointLight = function removePointLight(pl) {
          for (var i = 0; i < this._pointLights.length; ++i) {
            if (this._pointLights[i] === pl) {
              pl.detachFromScene();
              this._pointLights.splice(i, 1);
              return;
            }
          }
        };
        _proto.removePointLights = function removePointLights() {
          for (var i = 0; i < this._pointLights.length; ++i) {
            this._pointLights[i].detachFromScene();
          }
          this._pointLights.length = 0;
        };
        _proto.addRangedDirLight = function addRangedDirLight(l) {
          l.attachToScene(this);
          this._rangedDirLights.push(l);
        };
        _proto.removeRangedDirLight = function removeRangedDirLight(l) {
          for (var i = 0; i < this._rangedDirLights.length; ++i) {
            if (this._rangedDirLights[i] === l) {
              l.detachFromScene();
              this._rangedDirLights.splice(i, 1);
              return;
            }
          }
        };
        _proto.removeRangedDirLights = function removeRangedDirLights() {
          for (var i = 0; i < this._rangedDirLights.length; ++i) {
            this._rangedDirLights[i].detachFromScene();
          }
          this._rangedDirLights.length = 0;
        };
        _proto.addModel = function addModel(m) {
          m.attachToScene(this);
          this._models.push(m);
        };
        _proto.removeModel = function removeModel(model) {
          for (var i = 0; i < this._models.length; ++i) {
            if (this._models[i] === model) {
              this._lodStateCache.removeModel(model);
              model.detachFromScene();
              this._models.splice(i, 1);
              return;
            }
          }
        };
        _proto.removeModels = function removeModels() {
          for (var _iterator2 = _createForOfIteratorHelperLoose(this._models), _step2; !(_step2 = _iterator2()).done;) {
            var m = _step2.value;
            this._lodStateCache.removeModel(m);
            m.detachFromScene();
            m.destroy();
          }
          this._models.length = 0;
        };
        _proto.addBatch = function addBatch(batch) {
          this._batches.push(batch);
        };
        _proto.removeBatch = function removeBatch(batch) {
          for (var i = 0; i < this._batches.length; ++i) {
            if (this._batches[i] === batch) {
              this._batches.splice(i, 1);
              return;
            }
          }
        };
        _proto.removeBatches = function removeBatches() {
          this._batches.length = 0;
        };
        _proto.addLODGroup = function addLODGroup(lodGroup) {
          this._lodGroups.push(lodGroup);
          lodGroup.attachToScene(this);
          this._lodStateCache.addLodGroup(lodGroup);
        };
        _proto.removeLODGroup = function removeLODGroup(lodGroup) {
          var index = this._lodGroups.indexOf(lodGroup);
          if (index >= 0) {
            this._lodGroups.splice(index, 1);
            lodGroup.detachFromScene();
            this._lodStateCache.removeLodGroup(lodGroup);
          }
        };
        _proto.removeLODGroups = function removeLODGroups() {
          for (var _iterator3 = _createForOfIteratorHelperLoose(this._lodGroups), _step3; !(_step3 = _iterator3()).done;) {
            var group = _step3.value;
            this._lodStateCache.removeLodGroup(group);
          }
          this._lodGroups.length = 0;
        };
        _proto.onGlobalPipelineStateChanged = function onGlobalPipelineStateChanged() {
          for (var _iterator4 = _createForOfIteratorHelperLoose(this._models), _step4; !(_step4 = _iterator4()).done;) {
            var m = _step4.value;
            m.onGlobalPipelineStateChanged();
          }
        };
        _proto.generateModelId = function generateModelId() {
          return this._modelId++;
        };
        _createClass(RenderScene, [{
          key: "root",
          get: function get() {
            return this._root;
          }
        }, {
          key: "name",
          get: function get() {
            return this._name;
          }
        }, {
          key: "cameras",
          get: function get() {
            return this._cameras;
          }
        }, {
          key: "mainLight",
          get: function get() {
            return this._mainLight;
          }
        }, {
          key: "sphereLights",
          get: function get() {
            return this._sphereLights;
          }
        }, {
          key: "spotLights",
          get: function get() {
            return this._spotLights;
          }
        }, {
          key: "pointLights",
          get: function get() {
            return this._pointLights;
          }
        }, {
          key: "rangedDirLights",
          get: function get() {
            return this._rangedDirLights;
          }
        }, {
          key: "models",
          get: function get() {
            return this._models;
          }
        }, {
          key: "batches",
          get: function get() {
            return this._batches;
          }
        }, {
          key: "lodGroups",
          get: function get() {
            return this._lodGroups;
          }
        }]);
        return RenderScene;
      }();
      var LODInfo = function LODInfo() {
        this.usedLevel = -1;
        this.lastUsedLevel = -1;
        this.transformDirty = true;
      };
      var LodStateCache = function () {
        function LodStateCache(scene) {
          this._renderScene = null;
          this._modelsInLODGroup = new Map();
          this._lodStateInCamera = new Map();
          this._newAddedLodGroupVec = new Array();
          this._levelModels = new Map();
          this._renderScene = scene;
        }
        var _proto2 = LodStateCache.prototype;
        _proto2.addCamera = function addCamera(camera) {
          for (var _iterator5 = _createForOfIteratorHelperLoose(this._renderScene.lodGroups), _step5; !(_step5 = _iterator5()).done;) {
            var lodGroup = _step5.value;
            var layer = lodGroup.node.layer;
            if ((camera.visibility & layer) === layer) {
              if (!this._lodStateInCamera.has(camera)) {
                this._lodStateInCamera.set(camera, new Map());
              }
              break;
            }
          }
        };
        _proto2.removeCamera = function removeCamera(camera) {
          if (this._lodStateInCamera.has(camera)) {
            this._lodStateInCamera["delete"](camera);
          }
        };
        _proto2.addLodGroup = function addLodGroup(lodGroup) {
          this._newAddedLodGroupVec.push(lodGroup);
          for (var _iterator6 = _createForOfIteratorHelperLoose(this._renderScene.cameras), _step6; !(_step6 = _iterator6()).done;) {
            var camera = _step6.value;
            if (this._lodStateInCamera.has(camera)) {
              continue;
            }
            var layer = lodGroup.node.layer;
            if ((camera.visibility & layer) === layer) {
              this._lodStateInCamera.set(camera, new Map());
            }
          }
        };
        _proto2.removeLodGroup = function removeLodGroup(lodGroup) {
          for (var index = 0; index < lodGroup.lodCount; index++) {
            var lod = lodGroup.lodDataArray[index];
            for (var _iterator7 = _createForOfIteratorHelperLoose(lod.models), _step7; !(_step7 = _iterator7()).done;) {
              var model = _step7.value;
              this._modelsInLODGroup["delete"](model);
            }
          }
          for (var _iterator8 = _createForOfIteratorHelperLoose(this._lodStateInCamera), _step8; !(_step8 = _iterator8()).done;) {
            var visibleCamera = _step8.value;
            visibleCamera[1]["delete"](lodGroup);
          }
          this._levelModels["delete"](lodGroup);
        };
        _proto2.removeModel = function removeModel(model) {
          if (this._modelsInLODGroup.has(model)) {
            this._modelsInLODGroup["delete"](model);
          }
        };
        _proto2.updateLodState = function updateLodState() {
          var _this = this;
          for (var _iterator9 = _createForOfIteratorHelperLoose(this._newAddedLodGroupVec), _step9; !(_step9 = _iterator9()).done;) {
            var addedLodGroup = _step9.value;
            var levelModels = this._levelModels.get(addedLodGroup);
            if (!levelModels) {
              levelModels = new Map();
              this._levelModels.set(addedLodGroup, levelModels);
            }
            for (var index = 0; index < addedLodGroup.lodCount; index++) {
              var lodModels = levelModels.get(index);
              if (!lodModels) {
                lodModels = new Array();
              }
              var lod = addedLodGroup.lodDataArray[index];
              for (var _iterator11 = _createForOfIteratorHelperLoose(lod.models), _step11; !(_step11 = _iterator11()).done;) {
                var model = _step11.value;
                var modelInfo = this._modelsInLODGroup.get(model);
                if (!modelInfo) {
                  modelInfo = new Map();
                }
                this._modelsInLODGroup.set(model, modelInfo);
                lodModels.push(model);
              }
              levelModels.set(index, lodModels);
            }
          }
          this._newAddedLodGroupVec.length = 0;
          var _loop = function _loop() {
              var lodGroup = _step10.value;
              if (lodGroup.enabled) {
                var lodLevels = lodGroup.getLockedLODLevels();
                var count = lodLevels.length;
                if (count > 0) {
                  if (lodGroup.node.hasChangedFlags > 0) {
                    for (var _iterator12 = _createForOfIteratorHelperLoose(_this._lodStateInCamera), _step12; !(_step12 = _iterator12()).done;) {
                      var visibleCamera = _step12.value;
                      var lodInfo = visibleCamera[1].get(lodGroup);
                      if (!lodInfo) {
                        lodInfo = new LODInfo();
                        visibleCamera[1].set(lodGroup, lodInfo);
                      }
                      lodInfo.transformDirty = true;
                    }
                  }
                  if (lodGroup.isLockLevelChanged()) {
                    lodGroup.resetLockChangeFlag();
                    var _lodModels = _this._levelModels.get(lodGroup);
                    if (_lodModels) {
                      _lodModels.forEach(function (vecArray, index) {
                        vecArray.forEach(function (model) {
                          var modelInfo = _this._modelsInLODGroup.get(model);
                          if (modelInfo) {
                            modelInfo.clear();
                          }
                        });
                      });
                      for (var _iterator13 = _createForOfIteratorHelperLoose(lodLevels), _step13; !(_step13 = _iterator13()).done;) {
                        var visibleIndex = _step13.value;
                        var vecModels = _lodModels.get(visibleIndex);
                        if (vecModels) {
                          vecModels.forEach(function (model) {
                            var modelInfo = _this._modelsInLODGroup.get(model);
                            if (modelInfo && model.node && model.node.active) {
                              for (var _iterator14 = _createForOfIteratorHelperLoose(_this._lodStateInCamera), _step14; !(_step14 = _iterator14()).done;) {
                                var _visibleCamera = _step14.value;
                                modelInfo.set(_visibleCamera[0], true);
                              }
                            }
                          });
                        }
                      }
                    }
                  }
                  return 0;
                }
                var hasUpdated = false;
                for (var _iterator15 = _createForOfIteratorHelperLoose(_this._lodStateInCamera), _step15; !(_step15 = _iterator15()).done;) {
                  var _visibleCamera2 = _step15.value;
                  var _lodInfo = _visibleCamera2[1].get(lodGroup);
                  if (!_lodInfo) {
                    _lodInfo = new LODInfo();
                    _visibleCamera2[1].set(lodGroup, _lodInfo);
                  }
                  var cameraChangeFlags = _visibleCamera2[0].node.hasChangedFlags;
                  var lodChangeFlags = lodGroup.node.hasChangedFlags;
                  if (cameraChangeFlags > 0 || lodChangeFlags > 0 || _lodInfo.transformDirty) {
                    if (_lodInfo.transformDirty) {
                      _lodInfo.transformDirty = false;
                    }
                    var _index = lodGroup.getVisibleLODLevel(_visibleCamera2[0]);
                    if (_index !== _lodInfo.usedLevel) {
                      _lodInfo.lastUsedLevel = _lodInfo.usedLevel;
                      _lodInfo.usedLevel = _index;
                      hasUpdated = true;
                    }
                  }
                }
                var _lodModels2 = _this._levelModels.get(lodGroup);
                if (!_lodModels2) {
                  return 0;
                }
                if (lodGroup.isLockLevelChanged()) {
                  lodGroup.resetLockChangeFlag();
                  _lodModels2.forEach(function (vecArray, index) {
                    vecArray.forEach(function (model) {
                      var modelInfo = _this._modelsInLODGroup.get(model);
                      if (modelInfo) {
                        modelInfo.clear();
                      }
                    });
                  });
                  hasUpdated = true;
                } else if (hasUpdated) {
                  _this._lodStateInCamera.forEach(function (lodState, camera) {
                    var lodInfo = lodState.get(lodGroup);
                    if (lodInfo && lodInfo.usedLevel !== lodInfo.lastUsedLevel) {
                      var _vecModels = _lodModels2.get(lodInfo.lastUsedLevel);
                      if (_vecModels) {
                        _vecModels.forEach(function (model) {
                          var modelInfo = _this._modelsInLODGroup.get(model);
                          if (modelInfo) {
                            modelInfo.clear();
                          }
                        });
                      }
                    }
                  });
                }
                if (hasUpdated) {
                  _this._lodStateInCamera.forEach(function (lodState, camera) {
                    var lodInfo = lodState.get(lodGroup);
                    if (lodInfo) {
                      var usedLevel = lodInfo.usedLevel;
                      var _vecModels2 = _lodModels2.get(usedLevel);
                      if (_vecModels2) {
                        _vecModels2.forEach(function (model) {
                          var modelInfo = _this._modelsInLODGroup.get(model);
                          if (modelInfo && model.node && model.node.active) {
                            modelInfo.set(camera, true);
                          }
                        });
                      }
                    }
                  });
                }
              }
            },
            _ret;
          for (var _iterator10 = _createForOfIteratorHelperLoose(this._renderScene.lodGroups), _step10; !(_step10 = _iterator10()).done;) {
            _ret = _loop();
            if (_ret === 0) continue;
          }
        };
        _proto2.isLodModelCulled = function isLodModelCulled(camera, model) {
          var modelInfo = this._modelsInLODGroup.get(model);
          if (!modelInfo) {
            return false;
          }
          return !modelInfo.has(camera);
        };
        _proto2.clearCache = function clearCache() {
          this._levelModels.clear();
          this._modelsInLODGroup.clear();
          this._lodStateInCamera.clear();
          this._newAddedLodGroupVec.length = 0;
        };
        _proto2.isLodGroupVisibleByCamera = function isLodGroupVisibleByCamera(lodGroup, camera) {
          var layer = lodGroup.node.layer;
          return (camera.visibility & layer) === layer;
        };
        return LodStateCache;
      }();

      var _orientationMap$1;
      var orientationMap$1 = (_orientationMap$1 = {}, _orientationMap$1[Orientation.PORTRAIT] = SurfaceTransform.IDENTITY, _orientationMap$1[Orientation.LANDSCAPE_RIGHT] = SurfaceTransform.ROTATE_90, _orientationMap$1[Orientation.PORTRAIT_UPSIDE_DOWN] = SurfaceTransform.ROTATE_180, _orientationMap$1[Orientation.LANDSCAPE_LEFT] = SurfaceTransform.ROTATE_270, _orientationMap$1);
      var RenderWindow = function () {
        RenderWindow.registerCreateFunc = function registerCreateFunc(root) {
          root._createWindowFun = function (_root) {
            return new RenderWindow();
          };
        };
        function RenderWindow(root) {
          this._title = '';
          this._width = 1;
          this._height = 1;
          this._swapchain = null;
          this._renderPass = null;
          this._colorTextures = [];
          this._depthStencilTexture = null;
          this._cameras = [];
          this._hasOnScreenAttachments = false;
          this._hasOffScreenAttachments = false;
          this._framebuffer = null;
          this._device = null;
        }
        var _proto = RenderWindow.prototype;
        _proto.initialize = function initialize(device, info) {
          if (info.title !== undefined) {
            this._title = info.title;
          }
          if (info.swapchain !== undefined) {
            this._swapchain = info.swapchain;
          }
          this._width = info.width;
          this._height = info.height;
          this._device = device;
          this._renderPass = device.createRenderPass(info.renderPassInfo);
          if (info.swapchain) {
            this._swapchain = info.swapchain;
            this._colorTextures.push(info.swapchain.colorTexture);
            this._depthStencilTexture = info.swapchain.depthStencilTexture;
          } else {
            for (var i = 0; i < info.renderPassInfo.colorAttachments.length; i++) {
              var textureInfo = new TextureInfo(TextureType.TEX2D, TextureUsageBit.COLOR_ATTACHMENT | TextureUsageBit.SAMPLED | TextureUsageBit.TRANSFER_SRC, info.renderPassInfo.colorAttachments[i].format, this._width, this._height);
              if (info.externalFlag && (info.externalFlag & TextureFlagBit.EXTERNAL_NORMAL || info.externalFlag & TextureFlagBit.EXTERNAL_OES)) {
                textureInfo.flags |= info.externalFlag;
                textureInfo.externalRes = info.externalResLow ? info.externalResLow : 0;
              }
              this._colorTextures.push(device.createTexture(textureInfo));
            }
            if (info.renderPassInfo.depthStencilAttachment.format !== Format.UNKNOWN) {
              this._depthStencilTexture = device.createTexture(new TextureInfo(TextureType.TEX2D, TextureUsageBit.DEPTH_STENCIL_ATTACHMENT | TextureUsageBit.SAMPLED, info.renderPassInfo.depthStencilAttachment.format, this._width, this._height));
              this._hasOffScreenAttachments = true;
            }
          }
          this._framebuffer = device.createFramebuffer(new FramebufferInfo(this._renderPass, this._colorTextures, this._depthStencilTexture));
          return true;
        };
        _proto.destroy = function destroy() {
          this.clearCameras();
          if (this._framebuffer) {
            this._framebuffer.destroy();
            this._framebuffer = null;
          }
          if (this._depthStencilTexture) {
            this._depthStencilTexture.destroy();
            this._depthStencilTexture = null;
          }
          for (var i = 0; i < this._colorTextures.length; i++) {
            var colorTexture = this._colorTextures[i];
            if (colorTexture) {
              colorTexture.destroy();
            }
          }
          this._colorTextures.length = 0;
          this._device = null;
        };
        _proto.resize = function resize(width, height) {
          if (this._swapchain) {
            this._swapchain.resize(width, height, orientationMap$1[screenAdapter.orientation]);
            this._width = this._swapchain.width;
            this._height = this._swapchain.height;
          } else {
            for (var i = 0; i < this._colorTextures.length; i++) {
              this._colorTextures[i].resize(width, height);
            }
            if (this._depthStencilTexture) {
              this._depthStencilTexture.resize(width, height);
            }
            this._width = width;
            this._height = height;
          }
          if (this.framebuffer) {
            this.framebuffer.destroy();
            this._framebuffer = this._device.createFramebuffer(new FramebufferInfo(this._renderPass, this._colorTextures, this._depthStencilTexture));
          }
          for (var _iterator = _createForOfIteratorHelperLoose(this._cameras), _step; !(_step = _iterator()).done;) {
            var camera = _step.value;
            camera.resize(width, height);
          }
        };
        _proto.extractRenderCameras = function extractRenderCameras(cameras) {
          for (var j = 0; j < this._cameras.length; j++) {
            var camera = this._cameras[j];
            if (camera.enabled) {
              camera.update();
              cameras.push(camera);
            }
          }
        };
        _proto.attachCamera = function attachCamera(camera) {
          for (var i = 0; i < this._cameras.length; i++) {
            if (this._cameras[i] === camera) {
              return;
            }
          }
          this._cameras.push(camera);
          this.sortCameras();
        };
        _proto.detachCamera = function detachCamera(camera) {
          for (var i = 0; i < this._cameras.length; ++i) {
            if (this._cameras[i] === camera) {
              this._cameras.splice(i, 1);
              return;
            }
          }
        };
        _proto.clearCameras = function clearCameras() {
          this._cameras.length = 0;
        };
        _proto.sortCameras = function sortCameras() {
          this._cameras.sort(function (a, b) {
            return a.priority - b.priority;
          });
        };
        _createClass(RenderWindow, [{
          key: "width",
          get: function get() {
            return this._width;
          }
        }, {
          key: "height",
          get: function get() {
            return this._height;
          }
        }, {
          key: "swapchain",
          get: function get() {
            return this._swapchain;
          }
        }, {
          key: "framebuffer",
          get: function get() {
            return this._framebuffer;
          }
        }, {
          key: "cameras",
          get: function get() {
            return this._cameras;
          }
        }]);
        return RenderWindow;
      }();

      var Root = exports('az', function () {
        function Root(device) {
          var _this = this;
          this._createSceneFun = null;
          this._createWindowFun = null;
          this._device = void 0;
          this._windows = [];
          this._mainWindow = null;
          this._curWindow = null;
          this._tempWindow = null;
          this._usesCustomPipeline = true;
          this._pipeline = null;
          this._pipelineEvent = null;
          this._classicPipeline = null;
          this._customPipeline = null;
          this._batcher = null;
          this._dataPoolMgr = void 0;
          this._scenes = [];
          this._modelPools = new Map();
          this._cameraPool = null;
          this._lightPools = new Map();
          this._debugView = new DebugView();
          this._fpsTime = 0;
          this._frameCount = 0;
          this._fps = 0;
          this._fixedFPS = 0;
          this._useDeferredPipeline = false;
          this._fixedFPSFrameTime = 0;
          this._cumulativeTime = 0;
          this._frameTime = 0;
          this._cameraList = [];
          this._device = device;
          this._dataPoolMgr = legacyCC.internal.DataPoolManager && new legacyCC.internal.DataPoolManager(device);
          RenderScene.registerCreateFunc(this);
          RenderWindow.registerCreateFunc(this);
          this._cameraPool = new Pool(function () {
            return new Camera$1(_this._device);
          }, 4, function (cam) {
            return cam.destroy();
          });
        }
        var _proto = Root.prototype;
        _proto.initialize = function initialize(info) {
          var _this$_dataPoolMgr;
          var swapchain = deviceManager.swapchain;
          var colorAttachment = new ColorAttachment();
          colorAttachment.format = swapchain.colorTexture.format;
          var depthStencilAttachment = new DepthStencilAttachment();
          depthStencilAttachment.format = swapchain.depthStencilTexture.format;
          depthStencilAttachment.depthStoreOp = StoreOp.DISCARD;
          depthStencilAttachment.stencilStoreOp = StoreOp.DISCARD;
          var renderPassInfo = new RenderPassInfo([colorAttachment], depthStencilAttachment);
          this._mainWindow = this.createWindow({
            title: 'rootMainWindow',
            width: swapchain.width,
            height: swapchain.height,
            renderPassInfo: renderPassInfo,
            swapchain: swapchain
          });
          this._curWindow = this._mainWindow;
          var customJointTextureLayouts = settings.querySettings(Settings.Category.ANIMATION, 'customJointTextureLayouts') || [];
          (_this$_dataPoolMgr = this._dataPoolMgr) === null || _this$_dataPoolMgr === void 0 ? void 0 : _this$_dataPoolMgr.jointTexturePool.registerCustomTextureLayouts(customJointTextureLayouts);
          this._resizeMaxJointForDS();
        };
        _proto.destroy = function destroy() {
          this.destroyScenes();
          if (this._pipeline) {
            this._pipeline.destroy();
            this._pipeline = null;
            this._pipelineEvent = null;
          }
          if (this._batcher) {
            this._batcher.destroy();
            this._batcher = null;
          }
          this._curWindow = null;
          this._mainWindow = null;
          this.dataPoolManager.clear();
          if (legacyCC.rendering) {
            legacyCC.rendering.destroy();
          }
        };
        _proto.resize = function resize(width, height, windowId) {
          for (var _iterator = _createForOfIteratorHelperLoose(this._windows), _step; !(_step = _iterator()).done;) {
            var window = _step.value;
            if (window.swapchain) {
              window.resize(width, height);
            }
          }
        };
        _proto.setRenderPipeline = function setRenderPipeline(rppl) {
          var internal = legacyCC.internal,
            director = legacyCC.director,
            rendering = legacyCC.rendering;
          if (rppl instanceof DeferredPipeline) {
            this._useDeferredPipeline = true;
          }
          var isCreateDefaultPipeline = false;
          if (!rppl) {
            rppl = createDefaultPipeline();
            isCreateDefaultPipeline = true;
          }
          if (!this._useDeferredPipeline || !this.device.hasFeature(Feature.COMPUTE_SHADER)) {
            rppl.clusterEnabled = false;
          }
          rppl.bloomEnabled = false;
          if (macro.CUSTOM_PIPELINE_NAME !== '' && rendering && this.usesCustomPipeline) {
            this._customPipeline = rendering.createCustomPipeline();
            isCreateDefaultPipeline = true;
            this._pipeline = this._customPipeline;
            this._pipelineEvent = rppl;
          } else {
            this._classicPipeline = rppl;
            this._pipeline = this._classicPipeline;
            this._pipelineEvent = this._classicPipeline;
            this._usesCustomPipeline = false;
          }
          var renderMode = settings.querySettings(Settings.Category.RENDERING, 'renderMode');
          if (renderMode !== LegacyRenderMode.HEADLESS || this._classicPipeline) {
            if (!this._pipeline.activate(this._mainWindow.swapchain)) {
              if (isCreateDefaultPipeline) {
                this._pipeline.destroy();
              }
              this._classicPipeline = null;
              this._customPipeline = null;
              this._pipeline = null;
              this._pipelineEvent = null;
              return false;
            }
          }
          var scene = director.getScene();
          if (scene) {
            scene.globals.activate();
          }
          this.onGlobalPipelineStateChanged();
          if (!this._batcher && internal.Batcher2D) {
            this._batcher = new internal.Batcher2D(this);
            if (!this._batcher.initialize()) {
              this.destroy();
              return false;
            }
          }
          return true;
        };
        _proto.onGlobalPipelineStateChanged = function onGlobalPipelineStateChanged() {
          for (var i = 0; i < this._scenes.length; i++) {
            this._scenes[i].onGlobalPipelineStateChanged();
          }
          if (this._pipeline.pipelineSceneData.skybox.enabled) {
            this._pipeline.pipelineSceneData.skybox.model.onGlobalPipelineStateChanged();
          }
          this._pipeline.onGlobalPipelineStateChanged();
        };
        _proto.activeWindow = function activeWindow(window) {
          this._curWindow = window;
        };
        _proto.resetCumulativeTime = function resetCumulativeTime() {
          this._cumulativeTime = 0;
        };
        _proto.frameMove = function frameMove(deltaTime) {
          var _globalThis$__globalX;
          this._frameTime = deltaTime;
          ++this._frameCount;
          this._cumulativeTime += deltaTime;
          this._fpsTime += deltaTime;
          if (this._fpsTime > 1.0) {
            this._fps = this._frameCount;
            this._frameCount = 0;
            this._fpsTime = 0.0;
          }
          if ((_globalThis$__globalX = globalThis.__globalXR) !== null && _globalThis$__globalX !== void 0 && _globalThis$__globalX.isWebXR) {
            this._doWebXRFrameMove();
          } else {
            this._frameMoveBegin();
            this._frameMoveProcess();
            this._frameMoveEnd();
          }
        };
        _proto.createWindow = function createWindow(info) {
          var window = this._createWindowFun(this);
          window.initialize(this.device, info);
          this._windows.push(window);
          return window;
        };
        _proto.destroyWindow = function destroyWindow(window) {
          for (var i = 0; i < this._windows.length; ++i) {
            if (this._windows[i] === window) {
              window.destroy();
              this._windows.splice(i, 1);
              return;
            }
          }
        };
        _proto.destroyWindows = function destroyWindows() {
          for (var _iterator2 = _createForOfIteratorHelperLoose(this._windows), _step2; !(_step2 = _iterator2()).done;) {
            var window = _step2.value;
            window.destroy();
          }
          this._windows.length = 0;
        };
        _proto.createScene = function createScene(info) {
          var scene = this._createSceneFun(this);
          scene.initialize(info);
          this._scenes.push(scene);
          return scene;
        };
        _proto.destroyScene = function destroyScene(scene) {
          for (var i = 0; i < this._scenes.length; ++i) {
            if (this._scenes[i] === scene) {
              scene.destroy();
              this._scenes.splice(i, 1);
              return;
            }
          }
        };
        _proto.destroyScenes = function destroyScenes() {
          for (var _iterator3 = _createForOfIteratorHelperLoose(this._scenes), _step3; !(_step3 = _iterator3()).done;) {
            var scene = _step3.value;
            scene.destroy();
          }
          this._scenes.length = 0;
        };
        _proto.createModel = function createModel(ModelCtor) {
          var p = this._modelPools.get(ModelCtor);
          if (!p) {
            this._modelPools.set(ModelCtor, new Pool(function () {
              return new ModelCtor();
            }, 10, function (obj) {
              return obj.destroy();
            }));
            p = this._modelPools.get(ModelCtor);
          }
          var model = p.alloc();
          model.initialize();
          return model;
        };
        _proto.destroyModel = function destroyModel(m) {
          var p = this._modelPools.get(m.constructor);
          if (p) {
            p.free(m);
            if (m.scene) {
              m.scene.removeModel(m);
            }
          } else {
            warnID(1300, m.constructor.name);
          }
          m.destroy();
        };
        _proto.createCamera = function createCamera() {
          return this._cameraPool.alloc();
        };
        _proto.createLight = function createLight(LightCtor) {
          var l = this._lightPools.get(LightCtor);
          if (!l) {
            this._lightPools.set(LightCtor, new Pool(function () {
              return new LightCtor();
            }, 4, function (obj) {
              return obj.destroy();
            }));
            l = this._lightPools.get(LightCtor);
          }
          var light = l.alloc();
          light.initialize();
          return light;
        };
        _proto.destroyLight = function destroyLight(l) {
          if (l.scene) {
            switch (l.type) {
              case LightType.DIRECTIONAL:
                l.scene.removeDirectionalLight(l);
                break;
              case LightType.SPHERE:
                l.scene.removeSphereLight(l);
                break;
              case LightType.SPOT:
                l.scene.removeSpotLight(l);
                break;
              case LightType.POINT:
                l.scene.removePointLight(l);
                break;
              case LightType.RANGED_DIRECTIONAL:
                l.scene.removeRangedDirLight(l);
                break;
            }
          }
          l.destroy();
        };
        _proto.recycleLight = function recycleLight(l) {
          var p = this._lightPools.get(l.constructor);
          if (p) {
            p.free(l);
            if (l.scene) {
              switch (l.type) {
                case LightType.DIRECTIONAL:
                  l.scene.removeDirectionalLight(l);
                  break;
                case LightType.SPHERE:
                  l.scene.removeSphereLight(l);
                  break;
                case LightType.SPOT:
                  l.scene.removeSpotLight(l);
                  break;
                case LightType.POINT:
                  l.scene.removePointLight(l);
                  break;
                case LightType.RANGED_DIRECTIONAL:
                  l.scene.removeRangedDirLight(l);
                  break;
              }
            }
          }
        };
        _proto._doWebXRFrameMove = function _doWebXRFrameMove() {
          var xr = globalThis.__globalXR;
          if (!xr) {
            return;
          }
          var windows = this._windows;
          var cameraList = this._cameraList;
          var viewCount = xr.webXRMatProjs ? xr.webXRMatProjs.length : 1;
          if (!xr.webXRWindowMap) {
            xr.webXRWindowMap = new Map();
          }
          var allcameras = [];
          var webxrHmdPoseInfos = xr.webxrHmdPoseInfos;
          for (var xrEye = 0; xrEye < viewCount; xrEye++) {
            for (var _iterator4 = _createForOfIteratorHelperLoose(windows), _step4; !(_step4 = _iterator4()).done;) {
              var window = _step4.value;
              allcameras = allcameras.concat(window.cameras);
              if (window.swapchain) {
                xr.webXRWindowMap.set(window, xrEye);
              }
            }
            if (webxrHmdPoseInfos) {
              var cameraPosition = [0, 0, 0];
              for (var i = 0; i < webxrHmdPoseInfos.length; i++) {
                var info = webxrHmdPoseInfos[i];
                if (info.code === XRPoseType.VIEW_LEFT && xrEye === XREye.LEFT || info.code === XRPoseType.VIEW_RIGHT && xrEye === XREye.RIGHT) {
                  cameraPosition[0] = info.position.x;
                  cameraPosition[1] = info.position.y;
                  cameraPosition[2] = info.position.z;
                  break;
                }
              }
              for (var _iterator5 = _createForOfIteratorHelperLoose(allcameras), _step5; !(_step5 = _iterator5()).done;) {
                var cam = _step5.value;
                if (cam.trackingType !== TrackingType.NO_TRACKING && cam.node) {
                  var isTrackingRotation = cam.trackingType === TrackingType.ROTATION;
                  if (isTrackingRotation) {
                    cameraPosition = [0, 0, 0];
                  }
                  cam.node.setPosition(cameraPosition[0], cameraPosition[1], cameraPosition[2]);
                }
              }
            }
            allcameras.length = 0;
            this._frameMoveBegin();
            this._frameMoveProcess();
            for (var _i = cameraList.length - 1; _i >= 0; _i--) {
              var camera = cameraList[_i];
              var isMismatchedCam = xrEye === XREye.LEFT && camera.cameraType === CameraType.RIGHT_EYE || xrEye === XREye.RIGHT && camera.cameraType === CameraType.LEFT_EYE;
              if (isMismatchedCam) {
                cameraList.splice(_i, 1);
              }
            }
            this._frameMoveEnd();
          }
        };
        _proto._frameMoveBegin = function _frameMoveBegin() {
          for (var i = 0; i < this._scenes.length; ++i) {
            this._scenes[i].removeBatches();
          }
          this._cameraList.length = 0;
        };
        _proto._frameMoveProcess = function _frameMoveProcess() {
          var director = legacyCC.director;
          var windows = this._windows;
          var cameraList = this._cameraList;
          for (var i = 0; i < windows.length; i++) {
            var window = windows[i];
            window.extractRenderCameras(cameraList);
          }
          if (this._pipeline && cameraList.length > 0) {
            this._device.acquire([deviceManager.swapchain]);
            var scenes = this._scenes;
            var stamp = director.getTotalFrames();
            if (this._batcher) {
              this._batcher.update();
              this._batcher.uploadBuffers();
            }
            for (var _i2 = 0; _i2 < scenes.length; _i2++) {
              scenes[_i2].update(stamp);
            }
          }
        };
        _proto._frameMoveEnd = function _frameMoveEnd() {
          var director = legacyCC.director,
            Director = legacyCC.Director;
          var cameraList = this._cameraList;
          if (this._pipeline && cameraList.length > 0) {
            director.emit(Director.EVENT_BEFORE_COMMIT);
            cameraList.sort(function (a, b) {
              return a.priority - b.priority;
            });
            for (var i = 0; i < cameraList.length; ++i) {
              var _cameraList$i$geometr;
              (_cameraList$i$geometr = cameraList[i].geometryRenderer) === null || _cameraList$i$geometr === void 0 ? void 0 : _cameraList$i$geometr.update();
            }
            director.emit(Director.EVENT_BEFORE_RENDER);
            this._pipeline.render(cameraList);
            director.emit(Director.EVENT_AFTER_RENDER);
            this._device.present();
          }
          if (this._batcher) this._batcher.reset();
        };
        _proto._resizeMaxJointForDS = function _resizeMaxJointForDS() {
          var usedUBOVectorCount = Math.max((UBOGlobal.COUNT + UBOCamera.COUNT + UBOShadow.COUNT + UBOLocal.COUNT + UBOWorldBound.COUNT) / 4, 100);
          var maxJoints = Math.floor((deviceManager.gfxDevice.capabilities.maxVertexUniformVectors - usedUBOVectorCount) / 3);
          maxJoints = maxJoints < 256 ? maxJoints : 256;
          localDescriptorSetLayout_ResizeMaxJoints(maxJoints);
        };
        _createClass(Root, [{
          key: "device",
          get: function get() {
            return this._device;
          }
        }, {
          key: "mainWindow",
          get: function get() {
            return this._mainWindow;
          }
        }, {
          key: "curWindow",
          get: function get() {
            return this._curWindow;
          },
          set: function set(window) {
            this._curWindow = window;
          }
        }, {
          key: "tempWindow",
          get: function get() {
            return this._tempWindow;
          },
          set: function set(window) {
            this._tempWindow = window;
          }
        }, {
          key: "windows",
          get: function get() {
            return this._windows;
          }
        }, {
          key: "usesCustomPipeline",
          get: function get() {
            return this._usesCustomPipeline;
          }
        }, {
          key: "pipeline",
          get: function get() {
            return this._pipeline;
          }
        }, {
          key: "customPipeline",
          get: function get() {
            return this._customPipeline;
          }
        }, {
          key: "pipelineEvent",
          get: function get() {
            return this._pipelineEvent;
          }
        }, {
          key: "batcher2D",
          get: function get() {
            return this._batcher;
          }
        }, {
          key: "scenes",
          get: function get() {
            return this._scenes;
          }
        }, {
          key: "debugView",
          get: function get() {
            return this._debugView;
          }
        }, {
          key: "cumulativeTime",
          get: function get() {
            return this._cumulativeTime;
          }
        }, {
          key: "frameTime",
          get: function get() {
            return this._frameTime;
          }
        }, {
          key: "frameCount",
          get: function get() {
            return this._frameCount;
          }
        }, {
          key: "fps",
          get: function get() {
            return this._fps;
          }
        }, {
          key: "fixedFPS",
          get: function get() {
            return this._fixedFPS;
          },
          set: function set(fps) {
            if (fps > 0) {
              this._fixedFPS = fps;
              this._fixedFPSFrameTime = 1000.0 / fps;
            } else {
              this._fixedFPSFrameTime = 0;
            }
          }
        }, {
          key: "dataPoolManager",
          get: function get() {
            return this._dataPoolMgr;
          }
        }, {
          key: "useDeferredPipeline",
          get: function get() {
            return this._useDeferredPipeline;
          }
        }, {
          key: "cameraList",
          get: function get() {
            return this._cameraList;
          }
        }]);
        return Root;
      }());
      legacyCC.Root = Root;

      CCClass.Attr.setClassAttr(EventHandler, 'target', 'type', 'Object');
      CCClass.Attr.setClassAttr(EventHandler, 'target', 'ctor', Node$1);

      var _cachedArray = new Array(16);
      var _currentHovered = null;
      var pos = new Vec2();
      var _touchEvents = [NodeEventType.TOUCH_START, NodeEventType.TOUCH_MOVE, NodeEventType.TOUCH_END, NodeEventType.TOUCH_CANCEL];
      var _mouseEvents = [NodeEventType.MOUSE_DOWN, NodeEventType.MOUSE_ENTER, NodeEventType.MOUSE_MOVE, NodeEventType.MOUSE_LEAVE, NodeEventType.MOUSE_UP, NodeEventType.MOUSE_WHEEL];
      var DispatcherEventType;
      (function (DispatcherEventType) {
        DispatcherEventType[DispatcherEventType["ADD_POINTER_EVENT_PROCESSOR"] = 0] = "ADD_POINTER_EVENT_PROCESSOR";
        DispatcherEventType[DispatcherEventType["REMOVE_POINTER_EVENT_PROCESSOR"] = 1] = "REMOVE_POINTER_EVENT_PROCESSOR";
        DispatcherEventType[DispatcherEventType["MARK_LIST_DIRTY"] = 2] = "MARK_LIST_DIRTY";
      })(DispatcherEventType || (DispatcherEventType = {}));
      var NodeEventProcessor = function () {
        function NodeEventProcessor(node) {
          this.claimedTouchIdList = [];
          this.maskList = null;
          this.cachedCameraPriority = 0;
          this.previousMouseIn = false;
          this.bubblingTarget = null;
          this.capturingTarget = null;
          this.shouldHandleEventMouse = false;
          this.shouldHandleEventTouch = false;
          this._dispatchingTouch = null;
          this._isEnabled = false;
          this._node = void 0;
          this._node = node;
        }
        var _proto = NodeEventProcessor.prototype;
        _proto.setEnabled = function setEnabled(value, recursive) {
          if (recursive === void 0) {
            recursive = false;
          }
          if (this._isEnabled === value) {
            return;
          }
          this._isEnabled = value;
          var node = this.node;
          var children = node.children;
          if (value) {
            this._attachMask();
          }
          NodeEventProcessor.callbacksInvoker.emit(DispatcherEventType.MARK_LIST_DIRTY);
          if (recursive && children.length > 0) {
            for (var i = 0; i < children.length; ++i) {
              var child = children[i];
              child.eventProcessor.setEnabled(value, true);
            }
          }
          if (this._dispatchingTouch && !this._isEnabled) {
            var cancelEvent = new EventTouch([this._dispatchingTouch], true, InputEventType.TOUCH_CANCEL);
            cancelEvent.touch = this._dispatchingTouch;
            this.dispatchEvent(cancelEvent);
            this.claimedTouchIdList.length = 0;
            this._dispatchingTouch = null;
          }
        };
        _proto.reattach = function reattach() {
          var _this = this;
          var currentMaskList;
          this.node.walk(function (node) {
            if (!currentMaskList) {
              currentMaskList = _this._searchComponentsInParent(NodeEventProcessor._maskComp);
            }
            node.eventProcessor.maskList = currentMaskList;
          });
        };
        _proto.destroy = function destroy() {
          if (_currentHovered === this._node) {
            _currentHovered = null;
          }
          if (this.capturingTarget) this.capturingTarget.clear();
          if (this.bubblingTarget) this.bubblingTarget.clear();
          NodeEventProcessor.callbacksInvoker.emit(DispatcherEventType.REMOVE_POINTER_EVENT_PROCESSOR, this);
          if (this._dispatchingTouch) {
            var cancelEvent = new EventTouch([this._dispatchingTouch], true, InputEventType.TOUCH_CANCEL);
            cancelEvent.touch = this._dispatchingTouch;
            this.dispatchEvent(cancelEvent);
            this._dispatchingTouch = null;
          }
        };
        _proto.on = function on(type, callback, target, useCapture) {
          this._tryEmittingAddEvent(type);
          useCapture = !!useCapture;
          var invoker;
          if (useCapture) {
            var _this$capturingTarget;
            invoker = (_this$capturingTarget = this.capturingTarget) !== null && _this$capturingTarget !== void 0 ? _this$capturingTarget : this.capturingTarget = this._newCallbacksInvoker();
          } else {
            var _this$bubblingTarget;
            invoker = (_this$bubblingTarget = this.bubblingTarget) !== null && _this$bubblingTarget !== void 0 ? _this$bubblingTarget : this.bubblingTarget = this._newCallbacksInvoker();
          }
          invoker.on(type, callback, target);
          return callback;
        };
        _proto.once = function once(type, callback, target, useCapture) {
          this._tryEmittingAddEvent(type);
          useCapture = !!useCapture;
          var invoker;
          if (useCapture) {
            var _this$capturingTarget2;
            invoker = (_this$capturingTarget2 = this.capturingTarget) !== null && _this$capturingTarget2 !== void 0 ? _this$capturingTarget2 : this.capturingTarget = this._newCallbacksInvoker();
          } else {
            var _this$bubblingTarget2;
            invoker = (_this$bubblingTarget2 = this.bubblingTarget) !== null && _this$bubblingTarget2 !== void 0 ? _this$bubblingTarget2 : this.bubblingTarget = this._newCallbacksInvoker();
          }
          invoker.on(type, callback, target, true);
          return callback;
        };
        _proto.off = function off(type, callback, target, useCapture) {
          var _invoker;
          useCapture = !!useCapture;
          var invoker;
          if (useCapture) {
            invoker = this.capturingTarget;
          } else {
            invoker = this.bubblingTarget;
          }
          (_invoker = invoker) === null || _invoker === void 0 ? void 0 : _invoker.off(type, callback, target);
        };
        _proto.targetOff = function targetOff(target) {
          var _this$capturingTarget3, _this$bubblingTarget3;
          (_this$capturingTarget3 = this.capturingTarget) === null || _this$capturingTarget3 === void 0 ? void 0 : _this$capturingTarget3.removeAll(target);
          (_this$bubblingTarget3 = this.bubblingTarget) === null || _this$bubblingTarget3 === void 0 ? void 0 : _this$bubblingTarget3.removeAll(target);
          if (this.shouldHandleEventTouch && !this._hasTouchListeners()) {
            this.shouldHandleEventTouch = false;
          }
          if (this.shouldHandleEventMouse && !this._hasMouseListeners()) {
            this.shouldHandleEventMouse = false;
          }
          if (!this._hasPointerListeners()) {
            NodeEventProcessor.callbacksInvoker.emit(DispatcherEventType.REMOVE_POINTER_EVENT_PROCESSOR, this);
          }
        };
        _proto.emit = function emit(type, arg0, arg1, arg2, arg3, arg4) {
          var _this$bubblingTarget4;
          (_this$bubblingTarget4 = this.bubblingTarget) === null || _this$bubblingTarget4 === void 0 ? void 0 : _this$bubblingTarget4.emit(type, arg0, arg1, arg2, arg3, arg4);
        };
        _proto.dispatchEvent = function dispatchEvent(event) {
          var owner = this.node;
          var target;
          var i = 0;
          event.target = owner;
          _cachedArray.length = 0;
          this.getCapturingTargets(event.type, _cachedArray);
          event.eventPhase = 1;
          for (i = _cachedArray.length - 1; i >= 0; --i) {
            target = _cachedArray[i];
            if (target.eventProcessor.capturingTarget) {
              event.currentTarget = target;
              target.eventProcessor.capturingTarget.emit(event.type, event, _cachedArray);
              if (event.propagationStopped) {
                _cachedArray.length = 0;
                return;
              }
            }
          }
          _cachedArray.length = 0;
          event.eventPhase = 2;
          event.currentTarget = owner;
          if (this.capturingTarget) {
            this.capturingTarget.emit(event.type, event);
          }
          if (!event.propagationImmediateStopped && this.bubblingTarget) {
            this.bubblingTarget.emit(event.type, event);
          }
          if (!event.propagationStopped && event.bubbles) {
            this.getBubblingTargets(event.type, _cachedArray);
            event.eventPhase = 3;
            for (i = 0; i < _cachedArray.length; ++i) {
              target = _cachedArray[i];
              if (target.eventProcessor.bubblingTarget) {
                event.currentTarget = target;
                target.eventProcessor.bubblingTarget.emit(event.type, event);
                if (event.propagationStopped) {
                  _cachedArray.length = 0;
                  return;
                }
              }
            }
          }
          _cachedArray.length = 0;
        };
        _proto.hasEventListener = function hasEventListener(type, callback, target) {
          var has = false;
          if (this.bubblingTarget) {
            has = this.bubblingTarget.hasEventListener(type, callback, target);
          }
          if (!has && this.capturingTarget) {
            has = this.capturingTarget.hasEventListener(type, callback, target);
          }
          return has;
        };
        _proto.getCapturingTargets = function getCapturingTargets(type, targets) {
          var parent = this._node.parent;
          while (parent) {
            var _parent$eventProcesso;
            if ((_parent$eventProcesso = parent.eventProcessor.capturingTarget) !== null && _parent$eventProcesso !== void 0 && _parent$eventProcesso.hasEventListener(type)) {
              targets.push(parent);
            }
            parent = parent.parent;
          }
        };
        _proto.getBubblingTargets = function getBubblingTargets(type, targets) {
          var parent = this._node.parent;
          while (parent) {
            var _parent$eventProcesso2;
            if ((_parent$eventProcesso2 = parent.eventProcessor.bubblingTarget) !== null && _parent$eventProcesso2 !== void 0 && _parent$eventProcesso2.hasEventListener(type)) {
              targets.push(parent);
            }
            parent = parent.parent;
          }
        };
        _proto.onUpdatingSiblingIndex = function onUpdatingSiblingIndex() {
          NodeEventProcessor.callbacksInvoker.emit(DispatcherEventType.MARK_LIST_DIRTY);
        };
        _proto._searchComponentsInParent = function _searchComponentsInParent(ctor) {
          var node = this.node;
          if (ctor) {
            var index = 0;
            var list = [];
            for (var curr = node; curr && Node$1.isNode(curr); curr = curr.parent, ++index) {
              var comp = curr.getComponent(ctor);
              if (comp) {
                var next = {
                  index: index,
                  comp: comp
                };
                if (list) {
                  list.push(next);
                } else {
                  list = [next];
                }
              }
            }
            return list.length > 0 ? list : null;
          }
          return null;
        };
        _proto._attachMask = function _attachMask() {
          this.maskList = this._searchComponentsInParent(NodeEventProcessor._maskComp);
        };
        _proto._isTouchEvent = function _isTouchEvent(type) {
          var index = _touchEvents.indexOf(type);
          return index !== -1;
        };
        _proto._isMouseEvent = function _isMouseEvent(type) {
          var index = _mouseEvents.indexOf(type);
          return index !== -1;
        };
        _proto._hasTouchListeners = function _hasTouchListeners() {
          for (var i = 0; i < _touchEvents.length; ++i) {
            var eventType = _touchEvents[i];
            if (this.hasEventListener(eventType)) {
              return true;
            }
          }
          return false;
        };
        _proto._hasMouseListeners = function _hasMouseListeners() {
          for (var i = 0; i < _mouseEvents.length; ++i) {
            var eventType = _mouseEvents[i];
            if (this.hasEventListener(eventType)) {
              return true;
            }
          }
          return false;
        };
        _proto._hasPointerListeners = function _hasPointerListeners() {
          var has = this._hasTouchListeners();
          if (has) {
            return true;
          }
          return this._hasMouseListeners();
        };
        _proto._tryEmittingAddEvent = function _tryEmittingAddEvent(typeToAdd) {
          var isTouchEvent = this._isTouchEvent(typeToAdd);
          var isMouseEvent = this._isMouseEvent(typeToAdd);
          if (isTouchEvent) {
            this.shouldHandleEventTouch = true;
          } else if (isMouseEvent) {
            this.shouldHandleEventMouse = true;
          }
          if ((isTouchEvent || isMouseEvent) && !this._hasPointerListeners()) {
            NodeEventProcessor.callbacksInvoker.emit(DispatcherEventType.ADD_POINTER_EVENT_PROCESSOR, this);
          }
        };
        _proto._newCallbacksInvoker = function _newCallbacksInvoker() {
          var _this2 = this;
          var callbacksInvoker = new CallbacksInvoker();
          callbacksInvoker._registerOffCallback(function () {
            if (_this2.shouldHandleEventTouch && !_this2._hasTouchListeners()) {
              _this2.shouldHandleEventTouch = false;
            }
            if (_this2.shouldHandleEventMouse && !_this2._hasMouseListeners()) {
              _this2.shouldHandleEventMouse = false;
            }
            if (!_this2._hasPointerListeners()) {
              NodeEventProcessor.callbacksInvoker.emit(DispatcherEventType.REMOVE_POINTER_EVENT_PROCESSOR, _this2);
            }
          });
          return callbacksInvoker;
        };
        _proto._handleEventMouse = function _handleEventMouse(eventMouse) {
          switch (eventMouse.type) {
            case InputEventType.MOUSE_DOWN:
              return this._handleMouseDown(eventMouse);
            case InputEventType.MOUSE_MOVE:
              return this._handleMouseMove(eventMouse);
            case InputEventType.MOUSE_UP:
              return this._handleMouseUp(eventMouse);
            case InputEventType.MOUSE_WHEEL:
              return this._handleMouseWheel(eventMouse);
            default:
              return false;
          }
        };
        _proto._handleMouseDown = function _handleMouseDown(event) {
          var node = this._node;
          if (!node || !node._uiProps.uiTransformComp) {
            return false;
          }
          event.getLocation(pos);
          if (node._uiProps.uiTransformComp.hitTest(pos, event.windowId)) {
            event.type = NodeEventType.MOUSE_DOWN;
            event.bubbles = true;
            node.dispatchEvent(event);
            event.propagationStopped = true;
            return true;
          }
          return false;
        };
        _proto._handleMouseMove = function _handleMouseMove(event) {
          var node = this._node;
          if (!node || !node._uiProps.uiTransformComp) {
            return false;
          }
          event.getLocation(pos);
          var hit = node._uiProps.uiTransformComp.hitTest(pos, event.windowId);
          if (hit) {
            if (!this.previousMouseIn) {
              if (_currentHovered && _currentHovered !== node) {
                event.type = NodeEventType.MOUSE_LEAVE;
                _currentHovered.dispatchEvent(event);
                _currentHovered.eventProcessor.previousMouseIn = false;
              }
              _currentHovered = node;
              event.type = NodeEventType.MOUSE_ENTER;
              node.dispatchEvent(event);
              this.previousMouseIn = true;
            }
            event.type = NodeEventType.MOUSE_MOVE;
            event.bubbles = true;
            node.dispatchEvent(event);
            event.propagationStopped = true;
            return true;
          } else if (this.previousMouseIn) {
            event.type = NodeEventType.MOUSE_LEAVE;
            node.dispatchEvent(event);
            this.previousMouseIn = false;
            _currentHovered = null;
          }
          return false;
        };
        _proto._handleMouseUp = function _handleMouseUp(event) {
          var node = this._node;
          if (!node || !node._uiProps.uiTransformComp) {
            return false;
          }
          event.getLocation(pos);
          if (node._uiProps.uiTransformComp.hitTest(pos, event.windowId)) {
            event.type = NodeEventType.MOUSE_UP;
            event.bubbles = true;
            node.dispatchEvent(event);
            event.propagationStopped = true;
            return true;
          }
          return false;
        };
        _proto._handleMouseWheel = function _handleMouseWheel(event) {
          var node = this._node;
          if (!node || !node._uiProps.uiTransformComp) {
            return false;
          }
          event.getLocation(pos);
          if (node._uiProps.uiTransformComp.hitTest(pos, event.windowId)) {
            event.type = NodeEventType.MOUSE_WHEEL;
            event.bubbles = true;
            node.dispatchEvent(event);
            event.propagationStopped = true;
            return true;
          }
          return false;
        };
        _proto._handleEventTouch = function _handleEventTouch(eventTouch) {
          switch (eventTouch.type) {
            case InputEventType.TOUCH_START:
              return this._handleTouchStart(eventTouch);
            case InputEventType.TOUCH_MOVE:
              return this._handleTouchMove(eventTouch);
            case InputEventType.TOUCH_END:
              return this._handleTouchEnd(eventTouch);
            case InputEventType.TOUCH_CANCEL:
              return this._handleTouchCancel(eventTouch);
            default:
              return false;
          }
        };
        _proto._handleTouchStart = function _handleTouchStart(event) {
          var node = this.node;
          if (!node || !node._uiProps.uiTransformComp) {
            return false;
          }
          event.getLocation(pos);
          if (node._uiProps.uiTransformComp.hitTest(pos, event.windowId)) {
            event.type = NodeEventType.TOUCH_START;
            event.bubbles = true;
            this._dispatchingTouch = event.touch;
            node.dispatchEvent(event);
            return true;
          }
          return false;
        };
        _proto._handleTouchMove = function _handleTouchMove(event) {
          var node = this.node;
          if (!node || !node._uiProps.uiTransformComp) {
            return false;
          }
          event.type = NodeEventType.TOUCH_MOVE;
          event.bubbles = true;
          this._dispatchingTouch = event.touch;
          node.dispatchEvent(event);
          return true;
        };
        _proto._handleTouchEnd = function _handleTouchEnd(event) {
          var node = this.node;
          if (!node || !node._uiProps.uiTransformComp) {
            return;
          }
          event.getLocation(pos);
          if (node._uiProps.uiTransformComp.hitTest(pos, event.windowId)) {
            event.type = NodeEventType.TOUCH_END;
          } else {
            event.type = NodeEventType.TOUCH_CANCEL;
          }
          event.bubbles = true;
          node.dispatchEvent(event);
          this._dispatchingTouch = null;
        };
        _proto._handleTouchCancel = function _handleTouchCancel(event) {
          var node = this.node;
          if (!node || !node._uiProps.uiTransformComp) {
            return;
          }
          event.type = NodeEventType.TOUCH_CANCEL;
          event.bubbles = true;
          node.dispatchEvent(event);
        };
        _createClass(NodeEventProcessor, [{
          key: "isEnabled",
          get: function get() {
            return this._isEnabled;
          }
        }, {
          key: "node",
          get: function get() {
            return this._node;
          }
        }]);
        return NodeEventProcessor;
      }();
      NodeEventProcessor._maskComp = null;
      NodeEventProcessor.callbacksInvoker = new CallbacksInvoker();
      legacyCC.NodeEventProcessor = NodeEventProcessor;

      function find(path, referenceNode) {
        if (!referenceNode) {
          var scene = legacyCC.director.getScene();
          if (!scene) {
            return null;
          }
          referenceNode = scene;
        }
        return referenceNode.getChildByPath(path);
      }
      legacyCC.find = find;

      var fastRemoveAt = fastRemoveAt$2;
      var IsStartCalled = CCObject.Flags.IsStartCalled;
      var IsOnEnableCalled$1 = CCObject.Flags.IsOnEnableCalled;
      CCObject.Flags.IsEditorOnEnableCalled;
      function sortedIndex(array, comp) {
        var order = comp.constructor._executionOrder;
        var id = comp._id;
        var l = 0;
        for (var h = array.length - 1, m = h >>> 1; l <= h; m = l + h >>> 1) {
          var test = array[m];
          var testOrder = test.constructor._executionOrder;
          if (testOrder > order) {
            h = m - 1;
          } else if (testOrder < order) {
            l = m + 1;
          } else {
            var testId = test._id;
            if (testId > id) {
              h = m - 1;
            } else if (testId < id) {
              l = m + 1;
            } else {
              return m;
            }
          }
        }
        return ~l;
      }
      function stableRemoveInactive(iterator, flagToClear) {
        var array = iterator.array;
        var next = iterator.i + 1;
        while (next < array.length) {
          var comp = array[next];
          if (comp.node._activeInHierarchy) {
            ++next;
          } else {
            iterator.removeAt(next);
            if (flagToClear) {
              comp._objFlags &= ~flagToClear;
            }
          }
        }
      }
      var LifeCycleInvoker = function () {
        function LifeCycleInvoker(invokeFunc) {
          this._zero = void 0;
          this._neg = void 0;
          this._pos = void 0;
          this._invoke = void 0;
          var Iterator = MutableForwardIterator;
          this._zero = new Iterator([]);
          this._neg = new Iterator([]);
          this._pos = new Iterator([]);
          this._invoke = invokeFunc;
        }
        _createClass(LifeCycleInvoker, [{
          key: "zero",
          get: function get() {
            return this._zero;
          }
        }, {
          key: "neg",
          get: function get() {
            return this._neg;
          }
        }, {
          key: "pos",
          get: function get() {
            return this._pos;
          }
        }]);
        return LifeCycleInvoker;
      }();
      LifeCycleInvoker.stableRemoveInactive = stableRemoveInactive;
      function compareOrder(a, b) {
        return a.constructor._executionOrder - b.constructor._executionOrder;
      }
      var OneOffInvoker = function (_LifeCycleInvoker) {
        _inheritsLoose(OneOffInvoker, _LifeCycleInvoker);
        function OneOffInvoker() {
          return _LifeCycleInvoker.apply(this, arguments) || this;
        }
        var _proto = OneOffInvoker.prototype;
        _proto.add = function add(comp) {
          var order = comp.constructor._executionOrder;
          (order === 0 ? this._zero : order < 0 ? this._neg : this._pos).array.push(comp);
        };
        _proto.remove = function remove(comp) {
          var order = comp.constructor._executionOrder;
          (order === 0 ? this._zero : order < 0 ? this._neg : this._pos).fastRemove(comp);
        };
        _proto.cancelInactive = function cancelInactive(flagToClear) {
          stableRemoveInactive(this._zero, flagToClear);
          stableRemoveInactive(this._neg, flagToClear);
          stableRemoveInactive(this._pos, flagToClear);
        };
        _proto.invoke = function invoke() {
          var compsNeg = this._neg;
          if (compsNeg.array.length > 0) {
            compsNeg.array.sort(compareOrder);
            this._invoke(compsNeg);
            compsNeg.array.length = 0;
          }
          this._invoke(this._zero);
          this._zero.array.length = 0;
          var compsPos = this._pos;
          if (compsPos.array.length > 0) {
            compsPos.array.sort(compareOrder);
            this._invoke(compsPos);
            compsPos.array.length = 0;
          }
        };
        return OneOffInvoker;
      }(LifeCycleInvoker);
      var ReusableInvoker = function (_LifeCycleInvoker2) {
        _inheritsLoose(ReusableInvoker, _LifeCycleInvoker2);
        function ReusableInvoker() {
          return _LifeCycleInvoker2.apply(this, arguments) || this;
        }
        var _proto2 = ReusableInvoker.prototype;
        _proto2.add = function add(comp) {
          var order = comp.constructor._executionOrder;
          if (order === 0) {
            this._zero.array.push(comp);
          } else {
            var _array = order < 0 ? this._neg.array : this._pos.array;
            var i = sortedIndex(_array, comp);
            if (i < 0) {
              _array.splice(~i, 0, comp);
            }
          }
        };
        _proto2.remove = function remove(comp) {
          var order = comp.constructor._executionOrder;
          if (order === 0) {
            this._zero.fastRemove(comp);
          } else {
            var _iterator = order < 0 ? this._neg : this._pos;
            var i = sortedIndex(_iterator.array, comp);
            if (i >= 0) {
              _iterator.removeAt(i);
            }
          }
        };
        _proto2.invoke = function invoke(dt) {
          if (this._neg.array.length > 0) {
            this._invoke(this._neg, dt);
          }
          this._invoke(this._zero, dt);
          if (this._pos.array.length > 0) {
            this._invoke(this._pos, dt);
          }
        };
        return ReusableInvoker;
      }(LifeCycleInvoker);
      function createInvokeImplJit(code, useDt, ensureFlag) {
        var body = "" + ('var a=it.array;' + 'for(it.i=0;it.i<a.length;++it.i){' + 'var c=a[it.i];') + code + "}";
        var fastPath = useDt ? Function('it', 'dt', body) : Function('it', body);
        var singleInvoke = Function('c', 'dt', code);
        return createInvokeImpl(singleInvoke, fastPath, ensureFlag);
      }
      function createInvokeImpl(singleInvoke, fastPath, ensureFlag) {
        return function (iterator, dt) {
          try {
            fastPath(iterator, dt);
          } catch (e) {
            legacyCC._throw(e);
            var _array2 = iterator.array;
            if (ensureFlag) {
              _array2[iterator.i]._objFlags |= ensureFlag;
            }
            ++iterator.i;
            for (; iterator.i < _array2.length; ++iterator.i) {
              try {
                singleInvoke(_array2[iterator.i], dt);
              } catch (e) {
                legacyCC._throw(e);
                if (ensureFlag) {
                  _array2[iterator.i]._objFlags |= ensureFlag;
                }
              }
            }
          }
        };
      }
      var invokeStart = createInvokeImplJit("c.start();c._objFlags|=" + IsStartCalled, false, IsStartCalled) ;
      var invokeUpdate = createInvokeImplJit('c.update(dt)', true) ;
      var invokeLateUpdate = createInvokeImplJit('c.lateUpdate(dt)', true) ;
      var invokeOnEnable = function (iterator) {
        var compScheduler = legacyCC.director._compScheduler;
        var array = iterator.array;
        for (iterator.i = 0; iterator.i < array.length; ++iterator.i) {
          var comp = array[iterator.i];
          if (comp._enabled) {
            comp.onEnable();
            var deactivatedDuringOnEnable = !comp.node._activeInHierarchy;
            if (!deactivatedDuringOnEnable) {
              compScheduler._onEnabled(comp);
            }
          }
        }
      };
      var ComponentScheduler = function () {
        function ComponentScheduler() {
          this.startInvoker = void 0;
          this.updateInvoker = void 0;
          this.lateUpdateInvoker = void 0;
          this._deferredComps = [];
          this._updating = void 0;
          this.unscheduleAll();
        }
        var _proto3 = ComponentScheduler.prototype;
        _proto3.unscheduleAll = function unscheduleAll() {
          this.startInvoker = new OneOffInvoker(invokeStart);
          this.updateInvoker = new ReusableInvoker(invokeUpdate);
          this.lateUpdateInvoker = new ReusableInvoker(invokeLateUpdate);
          this._updating = false;
        };
        _proto3._onEnabled = function _onEnabled(comp) {
          legacyCC.director.getScheduler().resumeTarget(comp);
          comp._objFlags |= IsOnEnableCalled$1;
          if (this._updating) {
            this._deferredComps.push(comp);
          } else {
            this._scheduleImmediate(comp);
          }
        };
        _proto3._onDisabled = function _onDisabled(comp) {
          legacyCC.director.getScheduler().pauseTarget(comp);
          comp._objFlags &= ~IsOnEnableCalled$1;
          var index = this._deferredComps.indexOf(comp);
          if (index >= 0) {
            fastRemoveAt(this._deferredComps, index);
            return;
          }
          if (comp.internalStart && !(comp._objFlags & IsStartCalled)) {
            this.startInvoker.remove(comp);
          }
          if (comp.internalUpdate) {
            this.updateInvoker.remove(comp);
          }
          if (comp.internalLateUpdate) {
            this.lateUpdateInvoker.remove(comp);
          }
        };
        _proto3.enableComp = function enableComp(comp, invoker) {
          if (!(comp._objFlags & IsOnEnableCalled$1)) {
            if (comp.internalOnEnable) {
              if (invoker) {
                invoker.add(comp);
                return;
              } else {
                comp.internalOnEnable();
                var deactivatedDuringOnEnable = !comp.node.activeInHierarchy;
                if (deactivatedDuringOnEnable) {
                  return;
                }
              }
            }
            this._onEnabled(comp);
          }
        };
        _proto3.disableComp = function disableComp(comp) {
          if (comp._objFlags & IsOnEnableCalled$1) {
            if (comp.internalOnDisable) {
              comp.internalOnDisable();
            }
            this._onDisabled(comp);
          }
        };
        _proto3.startPhase = function startPhase() {
          this._updating = true;
          this.startInvoker.invoke();
          this._startForNewComps();
        };
        _proto3.updatePhase = function updatePhase(dt) {
          this.updateInvoker.invoke(dt);
        };
        _proto3.lateUpdatePhase = function lateUpdatePhase(dt) {
          this.lateUpdateInvoker.invoke(dt);
          this._updating = false;
          this._startForNewComps();
        };
        _proto3._startForNewComps = function _startForNewComps() {
          if (this._deferredComps.length > 0) {
            this._deferredSchedule();
            this.startInvoker.invoke();
          }
        };
        _proto3._scheduleImmediate = function _scheduleImmediate(comp) {
          if (typeof comp.internalStart === 'function' && !(comp._objFlags & IsStartCalled)) {
            this.startInvoker.add(comp);
          }
          if (typeof comp.internalUpdate === 'function') {
            this.updateInvoker.add(comp);
          }
          if (typeof comp.internalLateUpdate === 'function') {
            this.lateUpdateInvoker.add(comp);
          }
        };
        _proto3._deferredSchedule = function _deferredSchedule() {
          var comps = this._deferredComps;
          for (var i = 0, len = comps.length; i < len; i++) {
            this._scheduleImmediate(comps[i]);
          }
          comps.length = 0;
        };
        return ComponentScheduler;
      }();

      var MAX_POOL_SIZE = 4;
      var IsPreloadStarted = CCObject.Flags.IsPreloadStarted;
      var IsOnLoadStarted = CCObject.Flags.IsOnLoadStarted;
      var IsOnLoadCalled = CCObject.Flags.IsOnLoadCalled;
      var IsOnEnableCalled = CCObject.Flags.IsOnEnableCalled;
      var Deactivating = CCObject.Flags.Deactivating;
      var UnsortedInvoker = function (_LifeCycleInvoker) {
        _inheritsLoose(UnsortedInvoker, _LifeCycleInvoker);
        function UnsortedInvoker() {
          return _LifeCycleInvoker.apply(this, arguments) || this;
        }
        var _proto = UnsortedInvoker.prototype;
        _proto.add = function add(comp) {
          this._zero.array.push(comp);
        };
        _proto.remove = function remove(comp) {
          this._zero.fastRemove(comp);
        };
        _proto.cancelInactive = function cancelInactive(flagToClear) {
          LifeCycleInvoker.stableRemoveInactive(this._zero, flagToClear);
        };
        _proto.invoke = function invoke() {
          this._invoke(this._zero);
          this._zero.array.length = 0;
        };
        return UnsortedInvoker;
      }(LifeCycleInvoker);
      var invokePreload = createInvokeImplJit('c.__preload();') ;
      var invokeOnLoad = createInvokeImplJit("c.onLoad();c._objFlags|=" + IsOnLoadCalled, false, IsOnLoadCalled) ;
      var activateTasksPool = new Pool$1(MAX_POOL_SIZE);
      activateTasksPool.get = function getActivateTask() {
        var task = this._get() || {
          preload: new UnsortedInvoker(invokePreload),
          onLoad: new OneOffInvoker(invokeOnLoad),
          onEnable: new OneOffInvoker(invokeOnEnable)
        };
        task.preload.zero.i = -1;
        var invoker = task.onLoad;
        invoker.zero.i = -1;
        invoker.neg.i = -1;
        invoker.pos.i = -1;
        invoker = task.onEnable;
        invoker.zero.i = -1;
        invoker.neg.i = -1;
        invoker.pos.i = -1;
        return task;
      };
      function _componentCorrupted(node, comp, index) {
        errorID(3817, node.name, index);
        console.log('Corrupted component value:', comp);
        if (comp) {
          node._removeComponent(comp);
        } else {
          removeAt(node.getWritableComponents(), index);
        }
      }
      var NodeActivator = exports('dA', function () {
        function NodeActivator() {
          this._activatingStack = void 0;
          this.reset();
        }
        var _proto2 = NodeActivator.prototype;
        _proto2.reset = function reset() {
          this._activatingStack = [];
        };
        _proto2.activateNode = function activateNode(node, active) {
          if (active) {
            var task = activateTasksPool.get();
            if (task) {
              this._activatingStack.push(task);
              this._activateNodeRecursively(node, task.preload, task.onLoad, task.onEnable);
              task.preload.invoke();
              task.onLoad.invoke();
              task.onEnable.invoke();
              this._activatingStack.pop();
              activateTasksPool.put(task);
            }
          } else {
            this._deactivateNodeRecursively(node);
            var stack = this._activatingStack;
            for (var _iterator = _createForOfIteratorHelperLoose(stack), _step; !(_step = _iterator()).done;) {
              var lastTask = _step.value;
              lastTask.preload.cancelInactive(IsPreloadStarted);
              lastTask.onLoad.cancelInactive(IsOnLoadStarted);
              lastTask.onEnable.cancelInactive(IsOnEnableCalled);
            }
          }
          node.emit(NodeEventType.ACTIVE_IN_HIERARCHY_CHANGED, node);
        };
        _proto2.activateComp = function activateComp(comp, preloadInvoker, onLoadInvoker, onEnableInvoker) {
          if (!isValid(comp, true)) {
            return;
          }
          if (!(comp._objFlags & IsPreloadStarted)) {
            comp._objFlags |= IsPreloadStarted;
            if (comp.internalPreload) {
              if (preloadInvoker) {
                preloadInvoker.add(comp);
              } else {
                comp.internalPreload();
              }
            }
          }
          if (!(comp._objFlags & IsOnLoadStarted)) {
            comp._objFlags |= IsOnLoadStarted;
            if (comp.internalOnLoad) {
              if (onLoadInvoker) {
                onLoadInvoker.add(comp);
              } else {
                comp.internalOnLoad();
                comp._objFlags |= IsOnLoadCalled;
              }
            } else {
              comp._objFlags |= IsOnLoadCalled;
            }
          }
          if (comp._enabled) {
            {
              assertIsTrue(comp.node, getError(3823, comp.uuid, comp.name));
            }
            var deactivatedOnLoading = !comp.node.activeInHierarchy;
            if (deactivatedOnLoading) {
              return;
            }
            legacyCC.director._compScheduler.enableComp(comp, onEnableInvoker);
          }
        };
        _proto2.destroyComp = function destroyComp(comp) {
          legacyCC.director._compScheduler.disableComp(comp);
          if (comp.internalOnDestroy && comp._objFlags & IsOnLoadCalled) {
            comp.internalOnDestroy();
          }
        };
        _proto2._activateNodeRecursively = function _activateNodeRecursively(node, preloadInvoker, onLoadInvoker, onEnableInvoker) {
          if (node._objFlags & Deactivating) {
            errorID(3816, node.name);
            return;
          }
          node._setActiveInHierarchy(true);
          var originCount = node.components.length;
          for (var i = 0; i < originCount; ++i) {
            var component = node.components[i];
            if (component instanceof legacyCC.Component) {
              this.activateComp(component, preloadInvoker, onLoadInvoker, onEnableInvoker);
            } else {
              _componentCorrupted(node, component, i);
              --i;
              --originCount;
            }
          }
          for (var _i = 0, len = node.children.length; _i < len; ++_i) {
            var child = node.children[_i];
            if (child.active) {
              this._activateNodeRecursively(child, preloadInvoker, onLoadInvoker, onEnableInvoker);
            }
          }
          node._onPostActivated(true);
        };
        _proto2._deactivateNodeRecursively = function _deactivateNodeRecursively(node) {
          node._objFlags |= Deactivating;
          node._setActiveInHierarchy(false);
          var originCount = node.components.length;
          for (var c = 0; c < originCount; ++c) {
            var component = node.components[c];
            if (component._enabled) {
              legacyCC.director._compScheduler.disableComp(component);
              if (node.activeInHierarchy) {
                node._objFlags &= ~Deactivating;
                return;
              }
            }
          }
          for (var i = 0, len = node.children.length; i < len; ++i) {
            var child = node.children[i];
            if (child.activeInHierarchy) {
              this._deactivateNodeRecursively(child);
              if (node.activeInHierarchy) {
                node._objFlags &= ~Deactivating;
                return;
              }
            }
          }
          node._onPostActivated(false);
          node._objFlags &= ~Deactivating;
        };
        return NodeActivator;
      }());

      var Destroyed$1 = CCObject.Flags.Destroyed;
      var PersistentMask$1 = CCObject.Flags.PersistentMask;
      var DEFAULT = CCClass.Attr.DELIMETER + "default";
      var IDENTIFIER_RE = CCClass.IDENTIFIER_RE;
      var VAR = 'var ';
      var LOCAL_OBJ = 'o';
      var LOCAL_TEMP_OBJ = 't';
      var LOCAL_ARRAY = 'a';
      var LINE_INDEX_OF_NEW_OBJ = 0;
      var DEFAULT_MODULE_CACHE = {
        'cc.ClickEvent': false,
        'cc.PrefabInfo': false
      };
      var escapeForJS = CCClass.escapeForJS;
      var Declaration = function () {
        function Declaration(varName, expression) {
          this.varName = void 0;
          this.expression = void 0;
          this.varName = varName;
          this.expression = expression;
        }
        var _proto = Declaration.prototype;
        _proto.toString = function toString() {
          return VAR + this.varName + "=" + this.expression + ";";
        };
        return Declaration;
      }();
      function mergeDeclaration(statement, expression) {
        if (expression instanceof Declaration) {
          return new Declaration(expression.varName, statement + expression.expression);
        } else {
          return statement + expression;
        }
      }
      function writeAssignment(codeArray, statement, expression) {
        if (Array.isArray(expression)) {
          expression[0] = mergeDeclaration(statement, expression[0]);
          codeArray.push(expression);
        } else {
          codeArray.push(mergeDeclaration(statement, expression) + ";");
        }
      }
      var Assignments = function () {
        function Assignments(targetExpression) {
          this._exps = void 0;
          this._targetExp = void 0;
          this._exps = [];
          this._targetExp = targetExpression;
        }
        var _proto2 = Assignments.prototype;
        _proto2.append = function append(key, expression) {
          this._exps.push([key, expression]);
        };
        _proto2.writeCode = function writeCode(codeArray) {
          var targetVar;
          if (this._exps.length > 1) {
            codeArray.push(LOCAL_TEMP_OBJ + "=" + this._targetExp + ";");
            targetVar = LOCAL_TEMP_OBJ;
          } else if (this._exps.length === 1) {
            targetVar = this._targetExp;
          } else {
            return;
          }
          for (var i = 0; i < this._exps.length; i++) {
            var pair = this._exps[i];
            writeAssignment(codeArray, targetVar + getPropAccessor(pair[0]) + "=", pair[1]);
          }
        };
        return Assignments;
      }();
      Assignments.pool = void 0;
      Assignments.pool = new Pool$1(function (obj) {
        obj._exps.length = 0;
        obj._targetExp = null;
      }, 1);
      Assignments.pool.get = function (targetExpression) {
        var cache = this._get() || new Assignments();
        cache._targetExp = targetExpression;
        return cache;
      };
      function getPropAccessor(key) {
        return IDENTIFIER_RE.test(key) ? "." + key : "[" + escapeForJS(key) + "]";
      }
      var Parser = function () {
        function Parser(obj, parent) {
          this.parent = void 0;
          this.objsToClear_iN$t = void 0;
          this.codeArray = void 0;
          this.objs = void 0;
          this.funcs = void 0;
          this.funcModuleCache = void 0;
          this.globalVariables = void 0;
          this.globalVariableId = void 0;
          this.localVariableId = void 0;
          this.result = void 0;
          this.parent = parent;
          this.objsToClear_iN$t = [];
          this.codeArray = [];
          this.objs = [];
          this.funcs = [];
          this.funcModuleCache = createMap();
          mixin(this.funcModuleCache, DEFAULT_MODULE_CACHE);
          this.globalVariables = [];
          this.globalVariableId = 0;
          this.localVariableId = 0;
          this.codeArray.push(VAR + LOCAL_OBJ + "," + LOCAL_TEMP_OBJ + ";", 'if(R){', LOCAL_OBJ + "=R;", '}else{', LOCAL_OBJ + "=R=new " + this.getFuncModule(obj.constructor, true) + "();", '}');
          obj._iN$t = {
            globalVar: 'R'
          };
          this.objsToClear_iN$t.push(obj);
          this.enumerateObject(this.codeArray, obj);
          var globalVariablesDeclaration;
          if (this.globalVariables.length > 0) {
            globalVariablesDeclaration = VAR + this.globalVariables.join(',') + ";";
          }
          var code = flattenCodeArray(['return (function(R){', globalVariablesDeclaration || [], this.codeArray, 'return o;', '})']);
          this.result = Function('O', 'F', code)(this.objs, this.funcs);
          for (var i = 0, len = this.objsToClear_iN$t.length; i < len; ++i) {
            this.objsToClear_iN$t[i]._iN$t = null;
          }
          this.objsToClear_iN$t.length = 0;
        }
        var _proto3 = Parser.prototype;
        _proto3.getFuncModule = function getFuncModule(func, usedInNew) {
          var clsName = getClassName(func);
          if (clsName) {
            var cache = this.funcModuleCache[clsName];
            if (cache) {
              return cache;
            } else if (cache === undefined) {
              var clsNameIsModule = clsName.indexOf('.') !== -1;
              if (clsNameIsModule) {
                try {
                  clsNameIsModule = func === Function("return " + clsName)();
                  if (clsNameIsModule) {
                    this.funcModuleCache[clsName] = clsName;
                    return clsName;
                  }
                } catch (e) {}
              }
            }
          }
          var index = this.funcs.indexOf(func);
          if (index < 0) {
            index = this.funcs.length;
            this.funcs.push(func);
          }
          var res = "F[" + index + "]";
          if (usedInNew) {
            res = "(" + res + ")";
          }
          this.funcModuleCache[clsName] = res;
          return res;
        };
        _proto3.getObjRef = function getObjRef(obj) {
          var index = this.objs.indexOf(obj);
          if (index < 0) {
            index = this.objs.length;
            this.objs.push(obj);
          }
          return "O[" + index + "]";
        };
        _proto3.setValueType = function setValueType(codeArray, defaultValue, srcValue, targetExpression) {
          var assignments = Assignments.pool.get(targetExpression);
          var fastDefinedProps = defaultValue.constructor.__props__;
          if (!fastDefinedProps) {
            fastDefinedProps = Object.keys(defaultValue);
          }
          for (var i = 0; i < fastDefinedProps.length; i++) {
            var propName = fastDefinedProps[i];
            var prop = srcValue[propName];
            if (defaultValue[propName] === prop) {
              continue;
            }
            var expression = this.enumerateField(srcValue, propName, prop);
            assignments.append(propName, expression);
          }
          assignments.writeCode(codeArray);
          Assignments.pool.put(assignments);
        };
        _proto3.enumerateCCClass = function enumerateCCClass(codeArray, obj, klass) {
          var props = klass.__values__;
          var attrs = CCClass.Attr.getClassAttrs(klass);
          for (var p = 0; p < props.length; p++) {
            var key = props[p];
            var val = obj[key];
            var defaultValue = attrs[key + DEFAULT];
            if (equalsToDefault(defaultValue, val)) {
              continue;
            }
            if (typeof val === 'object' && val instanceof legacyCC.ValueType) {
              defaultValue = CCClass.getDefault(defaultValue);
              if (defaultValue && defaultValue.constructor === val.constructor) {
                var targetExpression = LOCAL_OBJ + getPropAccessor(key);
                this.setValueType(codeArray, defaultValue, val, targetExpression);
                continue;
              }
            }
            this.setObjProp(codeArray, obj, key, val);
          }
        };
        _proto3.instantiateArray = function instantiateArray(value) {
          if (value.length === 0) {
            return '[]';
          }
          var arrayVar = LOCAL_ARRAY + ++this.localVariableId;
          var declaration = new Declaration(arrayVar, "new Array(" + value.length + ")");
          var codeArray = [declaration];
          value._iN$t = {
            globalVar: '',
            source: codeArray
          };
          this.objsToClear_iN$t.push(value);
          for (var i = 0; i < value.length; ++i) {
            var statement = arrayVar + "[" + i + "]=";
            var expression = this.enumerateField(value, i, value[i]);
            writeAssignment(codeArray, statement, expression);
          }
          return codeArray;
        };
        _proto3.instantiateTypedArray = function instantiateTypedArray(value) {
          var type = value.constructor.name;
          if (value.length === 0) {
            return "new " + type;
          }
          var arrayVar = LOCAL_ARRAY + ++this.localVariableId;
          var declaration = new Declaration(arrayVar, "new " + type + "(" + value.length + ")");
          var codeArray = [declaration];
          value._iN$t = {
            globalVar: '',
            source: codeArray
          };
          this.objsToClear_iN$t.push(value);
          for (var i = 0; i < value.length; ++i) {
            if (value[i] !== 0) {
              var statement = arrayVar + "[" + i + "]=";
              writeAssignment(codeArray, statement, value[i]);
            }
          }
          return codeArray;
        };
        _proto3.enumerateField = function enumerateField(obj, key, value) {
          if (typeof value === 'object' && value) {
            var _iN$t = value._iN$t;
            if (_iN$t) {
              var globalVar = _iN$t.globalVar;
              if (!globalVar) {
                globalVar = _iN$t.globalVar = "v" + ++this.globalVariableId;
                this.globalVariables.push(globalVar);
                var line = _iN$t.source[LINE_INDEX_OF_NEW_OBJ];
                _iN$t.source[LINE_INDEX_OF_NEW_OBJ] = mergeDeclaration(globalVar + "=", line);
              }
              return globalVar;
            } else if (ArrayBuffer.isView(value)) {
              return this.instantiateTypedArray(value);
            } else if (Array.isArray(value)) {
              return this.instantiateArray(value);
            } else {
              return this.instantiateObj(value);
            }
          } else if (typeof value === 'function') {
            return this.getFuncModule(value);
          } else if (typeof value === 'string') {
            return escapeForJS(value);
          } else {
            if (key === '_objFlags' && isCCObject(obj)) {
              value &= PersistentMask$1;
            }
            return value;
          }
        };
        _proto3.setObjProp = function setObjProp(codeArray, obj, key, value) {
          var statement = LOCAL_OBJ + getPropAccessor(key) + "=";
          var expression = this.enumerateField(obj, key, value);
          writeAssignment(codeArray, statement, expression);
        };
        _proto3.enumerateObject = function enumerateObject(codeArray, obj) {
          var klass = obj.constructor;
          if (isCCClassOrFastDefined(klass)) {
            this.enumerateCCClass(codeArray, obj, klass);
          } else {
            for (var key in obj) {
              if (!obj.hasOwnProperty(key) || key.charCodeAt(0) === 95 && key.charCodeAt(1) === 95 && key !== '__type__') {
                continue;
              }
              var value = obj[key];
              if (typeof value === 'object' && value && value === obj._iN$t) {
                continue;
              }
              this.setObjProp(codeArray, obj, key, value);
            }
          }
        };
        _proto3.instantiateObj = function instantiateObj(obj) {
          if (obj instanceof legacyCC.ValueType) {
            return CCClass.getNewValueTypeCode(obj);
          }
          if (obj instanceof legacyCC.Asset) {
            return this.getObjRef(obj);
          }
          if (obj._objFlags & Destroyed$1) {
            return null;
          }
          var createCode;
          var ctor = obj.constructor;
          if (isCCClassOrFastDefined(ctor)) {
            if (this.parent) {
              if (this.parent instanceof legacyCC.Component) {
                if (obj instanceof legacyCC.Node || obj instanceof legacyCC.Component) {
                  return this.getObjRef(obj);
                }
              } else if (this.parent instanceof legacyCC.Node) {
                if (obj instanceof legacyCC.Node) {
                  if (!obj.isChildOf(this.parent)) {
                    return this.getObjRef(obj);
                  }
                } else if (obj instanceof legacyCC.Component) {
                  var _obj$node;
                  if (!((_obj$node = obj.node) !== null && _obj$node !== void 0 && _obj$node.isChildOf(this.parent))) {
                    return this.getObjRef(obj);
                  }
                }
              }
            }
            createCode = new Declaration(LOCAL_OBJ, "new " + this.getFuncModule(ctor, true) + "()");
          } else if (ctor === Object) {
            createCode = new Declaration(LOCAL_OBJ, '{}');
          } else if (!ctor) {
            createCode = new Declaration(LOCAL_OBJ, 'Object.create(null)');
          } else {
            return this.getObjRef(obj);
          }
          var codeArray = [createCode];
          obj._iN$t = {
            globalVar: '',
            source: codeArray
          };
          this.objsToClear_iN$t.push(obj);
          this.enumerateObject(codeArray, obj);
          return ['(function(){', codeArray, 'return o;})();'];
        };
        return Parser;
      }();
      function equalsToDefault(def, value) {
        if (typeof def === 'function') {
          try {
            def = def();
          } catch (e) {
            return false;
          }
        }
        if (def === value) {
          return true;
        }
        if (def && value && typeof def === 'object' && typeof value === 'object' && def.constructor === value.constructor) {
          if (def instanceof legacyCC.ValueType) {
            if (def.equals(value)) {
              return true;
            }
          } else if (Array.isArray(def)) {
            return def.length === 0 && value.length === 0;
          } else if (def.constructor === Object) {
            return isEmptyObject(def) && isEmptyObject(value);
          }
        }
        return false;
      }
      function compile(node) {
        var root = node instanceof legacyCC.Node && node;
        var parser = new Parser(node, root);
        return parser.result;
      }

      var _dec$2s, _class$2q, _class2$2a, _initializer$1$, _initializer2$1B, _initializer3$14, _class3$C;
      var OptimizationPolicy = Enum({
        AUTO: 0,
        SINGLE_INSTANCE: 1,
        MULTI_INSTANCE: 2
      });
      var Prefab = exports('dB', (_dec$2s = ccclass$n('cc.Prefab'), _dec$2s(_class$2q = (_class2$2a = (_class3$C = function (_Asset) {
        _inheritsLoose(Prefab, _Asset);
        function Prefab() {
          var _this;
          _this = _Asset.call(this) || this;
          _this.data = _initializer$1$ && _initializer$1$();
          _this.optimizationPolicy = _initializer2$1B && _initializer2$1B();
          _this.persistent = _initializer3$14 && _initializer3$14();
          _this._createFunction = void 0;
          _this._instantiatedTimes = void 0;
          _this._createFunction = null;
          _this._instantiatedTimes = 0;
          return _this;
        }
        var _proto = Prefab.prototype;
        _proto.createNode = function createNode(cb) {
          var node = legacyCC.instantiate(this);
          node.name = this.name;
          cb(null, node);
        };
        _proto.compileCreateFunction = function compileCreateFunction() {
          this._createFunction = compile(this.data);
        };
        _proto._doInstantiate = function _doInstantiate(rootToRedirect) {
          if (!this.data._prefab) {
            warnID(3700);
          }
          if (!this._createFunction) {
            this.compileCreateFunction();
          }
          return this._createFunction(rootToRedirect);
        };
        _proto._instantiate = function _instantiate() {
          var node;
          var useJit = false;
          {
            if (this.optimizationPolicy === OptimizationPolicy.SINGLE_INSTANCE) {
              useJit = false;
            } else if (this.optimizationPolicy === OptimizationPolicy.MULTI_INSTANCE) {
              useJit = true;
            } else {
              useJit = this._instantiatedTimes + 1 >= Prefab.OptimizationPolicyThreshold;
            }
          }
          if (useJit) {
            node = this._doInstantiate();
            this.data._instantiate(node);
          } else {
            node = this.data._instantiate();
          }
          ++this._instantiatedTimes;
          return node;
        };
        _proto.initDefault = function initDefault(uuid) {
          _Asset.prototype.initDefault.call(this, uuid);
          this.data = new Node$1();
          this.data.name = '(Missing Node)';
          var prefabInfo = new legacyCC._PrefabInfo();
          prefabInfo.asset = this;
          prefabInfo.root = this.data;
          this.data._prefab = prefabInfo;
        };
        _proto.validate = function validate() {
          return !!this.data;
        };
        _proto.onLoaded = function onLoaded() {
          var rootNode = this.data;
          expandNestedPrefabInstanceNode(rootNode);
          applyTargetOverrides(rootNode);
        };
        return Prefab;
      }(Asset), _class3$C.OptimizationPolicy = OptimizationPolicy, _class3$C.OptimizationPolicyThreshold = 3, _class3$C), (_initializer$1$ = applyDecoratedInitializer(_class2$2a.prototype, "data", [serializable$j], function () {
        return null;
      }), _initializer2$1B = applyDecoratedInitializer(_class2$2a.prototype, "optimizationPolicy", [serializable$j], function () {
        return OptimizationPolicy.AUTO;
      }), _initializer3$14 = applyDecoratedInitializer(_class2$2a.prototype, "persistent", [serializable$j], function () {
        return false;
      })), _class2$2a)) || _class$2q));
      value(Prefab, '_utils', utils$1);
      legacyCC.Prefab = Prefab;
      {
        obsolete(legacyCC, 'cc._Prefab', 'Prefab');
      }

      var UIRendererManager = function () {
        function UIRendererManager() {
          this._allRenderers = [];
          this._dirtyRenderers = [];
          this._dirtyVersion = 0;
        }
        var _proto = UIRendererManager.prototype;
        _proto.addRenderer = function addRenderer(uiRenderer) {
          if (uiRenderer._internalId === -1) {
            uiRenderer._internalId = this._allRenderers.length;
            this._allRenderers.push(uiRenderer);
          }
        };
        _proto.removeRenderer = function removeRenderer(uiRenderer) {
          if (uiRenderer._internalId !== -1) {
            {
              assert(this._allRenderers[uiRenderer._internalId] === uiRenderer);
            }
            var id = uiRenderer._internalId;
            this._allRenderers[this._allRenderers.length - 1]._internalId = id;
            fastRemoveAt$2(this._allRenderers, id);
            uiRenderer._internalId = -1;
            if (uiRenderer._dirtyVersion === this._dirtyVersion) {
              fastRemove(this._dirtyRenderers, uiRenderer);
              uiRenderer._dirtyVersion = -1;
            }
          }
        };
        _proto.markDirtyRenderer = function markDirtyRenderer(uiRenderer) {
          if (uiRenderer._dirtyVersion !== this._dirtyVersion && uiRenderer._internalId !== -1) {
            this._dirtyRenderers.push(uiRenderer);
            uiRenderer._dirtyVersion = this._dirtyVersion;
          }
        };
        _proto.updateAllDirtyRenderers = function updateAllDirtyRenderers() {
          var length = this._dirtyRenderers.length;
          var dirtyRenderers = this._dirtyRenderers;
          for (var i = 0; i < length; i++) {
            {
              assert(dirtyRenderers[i]._internalId !== -1);
            }
            dirtyRenderers[i].updateRenderer();
          }
          this._dirtyRenderers.length = 0;
          this._dirtyVersion++;
        };
        return UIRendererManager;
      }();
      var uiRendererManager = new UIRendererManager();

      var Director = exports('dX', function (_EventTarget) {
        _inheritsLoose(Director, _EventTarget);
        function Director() {
          var _this;
          _this = _EventTarget.call(this) || this;
          _this._compScheduler = void 0;
          _this._nodeActivator = void 0;
          _this._invalid = void 0;
          _this._paused = void 0;
          _this._root = void 0;
          _this._loadingScene = void 0;
          _this._scene = void 0;
          _this._totalFrames = void 0;
          _this._scheduler = void 0;
          _this._systems = void 0;
          _this._persistRootNodes = {};
          _this._invalid = false;
          _this._paused = false;
          _this._root = null;
          _this._loadingScene = '';
          _this._scene = null;
          _this._totalFrames = 0;
          _this._scheduler = new Scheduler();
          _this._compScheduler = new ComponentScheduler();
          _this._nodeActivator = new NodeActivator();
          _this._systems = [];
          return _this;
        }
        var _proto = Director.prototype;
        _proto.calculateDeltaTime = function calculateDeltaTime(now) {};
        _proto.end = function end() {
          var _this2 = this;
          this.once(Director.EVENT_END_FRAME, function () {
            _this2.purgeDirector();
          });
        };
        _proto.pause = function pause() {
          if (this._paused) {
            return;
          }
          this._paused = true;
        };
        _proto.purgeDirector = function purgeDirector() {
          this._scheduler.unscheduleAll();
          this._compScheduler.unscheduleAll();
          this._nodeActivator.reset();
          {
            if (isValid(this._scene)) {
              this._scene.destroy();
            }
            this._scene = null;
          }
          this.stopAnimation();
          assetManager.releaseAll();
        };
        _proto.reset = function reset() {
          var _this$getScene;
          this.purgeDirector();
          for (var id in this._persistRootNodes) {
            this.removePersistRootNode(this._persistRootNodes[id]);
          }
          (_this$getScene = this.getScene()) === null || _this$getScene === void 0 ? void 0 : _this$getScene.destroy();
          this.emit(Director.EVENT_RESET);
          this.startAnimation();
        };
        _proto.runSceneImmediate = function runSceneImmediate(scene, onBeforeLoadScene, onLaunched) {
          var _this3 = this;
          if (scene instanceof SceneAsset) scene = scene.scene;
          assertID(scene instanceof Scene, 1216);
          {
            console.time('InitScene');
          }
          scene._load();
          {
            console.timeEnd('InitScene');
          }
          {
            console.time('AttachPersist');
          }
          var persistNodeList = Object.keys(this._persistRootNodes).map(function (x) {
            return _this3._persistRootNodes[x];
          });
          for (var i = 0; i < persistNodeList.length; i++) {
            var node = persistNodeList[i];
            node.emit(Node$1.EventType.SCENE_CHANGED_FOR_PERSISTS, scene.renderScene);
            var existNode = scene.uuid === node._originalSceneId && scene.getChildByUuid(node.uuid);
            if (existNode) {
              var index = existNode.getSiblingIndex();
              node.hideFlags &= ~CCObject.Flags.DontSave;
              node.hideFlags |= CCObject.Flags.DontSave & existNode.hideFlags;
              existNode._destroyImmediate();
              scene.insertChild(node, index);
            } else {
              node.hideFlags |= CCObject.Flags.DontSave;
              node.parent = scene;
            }
          }
          {
            console.timeEnd('AttachPersist');
          }
          var oldScene = this._scene;
          {
            console.time('Destroy');
          }
          if (isValid(oldScene)) {
            oldScene.destroy();
          }
          {
            {
              console.time('AutoRelease');
            }
            releaseManager._autoRelease(oldScene, scene, this._persistRootNodes);
            {
              console.timeEnd('AutoRelease');
            }
          }
          this._scene = null;
          CCObject._deferredDestroy();
          {
            console.timeEnd('Destroy');
          }
          if (onBeforeLoadScene) {
            onBeforeLoadScene();
          }
          this.emit(Director.EVENT_BEFORE_SCENE_LAUNCH, scene);
          this._scene = scene;
          {
            console.time('Activate');
          }
          scene._activate();
          {
            console.timeEnd('Activate');
          }
          if (this._root) {
            this._root.resetCumulativeTime();
          }
          this.startAnimation();
          if (onLaunched) {
            onLaunched(null, scene);
          }
          this.emit(Director.EVENT_AFTER_SCENE_LAUNCH, scene);
        };
        _proto.runScene = function runScene(scene, onBeforeLoadScene, onLaunched) {
          var _this4 = this;
          if (scene instanceof SceneAsset) scene = scene.scene;
          assertID(Boolean(scene), 1205);
          assertID(scene instanceof Scene, 1216);
          this.once(Director.EVENT_END_FRAME, function () {
            _this4.runSceneImmediate(scene, onBeforeLoadScene, onLaunched);
          });
        };
        _proto.loadScene = function loadScene(sceneName, onLaunched, onUnloaded) {
          var _this5 = this;
          if (this._loadingScene) {
            warnID(1208, sceneName, this._loadingScene);
            return false;
          }
          var bundle = assetManager.bundles.find(function (bundle) {
            return !!bundle.getSceneInfo(sceneName);
          });
          if (bundle) {
            this.emit(Director.EVENT_BEFORE_SCENE_LOADING, sceneName);
            this._loadingScene = sceneName;
            console.time("LoadScene " + sceneName);
            bundle.loadScene(sceneName, function (err, scene) {
              console.timeEnd("LoadScene " + sceneName);
              _this5._loadingScene = '';
              if (err) {
                error(err);
                if (onLaunched) {
                  onLaunched(err);
                }
              } else {
                _this5.runSceneImmediate(scene, onUnloaded, onLaunched);
              }
            });
            return true;
          } else {
            errorID(1209, sceneName);
            return false;
          }
        };
        _proto.preloadScene = function preloadScene(sceneName, onProgress, onLoaded) {
          var bundle = assetManager.bundles.find(function (bundle) {
            return !!bundle.getSceneInfo(sceneName);
          });
          if (bundle) {
            bundle.preloadScene(sceneName, null, onProgress, onLoaded);
          } else {
            var _err = "Can not preload the scene \"" + sceneName + "\" because it is not in the build settings.";
            if (onLoaded) {
              onLoaded(new Error(_err));
            }
            error("preloadScene: " + _err);
          }
        };
        _proto.resume = function resume() {
          if (!this._paused) {
            return;
          }
          this._paused = false;
        };
        _proto.getScene = function getScene() {
          return this._scene;
        };
        _proto.getDeltaTime = function getDeltaTime() {
          return legacyCC.game.deltaTime;
        };
        _proto.getTotalTime = function getTotalTime() {
          return legacyCC.game.totalTime;
        };
        _proto.getCurrentTime = function getCurrentTime() {
          return legacyCC.game.frameStartTime;
        };
        _proto.getTotalFrames = function getTotalFrames() {
          return this._totalFrames;
        };
        _proto.isPaused = function isPaused() {
          return this._paused;
        };
        _proto.getScheduler = function getScheduler() {
          return this._scheduler;
        };
        _proto.setScheduler = function setScheduler(scheduler) {
          if (this._scheduler !== scheduler) {
            this.unregisterSystem(this._scheduler);
            this._scheduler = scheduler;
            this.registerSystem(Scheduler.ID, scheduler, 200);
          }
        };
        _proto.registerSystem = function registerSystem(name, sys, priority) {
          sys.id = name;
          sys.priority = priority;
          this._systems.push(sys);
          this._systems.sort(System.sortByPriority);
        };
        _proto.unregisterSystem = function unregisterSystem(sys) {
          fastRemove(this._systems, sys);
          this._systems.sort(System.sortByPriority);
        };
        _proto.getSystem = function getSystem(name) {
          return this._systems.find(function (sys) {
            return sys.id === name;
          });
        };
        _proto.getAnimationManager = function getAnimationManager() {
          return this.getSystem(legacyCC.AnimationManager.ID);
        };
        _proto.startAnimation = function startAnimation() {
          this._invalid = false;
        };
        _proto.stopAnimation = function stopAnimation() {
          this._invalid = true;
        };
        _proto.mainLoop = function mainLoop(now) {
          var dt;
          {
            dt = legacyCC.game._calculateDT(now);
          }
          this.tick(dt);
        };
        _proto.tick = function tick(dt) {
          if (!this._invalid) {
            this.emit(Director.EVENT_BEGIN_FRAME);
            {
              input$1._frameDispatchEvents();
            }
            if (!this._paused) {
              this.emit(Director.EVENT_BEFORE_UPDATE);
              this._compScheduler.startPhase();
              this._compScheduler.updatePhase(dt);
              for (var i = 0; i < this._systems.length; ++i) {
                this._systems[i].update(dt);
              }
              this._compScheduler.lateUpdatePhase(dt);
              this.emit(Director.EVENT_AFTER_UPDATE);
              CCObject._deferredDestroy();
              for (var _i = 0; _i < this._systems.length; ++_i) {
                this._systems[_i].postUpdate(dt);
              }
            }
            this.emit(Director.EVENT_BEFORE_DRAW);
            uiRendererManager.updateAllDirtyRenderers();
            this._root.frameMove(dt);
            this.emit(Director.EVENT_AFTER_DRAW);
            Node$1.resetHasChangedFlags();
            Node$1.clearNodeArray();
            scalableContainerManager.update(dt);
            this.emit(Director.EVENT_END_FRAME);
            this._totalFrames++;
          }
        };
        _proto.buildRenderPipeline = function buildRenderPipeline() {
          if (this._root) {
            this._root.customPipeline.beginSetup();
            var builder = legacyCC.rendering.getCustomPipeline(macro.CUSTOM_PIPELINE_NAME);
            builder.setup(this._root.cameraList, this._root.customPipeline);
            this._root.customPipeline.endSetup();
          }
        };
        _proto.setupRenderPipelineBuilder = function setupRenderPipelineBuilder() {
          if (macro.CUSTOM_PIPELINE_NAME !== '' && legacyCC.rendering && this._root && this._root.usesCustomPipeline) {
            this.on(Director.EVENT_BEFORE_RENDER, this.buildRenderPipeline, this);
          }
        };
        _proto.init = function init() {
          this._totalFrames = 0;
          this._paused = false;
          this.registerSystem(Scheduler.ID, this._scheduler, 200);
          this._root = new Root(deviceManager.gfxDevice);
          var rootInfo = {};
          this._root.initialize(rootInfo);
          this.setupRenderPipelineBuilder();
          for (var i = 0; i < this._systems.length; i++) {
            this._systems[i].init();
          }
          this.emit(Director.EVENT_INIT);
        };
        _proto.addPersistRootNode = function addPersistRootNode(node) {
          if (!Node$1.isNode(node) || !node.uuid) {
            warnID(3800);
            return;
          }
          var id = node.uuid;
          if (!this._persistRootNodes[id]) {
            var _scene = this._scene;
            if (isValid(_scene)) {
              if (!node.parent) {
                node.parent = _scene;
                node._originalSceneId = _scene.uuid;
              } else if (!(node.parent instanceof Scene)) {
                warnID(3801);
                return;
              } else if (node.parent !== _scene) {
                warnID(3802);
                return;
              } else {
                node._originalSceneId = _scene.uuid;
              }
            }
            this._persistRootNodes[id] = node;
            node._persistNode = true;
            releaseManager._addPersistNodeRef(node);
          }
        };
        _proto.removePersistRootNode = function removePersistRootNode(node) {
          var id = node.uuid || '';
          if (node === this._persistRootNodes[id]) {
            delete this._persistRootNodes[id];
            node._persistNode = false;
            node._originalSceneId = '';
            releaseManager._removePersistNodeRef(node);
          }
        };
        _proto.isPersistRootNode = function isPersistRootNode(node) {
          return !!node._persistNode;
        };
        _createClass(Director, [{
          key: "root",
          get: function get() {
            return this._root;
          }
        }]);
        return Director;
      }(EventTarget));
      Director.EVENT_INIT = 'director_init';
      Director.EVENT_RESET = 'director_reset';
      Director.EVENT_BEFORE_SCENE_LOADING = 'director_before_scene_loading';
      Director.EVENT_BEFORE_SCENE_LAUNCH = 'director_before_scene_launch';
      Director.EVENT_AFTER_SCENE_LAUNCH = 'director_after_scene_launch';
      Director.EVENT_BEFORE_UPDATE = 'director_before_update';
      Director.EVENT_AFTER_UPDATE = 'director_after_update';
      Director.EVENT_BEFORE_DRAW = 'director_before_draw';
      Director.EVENT_AFTER_DRAW = 'director_after_draw';
      Director.EVENT_BEFORE_COMMIT = 'director_before_commit';
      Director.EVENT_BEFORE_RENDER = 'director_before_render';
      Director.EVENT_AFTER_RENDER = 'director_after_render';
      Director.EVENT_BEFORE_PHYSICS = 'director_before_physics';
      Director.EVENT_AFTER_PHYSICS = 'director_after_physics';
      Director.EVENT_BEGIN_FRAME = 'director_begin_frame';
      Director.EVENT_END_FRAME = 'director_end_frame';
      Director.instance = void 0;
      legacyCC.Director = Director;
      var director = exports('dY', Director.instance = legacyCC.director = new Director());

      function findCanvas() {
        var frame = document.querySelector('#GameDiv');
        var container = document.querySelector('#Cocos3dGameContainer');
        var canvas = document.querySelector('#GameCanvas');
        return {
          frame: frame,
          container: container,
          canvas: canvas
        };
      }
      function loadJsFile(path) {
        return new Promise(function (resolve, reject) {
          var err;
          function windowErrorListener(evt) {
            if (evt.filename === path) {
              err = evt.error;
            }
          }
          window.addEventListener('error', windowErrorListener);
          var script = document.createElement('script');
          script.charset = 'utf-8';
          script.async = true;
          script.crossOrigin = 'anonymous';
          script.addEventListener('error', function () {
            window.removeEventListener('error', windowErrorListener);
            reject(Error("Error loading " + path));
          });
          script.addEventListener('load', function () {
            window.removeEventListener('error', windowErrorListener);
            document.head.removeChild(script);
            if (err) {
              reject(err);
            } else {
              resolve();
            }
          });
          script.src = path.replace('#', '%23');
          document.head.appendChild(script);
        });
      }

      var FRAME_RESET_TIME = 2000;
      var Pacer = function () {
        function Pacer() {
          var _this = this;
          this._stHandle = 0;
          this._onTick = null;
          this._targetFrameRate = 60;
          this._frameTime = 0;
          this._startTime = 0;
          this._isPlaying = false;
          this._frameCount = 0;
          this._callback = null;
          this._rAF = void 0;
          this._cAF = void 0;
          this._handleRAF = function () {
            var elapseTime = performance.now() - _this._startTime;
            var elapseFrame = Math.floor(elapseTime / _this._frameTime);
            if (elapseFrame < _this._frameCount) {
              _this._rAF.call(window, _this._handleRAF);
            } else {
              _this._frameCount++;
              if (_this._callback) {
                _this._callback();
              }
            }
            if (performance.now() - _this._startTime > FRAME_RESET_TIME) {
              _this._startTime = performance.now();
              _this._frameCount = 0;
            }
          };
          this._frameTime = 1000 / this._targetFrameRate;
          this._rAF = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame;
          this._cAF = window.cancelAnimationFrame || window.cancelRequestAnimationFrame || window.msCancelRequestAnimationFrame || window.mozCancelRequestAnimationFrame || window.oCancelRequestAnimationFrame || window.webkitCancelRequestAnimationFrame || window.msCancelAnimationFrame || window.mozCancelAnimationFrame || window.webkitCancelAnimationFrame || window.ocancelAnimationFrame;
        }
        var _proto = Pacer.prototype;
        _proto.start = function start() {
          var _globalThis$__globalX,
            _this2 = this;
          if (this._isPlaying) return;
          var recordStartTime = this._rAF === undefined || ((_globalThis$__globalX = globalThis.__globalXR) === null || _globalThis$__globalX === void 0 ? void 0 : _globalThis$__globalX.isWebXR);
          var updateCallback = function updateCallback() {
            if (recordStartTime) _this2._startTime = performance.now();
            if (_this2._isPlaying) {
              _this2._stHandle = _this2._stTime(updateCallback);
            }
            if (_this2._onTick) {
              _this2._onTick();
            }
          };
          this._startTime = performance.now();
          this._stHandle = this._stTime(updateCallback);
          this._isPlaying = true;
          this._frameCount = 0;
        };
        _proto.stop = function stop() {
          if (!this._isPlaying) return;
          this._ctTime(this._stHandle);
          this._stHandle = 0;
          this._isPlaying = false;
          this._frameCount = 0;
        };
        _proto._stTime = function _stTime(callback) {
          var _globalThis$__globalX2;
          if (this._rAF === undefined || (_globalThis$__globalX2 = globalThis.__globalXR) !== null && _globalThis$__globalX2 !== void 0 && _globalThis$__globalX2.isWebXR) {
            var currTime = performance.now();
            var elapseTime = Math.max(0, currTime - this._startTime);
            var timeToCall = Math.max(0, this._frameTime - elapseTime);
            return setTimeout(callback, timeToCall);
          }
          this._callback = callback;
          return this._rAF.call(window, this._handleRAF);
        };
        _proto._ctTime = function _ctTime(id) {
          var _globalThis$__globalX3;
          if (this._cAF === undefined || (_globalThis$__globalX3 = globalThis.__globalXR) !== null && _globalThis$__globalX3 !== void 0 && _globalThis$__globalX3.isWebXR) {
            clearTimeout(id);
          } else if (id) {
            this._cAF.call(window, id);
          }
        };
        _createClass(Pacer, [{
          key: "targetFrameRate",
          get: function get() {
            return this._targetFrameRate;
          },
          set: function set(val) {
            if (this._targetFrameRate !== val) {
              assertIsTrue(val > 0);
              this._targetFrameRate = val;
              this._frameTime = 1000 / this._targetFrameRate;
              if (this._isPlaying) {
                this.stop();
                this.start();
              }
            }
          }
        }, {
          key: "onTick",
          get: function get() {
            return this._onTick;
          },
          set: function set(val) {
            this._onTick = val;
          }
        }]);
        return Pacer;
      }();

      var EffectSettings = function () {
        function EffectSettings() {
          this._data = null;
        }
        var _proto = EffectSettings.prototype;
        _proto.init = function init(path) {
          var _this = this;
          if (path === void 0) {
            path = '';
          }
          if (!legacyCC.rendering || !legacyCC.rendering.enableEffectImport || !path) {
            return Promise.resolve();
          }
          return new Promise(function (resolve, reject) {
            {
              var xhr = new XMLHttpRequest();
              xhr.open('GET', path);
              xhr.responseType = 'arraybuffer';
              xhr.onload = function () {
                _this._data = xhr.response;
                resolve();
              };
              xhr.onerror = function () {
                reject(new Error('request effect settings failed!'));
              };
              xhr.send(null);
            }
          });
        };
        _createClass(EffectSettings, [{
          key: "data",
          get: function get() {
            return this._data;
          }
        }]);
        return EffectSettings;
      }();
      var effectSettings = new EffectSettings();
      legacyCC.effectSettings = effectSettings;

      var Game = exports('dZ', function (_EventTarget) {
        _inheritsLoose(Game, _EventTarget);
        function Game() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _EventTarget.call.apply(_EventTarget, [this].concat(args)) || this;
          _this.frame = null;
          _this.container = null;
          _this.canvas = null;
          _this.renderType = -1;
          _this.eventTargetOn = _EventTarget.prototype.on;
          _this.eventTargetOnce = _EventTarget.prototype.once;
          _this.config = {};
          _this.onStart = null;
          _this.frameTime = 1000 / 60;
          _this._isCloning = false;
          _this._inited = false;
          _this._engineInited = false;
          _this._rendererInitialized = false;
          _this._paused = true;
          _this._pausedByEngine = false;
          _this._frameRate = 60;
          _this._pacer = null;
          _this._initTime = 0;
          _this._startTime = 0;
          _this._deltaTime = 0.0;
          _this._useFixedDeltaTime = false;
          _this._shouldLoadLaunchScene = true;
          _this.onPreBaseInitDelegate = new AsyncDelegate();
          _this.onPostBaseInitDelegate = new AsyncDelegate();
          _this.onPreInfrastructureInitDelegate = new AsyncDelegate();
          _this.onPostInfrastructureInitDelegate = new AsyncDelegate();
          _this.onPreSubsystemInitDelegate = new AsyncDelegate();
          _this.onPostSubsystemInitDelegate = new AsyncDelegate();
          _this.onPreProjectInitDelegate = new AsyncDelegate();
          _this.onPostProjectInitDelegate = new AsyncDelegate();
          return _this;
        }
        var _proto = Game.prototype;
        _proto.setFrameRate = function setFrameRate(frameRate) {
          this.frameRate = frameRate;
        };
        _proto.getFrameRate = function getFrameRate() {
          return this.frameRate;
        };
        _proto.step = function step() {
          director.tick(this._calculateDT(true));
        };
        _proto.pauseByEngine = function pauseByEngine() {
          if (this._paused) {
            return;
          }
          this._pausedByEngine = true;
          this.pause();
        };
        _proto.resumeByEngine = function resumeByEngine() {
          if (this._pausedByEngine) {
            this.resume();
            this._pausedByEngine = false;
          }
        };
        _proto.pause = function pause() {
          var _this$_pacer;
          if (this._paused) {
            return;
          }
          this._paused = true;
          (_this$_pacer = this._pacer) === null || _this$_pacer === void 0 ? void 0 : _this$_pacer.stop();
          this.emit(Game.EVENT_PAUSE);
        };
        _proto.resume = function resume() {
          var _this$_pacer2;
          if (!this._paused) {
            return;
          }
          input$1._clearEvents();
          this._paused = false;
          (_this$_pacer2 = this._pacer) === null || _this$_pacer2 === void 0 ? void 0 : _this$_pacer2.start();
          this.emit(Game.EVENT_RESUME);
        };
        _proto.isPaused = function isPaused() {
          return this._paused;
        };
        _proto.restart = function restart() {
          var _this2 = this;
          var endFramePromise = new Promise(function (resolve) {
            director.once(Director.EVENT_END_FRAME, function () {
              return resolve();
            });
          });
          return endFramePromise.then(function () {
            director.reset();
            legacyCC.Object._deferredDestroy();
            _this2.pause();
            _this2.resume();
            _this2._shouldLoadLaunchScene = true;
            SplashScreen.instance.curTime = 0;
            _this2._safeEmit(Game.EVENT_RESTART);
          });
        };
        _proto.end = function end() {
          systemInfo.close();
        };
        _proto.on = function on(type, callback, target, once) {
          if (this.canRegisterEvent(type)) {
            callback.call(target);
          }
          return this.eventTargetOn(type, callback, target, once);
        };
        _proto.once = function once(type, callback, target) {
          if (this.canRegisterEvent(type)) {
            return callback.call(target);
          }
          return this.eventTargetOnce(type, callback, target);
        };
        _proto.canRegisterEvent = function canRegisterEvent(type) {
          return this._engineInited && type === Game.EVENT_ENGINE_INITED || this._inited && type === Game.EVENT_GAME_INITED || this._rendererInitialized && type === Game.EVENT_RENDERER_INITED;
        };
        _proto.init = function init(config) {
          var _this3 = this;
          this._compatibleWithOldParams(config);
          return Promise.resolve().then(function () {
            _this3.emit(Game.EVENT_PRE_BASE_INIT);
            return _this3.onPreBaseInitDelegate.dispatch();
          }).then(function () {
            {
              console.time('Init Base');
            }
            var debugMode = config.debugMode || DebugMode.NONE;
            _resetDebugSetting(debugMode);
          }).then(function () {
            return sys.init();
          }).then(function () {
            _this3._initEvents();
          }).then(function () {
            return settings.init(config.settingsPath, config.overrideSettings);
          }).then(function () {
            {
              console.timeEnd('Init Base');
            }
            _this3.emit(Game.EVENT_POST_BASE_INIT);
            return _this3.onPostBaseInitDelegate.dispatch();
          }).then(function () {
            _this3.emit(Game.EVENT_PRE_INFRASTRUCTURE_INIT);
            return _this3.onPreInfrastructureInitDelegate.dispatch();
          }).then(function () {
            {
              console.time('Init Infrastructure');
            }
            macro.init();
            _this3._initXR();
            var adapter = findCanvas();
            if (adapter) {
              _this3.canvas = adapter.canvas;
              _this3.frame = adapter.frame;
              _this3.container = adapter.container;
            }
            screen.init();
            garbageCollectionManager.init();
            deviceManager.init(_this3.canvas, bindingMappingInfo);
            if (macro.CUSTOM_PIPELINE_NAME === '') {
              legacyCC.rendering = undefined;
            }
            assetManager.init();
            builtinResMgr.init();
            Layers.init();
            _this3.initPacer();
            {
              console.timeEnd('Init Infrastructure');
            }
          }).then(function () {
            _this3.emit(Game.EVENT_POST_INFRASTRUCTURE_INIT);
            return _this3.onPostInfrastructureInitDelegate.dispatch();
          }).then(function () {
            _this3.emit(Game.EVENT_PRE_SUBSYSTEM_INIT);
            return _this3.onPreSubsystemInitDelegate.dispatch();
          }).then(function () {
            return effectSettings.init(settings.querySettings(Settings.Category.RENDERING, 'effectSettingsPath'));
          }).then(function () {
            if (!legacyCC.rendering || !legacyCC.rendering.enableEffectImport) {
              return;
            }
            var renderMode = settings.querySettings(Settings.Category.RENDERING, 'renderMode');
            if (renderMode === LegacyRenderMode.HEADLESS) {
              legacyCC.rendering.init(deviceManager.gfxDevice, null);
              return;
            }
            var data = effectSettings.data;
            if (data === null) {
              errorID(1102);
              return;
            }
            legacyCC.rendering.init(deviceManager.gfxDevice, data);
          }).then(function () {
            var scriptPackages = settings.querySettings(Settings.Category.SCRIPTING, 'scriptPackages');
            if (scriptPackages) {
              return Promise.all(scriptPackages.map(function (pack) {
                return module.import(pack);
              }));
            }
            return Promise.resolve([]);
          }).then(function () {
            {
              console.time('Init SubSystem');
            }
            director.init();
            return builtinResMgr.loadBuiltinAssets();
          }).then(function () {
            {
              console.timeEnd('Init SubSystem');
            }
            _this3.emit(Game.EVENT_POST_SUBSYSTEM_INIT);
            return _this3.onPostSubsystemInitDelegate.dispatch();
          }).then(function () {
            log("Cocos Creator v" + engineVersion);
            _this3.emit(Game.EVENT_ENGINE_INITED);
            _this3._engineInited = true;
          }).then(function () {
            _this3.emit(Game.EVENT_PRE_PROJECT_INIT);
            return _this3.onPreProjectInitDelegate.dispatch();
          }).then(function () {
            {
              console.time('Init Project');
            }
            var jsList = settings.querySettings(Settings.Category.PLUGINS, 'jsList');
            var promise = Promise.resolve();
            if (jsList) {
              jsList.forEach(function (jsListFile) {
                promise = promise.then(function () {
                  return loadJsFile(('src') + "/" + jsListFile);
                });
              });
            }
            return promise;
          }).then(function () {
            return _this3._loadProjectBundles();
          }).then(function () {
            return _this3._loadCCEScripts();
          }).then(function () {
            return _this3._setupRenderPipeline();
          }).then(function () {
            return _this3._loadPreloadAssets();
          }).then(function () {
            builtinResMgr.compileBuiltinMaterial();
            return SplashScreen.instance.init();
          }).then(function () {
            {
              console.timeEnd('Init Project');
            }
            _this3.emit(Game.EVENT_POST_PROJECT_INIT);
            return _this3.onPostProjectInitDelegate.dispatch();
          }).then(function () {
            _this3._inited = true;
            _this3._safeEmit(Game.EVENT_GAME_INITED);
          });
        };
        _proto._initXR = function _initXR() {
          var _settings$querySettin;
          if (typeof globalThis.__globalXR === 'undefined') {
            globalThis.__globalXR = {};
          }
          var globalXR = globalThis.__globalXR;
          globalXR.webxrCompatible = (_settings$querySettin = settings.querySettings(Settings.Category.XR, 'webxrCompatible')) !== null && _settings$querySettin !== void 0 ? _settings$querySettin : false;
          if (sys.isXR) {
            var _settings$querySettin2, _settings$querySettin3;
            xr.entry = xr.XrEntry.getInstance();
            var xrMSAA = (_settings$querySettin2 = settings.querySettings(Settings.Category.RENDERING, 'msaa')) !== null && _settings$querySettin2 !== void 0 ? _settings$querySettin2 : 1;
            var xrRenderingScale = (_settings$querySettin3 = settings.querySettings(Settings.Category.RENDERING, 'renderingScale')) !== null && _settings$querySettin3 !== void 0 ? _settings$querySettin3 : 1.0;
            xr.entry.setMultisamplesRTT(xrMSAA);
            xr.entry.setRenderingScale(xrRenderingScale);
          }
        };
        _proto._compatibleWithOldParams = function _compatibleWithOldParams(config) {
          var overrideSettings = config.overrideSettings = config.overrideSettings || {};
          if ('showFPS' in config) {
            overrideSettings.profiling = overrideSettings.profiling || {};
            overrideSettings.profiling.showFPS = config.showFPS;
          }
          if ('frameRate' in config) {
            overrideSettings.screen = overrideSettings.screen || {};
            overrideSettings.screen.frameRate = config.frameRate;
          }
          if ('renderMode' in config) {
            overrideSettings.rendering = overrideSettings.rendering || {};
            overrideSettings.rendering.renderMode = config.renderMode;
          }
          if ('renderPipeline' in config) {
            overrideSettings.rendering = overrideSettings.rendering || {};
            overrideSettings.rendering.renderPipeline = config.renderPipeline;
          }
          if ('assetOptions' in config) {
            overrideSettings.assets = overrideSettings.assets || {};
            Object.assign(overrideSettings.assets, config.assetOptions);
          }
          if ('customJointTextureLayouts' in config) {
            overrideSettings.animation = overrideSettings.animation || {};
            overrideSettings.animation.customJointTextureLayouts = config.customJointTextureLayouts;
          }
          if ('physics' in config) {
            overrideSettings.physics = overrideSettings.physics || {};
            Object.assign(overrideSettings.physics, config.physics);
          }
          if ('orientation' in config) {
            overrideSettings.screen = overrideSettings.screen || {};
            overrideSettings.screen.orientation = config.orientation;
          }
          if ('exactFitScreen' in config) {
            overrideSettings.screen = overrideSettings.screen || {};
            overrideSettings.screen.exactFitScreen = config.exactFitScreen;
          }
        };
        _proto._loadPreloadAssets = function _loadPreloadAssets() {
          var preloadAssets = settings.querySettings(Settings.Category.ASSETS, 'preloadAssets');
          if (!preloadAssets) return Promise.resolve([]);
          return Promise.all(preloadAssets.map(function (uuid) {
            return new Promise(function (resolve, reject) {
              assetManager.loadAny(uuid, function (err) {
                if (err) {
                  reject(err);
                  return;
                }
                resolve();
              });
            });
          }));
        };
        _proto._loadCCEScripts = function _loadCCEScripts() {
          return new Promise(function (resolve, reject) {
            {
              resolve();
            }
          });
        };
        _proto._loadProjectBundles = function _loadProjectBundles() {
          var preloadBundles = settings.querySettings(Settings.Category.ASSETS, 'preloadBundles');
          if (!preloadBundles) return Promise.resolve([]);
          return Promise.all(preloadBundles.map(function (_ref) {
            var bundle = _ref.bundle,
              version = _ref.version;
            return new Promise(function (resolve, reject) {
              var opts = {};
              if (version) opts.version = version;
              assetManager.loadBundle(bundle, opts, function (err) {
                if (err) {
                  reject(err);
                  return;
                }
                resolve();
              });
            });
          }));
        };
        _proto.run = function run(onStart) {
          if (onStart) {
            this.onStart = onStart;
          }
          if (!this._inited || EDITOR_NOT_IN_PREVIEW) {
            return;
          }
          this.resume();
        };
        _proto._calculateDT = function _calculateDT(useFixedDeltaTime) {
          this._useFixedDeltaTime = useFixedDeltaTime;
          if (useFixedDeltaTime) {
            this._startTime = performance.now();
            return this.frameTime / 1000;
          }
          var now = performance.now();
          this._deltaTime = now > this._startTime ? (now - this._startTime) / 1000 : 0;
          if (this._deltaTime > Game.DEBUG_DT_THRESHOLD) {
            this._deltaTime = this.frameTime / 1000;
          }
          this._startTime = now;
          return this._deltaTime;
        };
        _proto._updateCallback = function _updateCallback() {
          var _this4 = this;
          if (!this._inited) return;
          if (!SplashScreen.instance.isFinished) {
            SplashScreen.instance.update(this._calculateDT(false));
          } else if (this._shouldLoadLaunchScene) {
            this._shouldLoadLaunchScene = false;
            var launchScene = settings.querySettings(Settings.Category.LAUNCH, 'launchScene');
            if (launchScene) {
              director.loadScene(launchScene, function () {
                var _this4$onStart;
                logID(1103, launchScene);
                _this4._initTime = performance.now();
                director.startAnimation();
                (_this4$onStart = _this4.onStart) === null || _this4$onStart === void 0 ? void 0 : _this4$onStart.call(_this4);
              });
            } else {
              var _this$onStart;
              this._initTime = performance.now();
              director.startAnimation();
              (_this$onStart = this.onStart) === null || _this$onStart === void 0 ? void 0 : _this$onStart.call(this);
            }
          } else {
            director.tick(this._calculateDT(false));
          }
        };
        _proto.initPacer = function initPacer() {
          var _settings$querySettin4;
          var frameRate = (_settings$querySettin4 = settings.querySettings(Settings.Category.SCREEN, 'frameRate')) !== null && _settings$querySettin4 !== void 0 ? _settings$querySettin4 : 60;
          assert(typeof frameRate === 'number');
          this._pacer = new Pacer();
          this._pacer.onTick = this._updateCallback.bind(this);
          this.frameRate = frameRate;
        };
        _proto._initEvents = function _initEvents() {
          systemInfo.on('show', this._onShow, this);
          systemInfo.on('hide', this._onHide, this);
          systemInfo.on('close', this._onClose, this);
        };
        _proto._onHide = function _onHide() {
          this.emit(Game.EVENT_HIDE);
          this.pauseByEngine();
        };
        _proto._onShow = function _onShow() {
          this.emit(Game.EVENT_SHOW);
          this.resumeByEngine();
        };
        _proto._onClose = function _onClose() {
          this.emit(Game.EVENT_CLOSE);
          systemInfo.exit();
        };
        _proto.addPersistRootNode = function addPersistRootNode(node) {
          director.addPersistRootNode(node);
        };
        _proto.removePersistRootNode = function removePersistRootNode(node) {
          director.removePersistRootNode(node);
        };
        _proto.isPersistRootNode = function isPersistRootNode(node) {
          return director.isPersistRootNode(node);
        };
        _proto._setupRenderPipeline = function _setupRenderPipeline() {
          var _this5 = this;
          var renderPipeline = settings.querySettings(Settings.Category.RENDERING, 'renderPipeline');
          if (!renderPipeline) {
            return this._setRenderPipeline();
          }
          return new Promise(function (resolve, reject) {
            assetManager.loadAny(renderPipeline, function (err, asset) {
              return err || !(asset instanceof RenderPipeline) ? reject(err) : resolve(asset);
            });
          }).then(function (asset) {
            _this5._setRenderPipeline(asset);
          })["catch"](function (reason) {
            warn(reason);
            warn("Failed load render pipeline: " + renderPipeline + ", engine failed to initialize, will fallback to default pipeline");
            _this5._setRenderPipeline();
          });
        };
        _proto._setRenderPipeline = function _setRenderPipeline(rppl) {
          if (!director.root.setRenderPipeline(rppl)) {
            this._setRenderPipeline();
          }
          this._rendererInitialized = true;
          this._safeEmit(Game.EVENT_RENDERER_INITED);
        };
        _proto._safeEmit = function _safeEmit(event) {
          {
            this.emit(event);
          }
        };
        _createClass(Game, [{
          key: "inited",
          get: function get() {
            return this._inited;
          }
        }, {
          key: "frameRate",
          get: function get() {
            return this._frameRate;
          },
          set: function set(frameRate) {
            if (typeof frameRate !== 'number') {
              frameRate = parseInt(frameRate, 10);
              if (Number.isNaN(frameRate)) {
                frameRate = 60;
              }
            }
            this._frameRate = frameRate;
            this.frameTime = 1000 / frameRate;
            if (this._pacer) this._pacer.targetFrameRate = this._frameRate;
          }
        }, {
          key: "deltaTime",
          get: function get() {
            return this._useFixedDeltaTime ? this.frameTime / 1000 : this._deltaTime;
          }
        }, {
          key: "totalTime",
          get: function get() {
            return performance.now() - this._initTime;
          }
        }, {
          key: "frameStartTime",
          get: function get() {
            return this._startTime;
          }
        }]);
        return Game;
      }(EventTarget));
      Game.EVENT_HIDE = 'game_on_hide';
      Game.EVENT_SHOW = 'game_on_show';
      Game.EVENT_LOW_MEMORY = 'game_on_low_memory';
      Game.EVENT_GAME_INITED = 'game_inited';
      Game.EVENT_ENGINE_INITED = 'engine_inited';
      Game.EVENT_RENDERER_INITED = 'renderer_inited';
      Game.EVENT_PRE_BASE_INIT = 'pre_base_init';
      Game.EVENT_POST_BASE_INIT = 'post_base_init';
      Game.EVENT_PRE_INFRASTRUCTURE_INIT = 'pre_infrastructure_init';
      Game.EVENT_POST_INFRASTRUCTURE_INIT = 'post_infrastructure_init';
      Game.EVENT_PRE_SUBSYSTEM_INIT = 'pre_subsystem_init';
      Game.EVENT_POST_SUBSYSTEM_INIT = 'post_subsystem_init';
      Game.EVENT_PRE_PROJECT_INIT = 'pre_project_init';
      Game.EVENT_POST_PROJECT_INIT = 'post_project_init';
      Game.EVENT_RESTART = 'game_on_restart';
      Game.EVENT_PAUSE = 'game_on_pause';
      Game.EVENT_RESUME = 'game_on_resume';
      Game.EVENT_CLOSE = 'game_on_close';
      Game.RENDER_TYPE_CANVAS = 0;
      Game.RENDER_TYPE_WEBGL = 1;
      Game.RENDER_TYPE_OPENGL = 2;
      Game.RENDER_TYPE_HEADLESS = 3;
      Game.DEBUG_DT_THRESHOLD = 1;
      legacyCC.Game = Game;
      var game = exports('d_', legacyCC.game = new Game());

      var DynamicAtlasManager = exports('X', function (_System) {
        _inheritsLoose(DynamicAtlasManager, _System);
        function DynamicAtlasManager() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _System.call.apply(_System, [this].concat(args)) || this;
          _this._atlases = [];
          _this._atlasIndex = -1;
          _this._maxAtlasCount = 5;
          _this._textureSize = 2048;
          _this._maxFrameSize = 512;
          _this._textureBleeding = true;
          _this._enabled = false;
          return _this;
        }
        var _proto = DynamicAtlasManager.prototype;
        _proto.newAtlas = function newAtlas() {
          var atlas = this._atlases[++this._atlasIndex];
          if (!atlas) {
            atlas = new Atlas(this._textureSize, this._textureSize);
            this._atlases.push(atlas);
          }
          return atlas;
        };
        _proto.beforeSceneLoad = function beforeSceneLoad() {
          this.reset();
        };
        _proto.init = function init() {
          this.enabled = !macro.CLEANUP_IMAGE_CACHE;
        };
        _proto.insertSpriteFrame = function insertSpriteFrame(spriteFrame) {
          if (!this._enabled || this._atlasIndex === this._maxAtlasCount || !spriteFrame || spriteFrame._original) return null;
          if (!spriteFrame.packable) return null;
          var sampler = spriteFrame.texture.getSamplerInfo();
          if (sampler.minFilter !== Filter.LINEAR || sampler.magFilter !== Filter.LINEAR || sampler.mipFilter !== Filter.NONE) {
            return null;
          }
          var atlas = this._atlases[this._atlasIndex];
          if (!atlas) {
            atlas = this.newAtlas();
          }
          var frame = atlas.insertSpriteFrame(spriteFrame);
          if (!frame && this._atlasIndex !== this._maxAtlasCount) {
            atlas = this.newAtlas();
            return atlas.insertSpriteFrame(spriteFrame);
          }
          return frame;
        };
        _proto.reset = function reset() {
          for (var i = 0, l = this._atlases.length; i < l; i++) {
            this._atlases[i].destroy();
          }
          this._atlases.length = 0;
          this._atlasIndex = -1;
        };
        _proto.deleteAtlasSpriteFrame = function deleteAtlasSpriteFrame(spriteFrame) {
          if (!spriteFrame._original) return;
          var atlas;
          for (var i = this._atlases.length - 1; i >= 0; i--) {
            atlas = this._atlases[i];
            fastRemove(atlas._innerSpriteFrames, spriteFrame);
          }
          var texture = spriteFrame._original._texture;
          this.deleteAtlasTexture(texture);
        };
        _proto.deleteAtlasTexture = function deleteAtlasTexture(texture) {
          if (texture) {
            for (var i = this._atlases.length - 1; i >= 0; i--) {
              this._atlases[i].deleteInnerTexture(texture);
              if (this._atlases[i].isEmpty()) {
                this._atlases[i].destroy();
                this._atlases.splice(i, 1);
                this._atlasIndex--;
              }
            }
          }
        };
        _proto.packToDynamicAtlas = function packToDynamicAtlas(comp, frame) {
          if (!this._enabled) return;
          if (frame && !frame._original && frame.packable && frame.texture && frame.texture.width > 0 && frame.texture.height > 0) {
            var packedFrame = this.insertSpriteFrame(frame);
            if (packedFrame) {
              frame._setDynamicAtlasFrame(packedFrame);
            }
          }
        };
        _createClass(DynamicAtlasManager, [{
          key: "enabled",
          get: function get() {
            return this._enabled;
          },
          set: function set(value) {
            if (this._enabled === value) return;
            if (value) {
              this.reset();
              legacyCC.director.on(legacyCC.Director.EVENT_BEFORE_SCENE_LAUNCH, this.beforeSceneLoad, this);
            } else {
              this.reset();
              legacyCC.director.off(legacyCC.Director.EVENT_BEFORE_SCENE_LAUNCH, this.beforeSceneLoad, this);
            }
            this._enabled = value;
          }
        }, {
          key: "maxAtlasCount",
          get: function get() {
            return this._maxAtlasCount;
          },
          set: function set(value) {
            this._maxAtlasCount = value;
          }
        }, {
          key: "atlasCount",
          get: function get() {
            return this._atlases.length;
          }
        }, {
          key: "textureBleeding",
          get: function get() {
            return this._textureBleeding;
          },
          set: function set(enable) {
            this._textureBleeding = enable;
          }
        }, {
          key: "textureSize",
          get: function get() {
            return this._textureSize;
          },
          set: function set(value) {
            this._textureSize = value;
          }
        }, {
          key: "maxFrameSize",
          get: function get() {
            return this._maxFrameSize;
          },
          set: function set(value) {
            this._maxFrameSize = value;
          }
        }]);
        return DynamicAtlasManager;
      }(System));
      DynamicAtlasManager.instance = void 0;
      var dynamicAtlasManager = exports('Y', DynamicAtlasManager.instance = new DynamicAtlasManager());
      director.registerSystem('dynamicAtlasManager', dynamicAtlasManager, 0);
      legacyCC.internal.dynamicAtlasManager = dynamicAtlasManager;

      function toPPM(buffer, w, h) {
        return "P3 " + w + " " + h + " 255\n" + buffer.filter(function (e, i) {
          return i % 4 < 3;
        }).toString() + "\n";
      }

      var _keyMap;
      (function (_keyMap) {
        _keyMap[_keyMap["positions"] = AttributeName.ATTR_POSITION] = "positions";
        _keyMap[_keyMap["normals"] = AttributeName.ATTR_NORMAL] = "normals";
        _keyMap[_keyMap["uvs"] = AttributeName.ATTR_TEX_COORD] = "uvs";
        _keyMap[_keyMap["colors"] = AttributeName.ATTR_COLOR] = "colors";
      })(_keyMap || (_keyMap = {}));
      function readMesh(mesh, iPrimitive) {
        if (iPrimitive === void 0) {
          iPrimitive = 0;
        }
        var out = {
          positions: []
        };
        var dataView = new DataView(mesh.data.buffer, mesh.data.byteOffset, mesh.data.byteLength);
        var struct = mesh.struct;
        var primitive = struct.primitives[iPrimitive];
        for (var _iterator = _createForOfIteratorHelperLoose(primitive.vertexBundelIndices), _step; !(_step = _iterator()).done;) {
          var idx = _step.value;
          var bundle = struct.vertexBundles[idx];
          var offset = bundle.view.offset;
          var _bundle$view = bundle.view,
            length = _bundle$view.length,
            stride = _bundle$view.stride;
          for (var _iterator2 = _createForOfIteratorHelperLoose(bundle.attributes), _step2; !(_step2 = _iterator2()).done;) {
            var attr = _step2.value;
            var name = _keyMap[attr.name];
            if (name) {
              out[name] = (out[name] || []).concat(readBuffer(dataView, attr.format, offset, length, stride));
            }
            offset += FormatInfos[attr.format].size;
          }
        }
        var view = primitive.indexView;
        out.indices = readBuffer(dataView, Format["R" + view.stride * 8 + "UI"], view.offset, view.length);
        return out;
      }

      var BufferBlob = function () {
        function BufferBlob() {
          this._arrayBufferOrPaddings = [];
          this._length = 0;
        }
        var _proto = BufferBlob.prototype;
        _proto.setNextAlignment = function setNextAlignment(align) {
          if (align !== 0) {
            var remainder = this._length % align;
            if (remainder !== 0) {
              var padding = align - remainder;
              this._arrayBufferOrPaddings.push(padding);
              this._length += padding;
            }
          }
        };
        _proto.addBuffer = function addBuffer(arrayBuffer) {
          var result = this._length;
          this._arrayBufferOrPaddings.push(arrayBuffer);
          this._length += arrayBuffer.byteLength;
          return result;
        };
        _proto.getLength = function getLength() {
          return this._length;
        };
        _proto.getCombined = function getCombined() {
          var result = new Uint8Array(this._length);
          var counter = 0;
          this._arrayBufferOrPaddings.forEach(function (arrayBufferOrPadding) {
            if (typeof arrayBufferOrPadding === 'number') {
              counter += arrayBufferOrPadding;
            } else {
              result.set(new Uint8Array(arrayBufferOrPadding), counter);
              counter += arrayBufferOrPadding.byteLength;
            }
          });
          return result.buffer;
        };
        return BufferBlob;
      }();

      function createMorphRendering(mesh, gfxDevice) {
        return new StdMorphRendering(mesh, gfxDevice);
      }
      var StdMorphRendering = function () {
        function StdMorphRendering(mesh, gfxDevice) {
          this._mesh = void 0;
          this._subMeshRenderings = [];
          this._mesh = mesh;
          if (!this._mesh.struct.morph) {
            return;
          }
          var nSubMeshes = this._mesh.struct.primitives.length;
          this._subMeshRenderings = new Array(nSubMeshes).fill(null);
          for (var iSubMesh = 0; iSubMesh < nSubMeshes; ++iSubMesh) {
            var subMeshMorph = this._mesh.struct.morph.subMeshMorphs[iSubMesh];
            if (!subMeshMorph) {
              continue;
            }
            if (subMeshMorph.targets.length > UBOMorph.MAX_MORPH_TARGET_COUNT) {
              this._subMeshRenderings[iSubMesh] = new CpuComputing(this._mesh, iSubMesh, this._mesh.struct.morph, gfxDevice);
            } else {
              this._subMeshRenderings[iSubMesh] = new GpuComputing(this._mesh, iSubMesh, this._mesh.struct.morph, gfxDevice);
            }
          }
        }
        var _proto = StdMorphRendering.prototype;
        _proto.createInstance = function createInstance() {
          var _this = this;
          var nSubMeshes = this._mesh.struct.primitives.length;
          var subMeshInstances = new Array(nSubMeshes);
          for (var iSubMesh = 0; iSubMesh < nSubMeshes; ++iSubMesh) {
            var _this$_subMeshRenderi, _this$_subMeshRenderi2;
            subMeshInstances[iSubMesh] = (_this$_subMeshRenderi = (_this$_subMeshRenderi2 = this._subMeshRenderings[iSubMesh]) === null || _this$_subMeshRenderi2 === void 0 ? void 0 : _this$_subMeshRenderi2.createInstance()) !== null && _this$_subMeshRenderi !== void 0 ? _this$_subMeshRenderi : null;
          }
          return {
            setWeights: function setWeights(subMeshIndex, weights) {
              var _subMeshInstances$sub;
              (_subMeshInstances$sub = subMeshInstances[subMeshIndex]) === null || _subMeshInstances$sub === void 0 ? void 0 : _subMeshInstances$sub.setWeights(weights);
            },
            requiredPatches: function requiredPatches(subMeshIndex) {
              assertIsNonNullable(_this._mesh.struct.morph);
              var subMeshMorph = _this._mesh.struct.morph.subMeshMorphs[subMeshIndex];
              var subMeshRenderingInstance = subMeshInstances[subMeshIndex];
              if (subMeshRenderingInstance === null) {
                return null;
              }
              assertIsNonNullable(subMeshMorph);
              var patches = [{
                name: 'CC_USE_MORPH',
                value: true
              }, {
                name: 'CC_MORPH_TARGET_COUNT',
                value: subMeshMorph.targets.length
              }];
              if (subMeshMorph.attributes.includes(AttributeName.ATTR_POSITION)) {
                patches.push({
                  name: 'CC_MORPH_TARGET_HAS_POSITION',
                  value: true
                });
              }
              if (subMeshMorph.attributes.includes(AttributeName.ATTR_NORMAL)) {
                patches.push({
                  name: 'CC_MORPH_TARGET_HAS_NORMAL',
                  value: true
                });
              }
              if (subMeshMorph.attributes.includes(AttributeName.ATTR_TANGENT)) {
                patches.push({
                  name: 'CC_MORPH_TARGET_HAS_TANGENT',
                  value: true
                });
              }
              patches.push.apply(patches, subMeshRenderingInstance.requiredPatches());
              return patches;
            },
            adaptPipelineState: function adaptPipelineState(subMeshIndex, descriptorSet) {
              var _subMeshInstances$sub2;
              (_subMeshInstances$sub2 = subMeshInstances[subMeshIndex]) === null || _subMeshInstances$sub2 === void 0 ? void 0 : _subMeshInstances$sub2.adaptPipelineState(descriptorSet);
            },
            destroy: function destroy() {
              for (var _i = 0, _subMeshInstances = subMeshInstances; _i < _subMeshInstances.length; _i++) {
                var subMeshInstance = _subMeshInstances[_i];
                subMeshInstance === null || subMeshInstance === void 0 ? void 0 : subMeshInstance.destroy();
              }
            }
          };
        };
        return StdMorphRendering;
      }();
      var GpuComputing = function () {
        function GpuComputing(mesh, subMeshIndex, morph, gfxDevice) {
          this._gfxDevice = void 0;
          this._subMeshMorph = void 0;
          this._textureInfo = void 0;
          this._attributes = void 0;
          this._verticesCount = void 0;
          this._gfxDevice = gfxDevice;
          var subMeshMorph = morph.subMeshMorphs[subMeshIndex];
          assertIsNonNullable(subMeshMorph);
          this._subMeshMorph = subMeshMorph;
          enableVertexId(mesh, subMeshIndex, gfxDevice);
          var nVertices = mesh.struct.vertexBundles[mesh.struct.primitives[subMeshIndex].vertexBundelIndices[0]].view.count;
          this._verticesCount = nVertices;
          var nTargets = subMeshMorph.targets.length;
          var vec4Required = nVertices * nTargets;
          var vec4TextureFactory = createVec4TextureFactory(gfxDevice, vec4Required);
          this._textureInfo = {
            width: vec4TextureFactory.width,
            height: vec4TextureFactory.height
          };
          this._attributes = subMeshMorph.attributes.map(function (attributeName, attributeIndex) {
            var vec4Tex = vec4TextureFactory.create();
            var valueView = vec4Tex.valueView;
            subMeshMorph.targets.forEach(function (morphTarget, morphTargetIndex) {
              var displacementsView = morphTarget.displacements[attributeIndex];
              var displacements = new Float32Array(mesh.data.buffer, mesh.data.byteOffset + displacementsView.offset, displacementsView.count);
              var displacementsOffset = nVertices * morphTargetIndex * 4;
              for (var iVertex = 0; iVertex < nVertices; ++iVertex) {
                valueView[displacementsOffset + 4 * iVertex + 0] = displacements[3 * iVertex + 0];
                valueView[displacementsOffset + 4 * iVertex + 1] = displacements[3 * iVertex + 1];
                valueView[displacementsOffset + 4 * iVertex + 2] = displacements[3 * iVertex + 2];
              }
            });
            vec4Tex.updatePixels();
            return {
              name: attributeName,
              morphTexture: vec4Tex
            };
          });
        }
        var _proto2 = GpuComputing.prototype;
        _proto2.destroy = function destroy() {
          for (var _iterator = _createForOfIteratorHelperLoose(this._attributes), _step; !(_step = _iterator()).done;) {
            var attribute = _step.value;
            attribute.morphTexture.destroy();
          }
        };
        _proto2.createInstance = function createInstance() {
          var _this2 = this;
          var morphUniforms = new MorphUniforms(this._gfxDevice, this._subMeshMorph.targets.length);
          morphUniforms.setMorphTextureInfo(this._textureInfo.width, this._textureInfo.height);
          morphUniforms.setVerticesCount(this._verticesCount);
          morphUniforms.commit();
          return {
            setWeights: function setWeights(weights) {
              morphUniforms.setWeights(weights);
              morphUniforms.commit();
            },
            requiredPatches: function requiredPatches() {
              return [{
                name: 'CC_MORPH_TARGET_USE_TEXTURE',
                value: true
              }];
            },
            adaptPipelineState: function adaptPipelineState(descriptorSet) {
              for (var _iterator2 = _createForOfIteratorHelperLoose(_this2._attributes), _step2; !(_step2 = _iterator2()).done;) {
                var attribute = _step2.value;
                var binding = void 0;
                switch (attribute.name) {
                  case AttributeName.ATTR_POSITION:
                    binding = UNIFORM_POSITION_MORPH_TEXTURE_BINDING;
                    break;
                  case AttributeName.ATTR_NORMAL:
                    binding = UNIFORM_NORMAL_MORPH_TEXTURE_BINDING;
                    break;
                  case AttributeName.ATTR_TANGENT:
                    binding = UNIFORM_TANGENT_MORPH_TEXTURE_BINDING;
                    break;
                  default:
                    warn('Unexpected attribute!');
                    break;
                }
                if (binding !== undefined) {
                  descriptorSet.bindSampler(binding, attribute.morphTexture.sampler);
                  descriptorSet.bindTexture(binding, attribute.morphTexture.texture);
                }
              }
              descriptorSet.bindBuffer(UBOMorph.BINDING, morphUniforms.buffer);
              descriptorSet.update();
            },
            destroy: function destroy() {}
          };
        };
        return GpuComputing;
      }();
      var CpuComputing = function () {
        function CpuComputing(mesh, subMeshIndex, morph, gfxDevice) {
          this._gfxDevice = void 0;
          this._attributes = [];
          this._gfxDevice = gfxDevice;
          var subMeshMorph = morph.subMeshMorphs[subMeshIndex];
          assertIsNonNullable(subMeshMorph);
          enableVertexId(mesh, subMeshIndex, gfxDevice);
          this._attributes = subMeshMorph.attributes.map(function (attributeName, attributeIndex) {
            return {
              name: attributeName,
              targets: subMeshMorph.targets.map(function (attributeDisplacement) {
                return {
                  displacements: new Float32Array(mesh.data.buffer, mesh.data.byteOffset + attributeDisplacement.displacements[attributeIndex].offset, attributeDisplacement.displacements[attributeIndex].count)
                };
              })
            };
          });
        }
        var _proto3 = CpuComputing.prototype;
        _proto3.createInstance = function createInstance() {
          return new CpuComputingRenderingInstance(this, this._attributes[0].targets[0].displacements.length / 3, this._gfxDevice);
        };
        _createClass(CpuComputing, [{
          key: "data",
          get: function get() {
            return this._attributes;
          }
        }]);
        return CpuComputing;
      }();
      var CpuComputingRenderingInstance = function () {
        function CpuComputingRenderingInstance(owner, nVertices, gfxDevice) {
          this._attributes = void 0;
          this._owner = void 0;
          this._morphUniforms = void 0;
          this._owner = owner;
          this._morphUniforms = new MorphUniforms(gfxDevice, 0);
          var vec4TextureFactory = createVec4TextureFactory(gfxDevice, nVertices);
          this._morphUniforms.setMorphTextureInfo(vec4TextureFactory.width, vec4TextureFactory.height);
          this._morphUniforms.commit();
          this._attributes = this._owner.data.map(function (attributeMorph, attributeIndex) {
            var morphTexture = vec4TextureFactory.create();
            return {
              attributeName: attributeMorph.name,
              morphTexture: morphTexture
            };
          });
        }
        var _proto4 = CpuComputingRenderingInstance.prototype;
        _proto4.setWeights = function setWeights(weights) {
          for (var iAttribute = 0; iAttribute < this._attributes.length; ++iAttribute) {
            var myAttribute = this._attributes[iAttribute];
            var valueView = myAttribute.morphTexture.valueView;
            var attributeMorph = this._owner.data[iAttribute];
            assertIsTrue(weights.length === attributeMorph.targets.length);
            for (var iTarget = 0; iTarget < attributeMorph.targets.length; ++iTarget) {
              var targetDisplacements = attributeMorph.targets[iTarget].displacements;
              var weight = weights[iTarget];
              var nVertices = targetDisplacements.length / 3;
              if (iTarget === 0) {
                for (var iVertex = 0; iVertex < nVertices; ++iVertex) {
                  valueView[4 * iVertex + 0] = targetDisplacements[3 * iVertex + 0] * weight;
                  valueView[4 * iVertex + 1] = targetDisplacements[3 * iVertex + 1] * weight;
                  valueView[4 * iVertex + 2] = targetDisplacements[3 * iVertex + 2] * weight;
                }
              } else if (weight !== 0.0) {
                for (var _iVertex = 0; _iVertex < nVertices; ++_iVertex) {
                  valueView[4 * _iVertex + 0] += targetDisplacements[3 * _iVertex + 0] * weight;
                  valueView[4 * _iVertex + 1] += targetDisplacements[3 * _iVertex + 1] * weight;
                  valueView[4 * _iVertex + 2] += targetDisplacements[3 * _iVertex + 2] * weight;
                }
              }
            }
            myAttribute.morphTexture.updatePixels();
          }
        };
        _proto4.requiredPatches = function requiredPatches() {
          return [{
            name: 'CC_MORPH_TARGET_USE_TEXTURE',
            value: true
          }, {
            name: 'CC_MORPH_PRECOMPUTED',
            value: true
          }];
        };
        _proto4.adaptPipelineState = function adaptPipelineState(descriptorSet) {
          for (var _iterator3 = _createForOfIteratorHelperLoose(this._attributes), _step3; !(_step3 = _iterator3()).done;) {
            var attribute = _step3.value;
            var attributeName = attribute.attributeName;
            var binding = void 0;
            switch (attributeName) {
              case AttributeName.ATTR_POSITION:
                binding = UNIFORM_POSITION_MORPH_TEXTURE_BINDING;
                break;
              case AttributeName.ATTR_NORMAL:
                binding = UNIFORM_NORMAL_MORPH_TEXTURE_BINDING;
                break;
              case AttributeName.ATTR_TANGENT:
                binding = UNIFORM_TANGENT_MORPH_TEXTURE_BINDING;
                break;
              default:
                warn('Unexpected attribute!');
                break;
            }
            if (binding !== undefined) {
              descriptorSet.bindSampler(binding, attribute.morphTexture.sampler);
              descriptorSet.bindTexture(binding, attribute.morphTexture.texture);
            }
          }
          descriptorSet.bindBuffer(UBOMorph.BINDING, this._morphUniforms.buffer);
          descriptorSet.update();
        };
        _proto4.destroy = function destroy() {
          this._morphUniforms.destroy();
          for (var iAttribute = 0; iAttribute < this._attributes.length; ++iAttribute) {
            var myAttribute = this._attributes[iAttribute];
            myAttribute.morphTexture.destroy();
          }
        };
        return CpuComputingRenderingInstance;
      }();
      var MorphUniforms = function () {
        function MorphUniforms(gfxDevice, targetCount) {
          this._targetCount = void 0;
          this._localBuffer = void 0;
          this._remoteBuffer = void 0;
          this._targetCount = targetCount;
          this._localBuffer = new DataView(new ArrayBuffer(UBOMorph.SIZE));
          this._remoteBuffer = gfxDevice.createBuffer(new BufferInfo(BufferUsageBit.UNIFORM | BufferUsageBit.TRANSFER_DST, MemoryUsageBit.HOST | MemoryUsageBit.DEVICE, UBOMorph.SIZE, UBOMorph.SIZE));
        }
        var _proto5 = MorphUniforms.prototype;
        _proto5.destroy = function destroy() {
          this._remoteBuffer.destroy();
        };
        _proto5.setWeights = function setWeights(weights) {
          assertIsTrue(weights.length === this._targetCount);
          for (var iWeight = 0; iWeight < weights.length; ++iWeight) {
            this._localBuffer.setFloat32(UBOMorph.OFFSET_OF_WEIGHTS + 4 * iWeight, weights[iWeight], legacyCC.sys.isLittleEndian);
          }
        };
        _proto5.setMorphTextureInfo = function setMorphTextureInfo(width, height) {
          this._localBuffer.setFloat32(UBOMorph.OFFSET_OF_DISPLACEMENT_TEXTURE_WIDTH, width, legacyCC.sys.isLittleEndian);
          this._localBuffer.setFloat32(UBOMorph.OFFSET_OF_DISPLACEMENT_TEXTURE_HEIGHT, height, legacyCC.sys.isLittleEndian);
        };
        _proto5.setVerticesCount = function setVerticesCount(count) {
          this._localBuffer.setFloat32(UBOMorph.OFFSET_OF_VERTICES_COUNT, count, legacyCC.sys.isLittleEndian);
        };
        _proto5.commit = function commit() {
          this._remoteBuffer.update(this._localBuffer.buffer);
        };
        _createClass(MorphUniforms, [{
          key: "buffer",
          get: function get() {
            return this._remoteBuffer;
          }
        }]);
        return MorphUniforms;
      }();
      function createVec4TextureFactory(gfxDevice, vec4Capacity) {
        var hasFeatureFloatTexture = gfxDevice.getFormatFeatures(Format.RGBA32F) & FormatFeatureBit.SAMPLED_TEXTURE;
        var pixelRequired;
        var pixelFormat;
        var pixelBytes;
        var UpdateViewConstructor;
        if (hasFeatureFloatTexture) {
          pixelRequired = vec4Capacity;
          pixelBytes = 16;
          pixelFormat = Texture2D.PixelFormat.RGBA32F;
          UpdateViewConstructor = Float32Array;
        } else {
          pixelRequired = 4 * vec4Capacity;
          pixelBytes = 4;
          pixelFormat = Texture2D.PixelFormat.RGBA8888;
          UpdateViewConstructor = Uint8Array;
        }
        var _bestSizeToHavePixels = bestSizeToHavePixels(pixelRequired),
          width = _bestSizeToHavePixels.width,
          height = _bestSizeToHavePixels.height;
        assertIsTrue(width * height >= pixelRequired);
        return {
          width: width,
          height: height,
          create: function create() {
            var arrayBuffer = new ArrayBuffer(width * height * pixelBytes);
            var valueView = new Float32Array(arrayBuffer);
            var updateView = UpdateViewConstructor === Float32Array ? valueView : new UpdateViewConstructor(arrayBuffer);
            var image = new ImageAsset({
              width: width,
              height: height,
              _data: updateView,
              _compressed: false,
              format: pixelFormat
            });
            var textureAsset = new Texture2D();
            textureAsset.setFilters(Texture2D.Filter.NEAREST, Texture2D.Filter.NEAREST);
            textureAsset.setMipFilter(Texture2D.Filter.NONE);
            textureAsset.setWrapMode(Texture2D.WrapMode.CLAMP_TO_EDGE, Texture2D.WrapMode.CLAMP_TO_EDGE, Texture2D.WrapMode.CLAMP_TO_EDGE);
            textureAsset.image = image;
            if (!textureAsset.getGFXTexture()) {
              warn('Unexpected: failed to create morph texture?');
            }
            var sampler = gfxDevice.getSampler(textureAsset.getSamplerInfo());
            return {
              get texture() {
                return textureAsset.getGFXTexture();
              },
              get sampler() {
                return sampler;
              },
              get valueView() {
                return valueView;
              },
              destroy: function destroy() {
                textureAsset.destroy();
              },
              updatePixels: function updatePixels() {
                textureAsset.uploadData(updateView);
              }
            };
          }
        };
      }
      function enableVertexId(mesh, subMeshIndex, gfxDevice) {
        mesh.renderingSubMeshes[subMeshIndex].enableVertexIdChannel(gfxDevice);
      }
      function bestSizeToHavePixels(nPixels) {
        if (nPixels < 5) {
          nPixels = 5;
        }
        var aligned = nextPow2(nPixels);
        var epxSum = log2(aligned);
        var h = epxSum >> 1;
        var w = epxSum & 1 ? h + 1 : h;
        return {
          width: 1 << w,
          height: 1 << h
        };
      }

      function instantiateWasm(wasmUrl, importObject) {
        return fetchBuffer(wasmUrl).then(function (arrayBuffer) {
          return WebAssembly.instantiate(arrayBuffer, importObject);
        });
      }
      function fetchBuffer(binaryUrl) {
        return new Promise(function (resolve, reject) {
          try {
            if (EDITOR) ; else if (PREVIEW) ;
            binaryUrl = new URL(binaryUrl, module.meta.url).href;
            fetch(binaryUrl).then(function (response) {
              return response.arrayBuffer().then(resolve);
            })["catch"](function (e) {});
          } catch (e) {
            reject(e);
          }
        });
      }
      function ensureWasmModuleReady() {
        return Promise.resolve();
      }

      var MeshoptDecoder = {};
      function initDecoderASM(asm_factory) {
        return Promise.all([asm_factory.ready]).then(function () {
          MeshoptDecoder.supported = asm_factory.supported;
          MeshoptDecoder.ready = Promise.resolve();
          MeshoptDecoder.decodeVertexBuffer = asm_factory.decodeVertexBuffer;
          MeshoptDecoder.decodeIndexBuffer = asm_factory.decodeIndexBuffer;
          MeshoptDecoder.decodeIndexSequence = asm_factory.decodeIndexSequence;
          MeshoptDecoder.decodeGltfBuffer = asm_factory.decodeGltfBuffer;
          MeshoptDecoder.useWorkers = asm_factory.useWorkers;
          MeshoptDecoder.decodeGltfBufferAsync = asm_factory.decodeGltfBufferAsync;
          logID(14202);
        });
      }
      function initDecoderWASM(wasm_factory, wasm_url) {
        function instantiate(importObject) {
          return instantiateWasm(wasm_url, importObject);
        }
        return Promise.all([wasm_factory.ready(instantiate)]).then(function () {
          MeshoptDecoder.supported = wasm_factory.supported;
          MeshoptDecoder.ready = Promise.resolve();
          MeshoptDecoder.decodeVertexBuffer = wasm_factory.decodeVertexBuffer;
          MeshoptDecoder.decodeIndexBuffer = wasm_factory.decodeIndexBuffer;
          MeshoptDecoder.decodeIndexSequence = wasm_factory.decodeIndexSequence;
          MeshoptDecoder.decodeGltfBuffer = wasm_factory.decodeGltfBuffer;
          MeshoptDecoder.useWorkers = wasm_factory.useWorkers;
          MeshoptDecoder.decodeGltfBufferAsync = wasm_factory.decodeGltfBufferAsync;
          logID(14203);
        });
      }
      function shouldUseWasmModule() {
        {
          return sys.hasFeature(sys.Feature.WASM);
        }
      }
      function InitDecoder() {
        return ensureWasmModuleReady().then(function () {
          return Promise.all([module.import('./meshopt_decoder.asm-38d15b41.js'), module.import('./meshopt_decoder.wasm-ebbcb6df.js'), module.import('./meshopt_decoder.wasm-f85aad6b.js')]).then(function (_ref) {
            var meshopt_asm_factory = _ref[0]["default"],
              meshopt_wasm_factory = _ref[1]["default"],
              meshopt_wasm_url = _ref[2]["default"];
            if (shouldUseWasmModule()) {
              return initDecoderWASM(meshopt_wasm_factory, meshopt_wasm_url);
            } else {
              return initDecoderASM(meshopt_asm_factory);
            }
          });
        });
      }
      {
        game.onPostInfrastructureInitDelegate.add(InitDecoder);
      }

      /** @license zlib.js 2012 - imaya [ https://github.com/imaya/zlib.js ] The MIT License */
      var window$1 = {};
      (function () {

        function i(a) {
          throw a;
        }
        var r = void 0,
          v = !0,
          aa = this;
        function y(a, c) {
          var b = a.split("."),
            e = aa;
          !(b[0] in e) && e.execScript && e.execScript("var " + b[0]);
          for (var f; b.length && (f = b.shift());) !b.length && c !== r ? e[f] = c : e = e[f] ? e[f] : e[f] = {};
        }
        var H = "undefined" !== typeof Uint8Array && "undefined" !== typeof Uint16Array && "undefined" !== typeof Uint32Array;
        function ba(a) {
          if ("string" === typeof a) {
            var c = a.split(""),
              b,
              e;
            b = 0;
            for (e = c.length; b < e; b++) c[b] = (c[b].charCodeAt(0) & 255) >>> 0;
            a = c;
          }
          for (var f = 1, d = 0, g = a.length, h, m = 0; 0 < g;) {
            h = 1024 < g ? 1024 : g;
            g -= h;
            do f += a[m++], d += f; while (--h);
            f %= 65521;
            d %= 65521;
          }
          return (d << 16 | f) >>> 0;
        }
        function J(a, c) {
          this.index = "number" === typeof c ? c : 0;
          this.i = 0;
          this.buffer = a instanceof (H ? Uint8Array : Array) ? a : new (H ? Uint8Array : Array)(32768);
          2 * this.buffer.length <= this.index && i(Error("invalid index"));
          this.buffer.length <= this.index && this.f();
        }
        J.prototype.f = function () {
          var a = this.buffer,
            c,
            b = a.length,
            e = new (H ? Uint8Array : Array)(b << 1);
          if (H) e.set(a);else for (c = 0; c < b; ++c) e[c] = a[c];
          return this.buffer = e;
        };
        J.prototype.d = function (a, c, b) {
          var e = this.buffer,
            f = this.index,
            d = this.i,
            g = e[f],
            h;
          b && 1 < c && (a = 8 < c ? (N[a & 255] << 24 | N[a >>> 8 & 255] << 16 | N[a >>> 16 & 255] << 8 | N[a >>> 24 & 255]) >> 32 - c : N[a] >> 8 - c);
          if (8 > c + d) g = g << c | a, d += c;else for (h = 0; h < c; ++h) g = g << 1 | a >> c - h - 1 & 1, 8 === ++d && (d = 0, e[f++] = N[g], g = 0, f === e.length && (e = this.f()));
          e[f] = g;
          this.buffer = e;
          this.i = d;
          this.index = f;
        };
        J.prototype.finish = function () {
          var a = this.buffer,
            c = this.index,
            b;
          0 < this.i && (a[c] <<= 8 - this.i, a[c] = N[a[c]], c++);
          H ? b = a.subarray(0, c) : (a.length = c, b = a);
          return b;
        };
        var ca = new (H ? Uint8Array : Array)(256),
          ha;
        for (ha = 0; 256 > ha; ++ha) {
          for (var R = ha, ia = R, ja = 7, R = R >>> 1; R; R >>>= 1) ia <<= 1, ia |= R & 1, --ja;
          ca[ha] = (ia << ja & 255) >>> 0;
        }
        var N = ca;
        function la(a) {
          this.buffer = new (H ? Uint16Array : Array)(2 * a);
          this.length = 0;
        }
        la.prototype.getParent = function (a) {
          return 2 * ((a - 2) / 4 | 0);
        };
        la.prototype.push = function (a, c) {
          var b,
            e,
            f = this.buffer,
            d;
          b = this.length;
          f[this.length++] = c;
          for (f[this.length++] = a; 0 < b;) if (e = this.getParent(b), f[b] > f[e]) d = f[b], f[b] = f[e], f[e] = d, d = f[b + 1], f[b + 1] = f[e + 1], f[e + 1] = d, b = e;else break;
          return this.length;
        };
        la.prototype.pop = function () {
          var a,
            c,
            b = this.buffer,
            e,
            f,
            d;
          c = b[0];
          a = b[1];
          this.length -= 2;
          b[0] = b[this.length];
          b[1] = b[this.length + 1];
          for (d = 0;;) {
            f = 2 * d + 2;
            if (f >= this.length) break;
            f + 2 < this.length && b[f + 2] > b[f] && (f += 2);
            if (b[f] > b[d]) e = b[d], b[d] = b[f], b[f] = e, e = b[d + 1], b[d + 1] = b[f + 1], b[f + 1] = e;else break;
            d = f;
          }
          return {
            index: a,
            value: c,
            length: this.length
          };
        };
        function S(a) {
          var c = a.length,
            b = 0,
            e = Number.POSITIVE_INFINITY,
            f,
            d,
            g,
            h,
            m,
            j,
            s,
            n,
            l;
          for (n = 0; n < c; ++n) a[n] > b && (b = a[n]), a[n] < e && (e = a[n]);
          f = 1 << b;
          d = new (H ? Uint32Array : Array)(f);
          g = 1;
          h = 0;
          for (m = 2; g <= b;) {
            for (n = 0; n < c; ++n) if (a[n] === g) {
              j = 0;
              s = h;
              for (l = 0; l < g; ++l) j = j << 1 | s & 1, s >>= 1;
              for (l = j; l < f; l += m) d[l] = g << 16 | n;
              ++h;
            }
            ++g;
            h <<= 1;
            m <<= 1;
          }
          return [d, b, e];
        }
        function ma(a, c) {
          this.h = pa;
          this.w = 0;
          this.input = a;
          this.b = 0;
          c && (c.lazy && (this.w = c.lazy), "number" === typeof c.compressionType && (this.h = c.compressionType), c.outputBuffer && (this.a = H && c.outputBuffer instanceof Array ? new Uint8Array(c.outputBuffer) : c.outputBuffer), "number" === typeof c.outputIndex && (this.b = c.outputIndex));
          this.a || (this.a = new (H ? Uint8Array : Array)(32768));
        }
        var pa = 2,
          qa = {
            NONE: 0,
            r: 1,
            j: pa,
            N: 3
          },
          ra = [],
          T;
        for (T = 0; 288 > T; T++) switch (v) {
          case 143 >= T:
            ra.push([T + 48, 8]);
            break;
          case 255 >= T:
            ra.push([T - 144 + 400, 9]);
            break;
          case 279 >= T:
            ra.push([T - 256 + 0, 7]);
            break;
          case 287 >= T:
            ra.push([T - 280 + 192, 8]);
            break;
          default:
            i("invalid literal: " + T);
        }
        ma.prototype.n = function () {
          var a,
            c,
            b,
            e,
            f = this.input;
          switch (this.h) {
            case 0:
              b = 0;
              for (e = f.length; b < e;) {
                c = H ? f.subarray(b, b + 65535) : f.slice(b, b + 65535);
                b += c.length;
                var d = c,
                  g = b === e,
                  h = r,
                  m = r,
                  j = r,
                  s = r,
                  n = r,
                  l = this.a,
                  q = this.b;
                if (H) {
                  for (l = new Uint8Array(this.a.buffer); l.length <= q + d.length + 5;) l = new Uint8Array(l.length << 1);
                  l.set(this.a);
                }
                h = g ? 1 : 0;
                l[q++] = h | 0;
                m = d.length;
                j = ~m + 65536 & 65535;
                l[q++] = m & 255;
                l[q++] = m >>> 8 & 255;
                l[q++] = j & 255;
                l[q++] = j >>> 8 & 255;
                if (H) l.set(d, q), q += d.length, l = l.subarray(0, q);else {
                  s = 0;
                  for (n = d.length; s < n; ++s) l[q++] = d[s];
                  l.length = q;
                }
                this.b = q;
                this.a = l;
              }
              break;
            case 1:
              var E = new J(new Uint8Array(this.a.buffer), this.b);
              E.d(1, 1, v);
              E.d(1, 2, v);
              var t = sa(this, f),
                z,
                K,
                A;
              z = 0;
              for (K = t.length; z < K; z++) if (A = t[z], J.prototype.d.apply(E, ra[A]), 256 < A) E.d(t[++z], t[++z], v), E.d(t[++z], 5), E.d(t[++z], t[++z], v);else if (256 === A) break;
              this.a = E.finish();
              this.b = this.a.length;
              break;
            case pa:
              var x = new J(new Uint8Array(this.a), this.b),
                B,
                k,
                p,
                D,
                C,
                da = [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15],
                W,
                Ma,
                ea,
                Na,
                na,
                va = Array(19),
                Oa,
                $,
                oa,
                F,
                Pa;
              B = pa;
              x.d(1, 1, v);
              x.d(B, 2, v);
              k = sa(this, f);
              W = ta(this.L, 15);
              Ma = ua(W);
              ea = ta(this.K, 7);
              Na = ua(ea);
              for (p = 286; 257 < p && 0 === W[p - 1]; p--);
              for (D = 30; 1 < D && 0 === ea[D - 1]; D--);
              var Qa = p,
                Ra = D,
                M = new (H ? Uint32Array : Array)(Qa + Ra),
                u,
                O,
                w,
                fa,
                L = new (H ? Uint32Array : Array)(316),
                I,
                G,
                P = new (H ? Uint8Array : Array)(19);
              for (u = O = 0; u < Qa; u++) M[O++] = W[u];
              for (u = 0; u < Ra; u++) M[O++] = ea[u];
              if (!H) {
                u = 0;
                for (fa = P.length; u < fa; ++u) P[u] = 0;
              }
              u = I = 0;
              for (fa = M.length; u < fa; u += O) {
                for (O = 1; u + O < fa && M[u + O] === M[u]; ++O);
                w = O;
                if (0 === M[u]) {
                  if (3 > w) for (; 0 < w--;) L[I++] = 0, P[0]++;else for (; 0 < w;) G = 138 > w ? w : 138, G > w - 3 && G < w && (G = w - 3), 10 >= G ? (L[I++] = 17, L[I++] = G - 3, P[17]++) : (L[I++] = 18, L[I++] = G - 11, P[18]++), w -= G;
                } else if (L[I++] = M[u], P[M[u]]++, w--, 3 > w) for (; 0 < w--;) L[I++] = M[u], P[M[u]]++;else for (; 0 < w;) G = 6 > w ? w : 6, G > w - 3 && G < w && (G = w - 3), L[I++] = 16, L[I++] = G - 3, P[16]++, w -= G;
              }
              a = H ? L.subarray(0, I) : L.slice(0, I);
              na = ta(P, 7);
              for (F = 0; 19 > F; F++) va[F] = na[da[F]];
              for (C = 19; 4 < C && 0 === va[C - 1]; C--);
              Oa = ua(na);
              x.d(p - 257, 5, v);
              x.d(D - 1, 5, v);
              x.d(C - 4, 4, v);
              for (F = 0; F < C; F++) x.d(va[F], 3, v);
              F = 0;
              for (Pa = a.length; F < Pa; F++) if ($ = a[F], x.d(Oa[$], na[$], v), 16 <= $) {
                F++;
                switch ($) {
                  case 16:
                    oa = 2;
                    break;
                  case 17:
                    oa = 3;
                    break;
                  case 18:
                    oa = 7;
                    break;
                  default:
                    i("invalid code: " + $);
                }
                x.d(a[F], oa, v);
              }
              var Sa = [Ma, W],
                Ta = [Na, ea],
                Q,
                Ua,
                ga,
                ya,
                Va,
                Wa,
                Xa,
                Ya;
              Va = Sa[0];
              Wa = Sa[1];
              Xa = Ta[0];
              Ya = Ta[1];
              Q = 0;
              for (Ua = k.length; Q < Ua; ++Q) if (ga = k[Q], x.d(Va[ga], Wa[ga], v), 256 < ga) x.d(k[++Q], k[++Q], v), ya = k[++Q], x.d(Xa[ya], Ya[ya], v), x.d(k[++Q], k[++Q], v);else if (256 === ga) break;
              this.a = x.finish();
              this.b = this.a.length;
              break;
            default:
              i("invalid compression type");
          }
          return this.a;
        };
        function wa(a, c) {
          this.length = a;
          this.G = c;
        }
        function xa() {
          var a = za;
          switch (v) {
            case 3 === a:
              return [257, a - 3, 0];
            case 4 === a:
              return [258, a - 4, 0];
            case 5 === a:
              return [259, a - 5, 0];
            case 6 === a:
              return [260, a - 6, 0];
            case 7 === a:
              return [261, a - 7, 0];
            case 8 === a:
              return [262, a - 8, 0];
            case 9 === a:
              return [263, a - 9, 0];
            case 10 === a:
              return [264, a - 10, 0];
            case 12 >= a:
              return [265, a - 11, 1];
            case 14 >= a:
              return [266, a - 13, 1];
            case 16 >= a:
              return [267, a - 15, 1];
            case 18 >= a:
              return [268, a - 17, 1];
            case 22 >= a:
              return [269, a - 19, 2];
            case 26 >= a:
              return [270, a - 23, 2];
            case 30 >= a:
              return [271, a - 27, 2];
            case 34 >= a:
              return [272, a - 31, 2];
            case 42 >= a:
              return [273, a - 35, 3];
            case 50 >= a:
              return [274, a - 43, 3];
            case 58 >= a:
              return [275, a - 51, 3];
            case 66 >= a:
              return [276, a - 59, 3];
            case 82 >= a:
              return [277, a - 67, 4];
            case 98 >= a:
              return [278, a - 83, 4];
            case 114 >= a:
              return [279, a - 99, 4];
            case 130 >= a:
              return [280, a - 115, 4];
            case 162 >= a:
              return [281, a - 131, 5];
            case 194 >= a:
              return [282, a - 163, 5];
            case 226 >= a:
              return [283, a - 195, 5];
            case 257 >= a:
              return [284, a - 227, 5];
            case 258 === a:
              return [285, a - 258, 0];
            default:
              i("invalid length: " + a);
          }
        }
        var Aa = [],
          za,
          Ba;
        for (za = 3; 258 >= za; za++) Ba = xa(), Aa[za] = Ba[2] << 24 | Ba[1] << 16 | Ba[0];
        var Ca = H ? new Uint32Array(Aa) : Aa;
        function sa(a, c) {
          function b(a, c) {
            var b = a.G,
              d = [],
              e = 0,
              f;
            f = Ca[a.length];
            d[e++] = f & 65535;
            d[e++] = f >> 16 & 255;
            d[e++] = f >> 24;
            var g;
            switch (v) {
              case 1 === b:
                g = [0, b - 1, 0];
                break;
              case 2 === b:
                g = [1, b - 2, 0];
                break;
              case 3 === b:
                g = [2, b - 3, 0];
                break;
              case 4 === b:
                g = [3, b - 4, 0];
                break;
              case 6 >= b:
                g = [4, b - 5, 1];
                break;
              case 8 >= b:
                g = [5, b - 7, 1];
                break;
              case 12 >= b:
                g = [6, b - 9, 2];
                break;
              case 16 >= b:
                g = [7, b - 13, 2];
                break;
              case 24 >= b:
                g = [8, b - 17, 3];
                break;
              case 32 >= b:
                g = [9, b - 25, 3];
                break;
              case 48 >= b:
                g = [10, b - 33, 4];
                break;
              case 64 >= b:
                g = [11, b - 49, 4];
                break;
              case 96 >= b:
                g = [12, b - 65, 5];
                break;
              case 128 >= b:
                g = [13, b - 97, 5];
                break;
              case 192 >= b:
                g = [14, b - 129, 6];
                break;
              case 256 >= b:
                g = [15, b - 193, 6];
                break;
              case 384 >= b:
                g = [16, b - 257, 7];
                break;
              case 512 >= b:
                g = [17, b - 385, 7];
                break;
              case 768 >= b:
                g = [18, b - 513, 8];
                break;
              case 1024 >= b:
                g = [19, b - 769, 8];
                break;
              case 1536 >= b:
                g = [20, b - 1025, 9];
                break;
              case 2048 >= b:
                g = [21, b - 1537, 9];
                break;
              case 3072 >= b:
                g = [22, b - 2049, 10];
                break;
              case 4096 >= b:
                g = [23, b - 3073, 10];
                break;
              case 6144 >= b:
                g = [24, b - 4097, 11];
                break;
              case 8192 >= b:
                g = [25, b - 6145, 11];
                break;
              case 12288 >= b:
                g = [26, b - 8193, 12];
                break;
              case 16384 >= b:
                g = [27, b - 12289, 12];
                break;
              case 24576 >= b:
                g = [28, b - 16385, 13];
                break;
              case 32768 >= b:
                g = [29, b - 24577, 13];
                break;
              default:
                i("invalid distance");
            }
            f = g;
            d[e++] = f[0];
            d[e++] = f[1];
            d[e++] = f[2];
            var h, j;
            h = 0;
            for (j = d.length; h < j; ++h) l[q++] = d[h];
            t[d[0]]++;
            z[d[3]]++;
            E = a.length + c - 1;
            n = null;
          }
          var e,
            f,
            d,
            g,
            h,
            m = {},
            j,
            s,
            n,
            l = H ? new Uint16Array(2 * c.length) : [],
            q = 0,
            E = 0,
            t = new (H ? Uint32Array : Array)(286),
            z = new (H ? Uint32Array : Array)(30),
            K = a.w,
            A;
          if (!H) {
            for (d = 0; 285 >= d;) t[d++] = 0;
            for (d = 0; 29 >= d;) z[d++] = 0;
          }
          t[256] = 1;
          e = 0;
          for (f = c.length; e < f; ++e) {
            d = h = 0;
            for (g = 3; d < g && e + d !== f; ++d) h = h << 8 | c[e + d];
            m[h] === r && (m[h] = []);
            j = m[h];
            if (!(0 < E--)) {
              for (; 0 < j.length && 32768 < e - j[0];) j.shift();
              if (e + 3 >= f) {
                n && b(n, -1);
                d = 0;
                for (g = f - e; d < g; ++d) A = c[e + d], l[q++] = A, ++t[A];
                break;
              }
              if (0 < j.length) {
                var x = r,
                  B = r,
                  k = 0,
                  p = r,
                  D = r,
                  C = r,
                  da = r,
                  W = c.length,
                  D = 0,
                  da = j.length;
                a: for (; D < da; D++) {
                  x = j[da - D - 1];
                  p = 3;
                  if (3 < k) {
                    for (C = k; 3 < C; C--) if (c[x + C - 1] !== c[e + C - 1]) continue a;
                    p = k;
                  }
                  for (; 258 > p && e + p < W && c[x + p] === c[e + p];) ++p;
                  p > k && (B = x, k = p);
                  if (258 === p) break;
                }
                s = new wa(k, e - B);
                n ? n.length < s.length ? (A = c[e - 1], l[q++] = A, ++t[A], b(s, 0)) : b(n, -1) : s.length < K ? n = s : b(s, 0);
              } else n ? b(n, -1) : (A = c[e], l[q++] = A, ++t[A]);
            }
            j.push(e);
          }
          l[q++] = 256;
          t[256]++;
          a.L = t;
          a.K = z;
          return H ? l.subarray(0, q) : l;
        }
        function ta(a, c) {
          function b(a) {
            var c = z[a][K[a]];
            c === n ? (b(a + 1), b(a + 1)) : --E[c];
            ++K[a];
          }
          var e = a.length,
            f = new la(572),
            d = new (H ? Uint8Array : Array)(e),
            g,
            h,
            m,
            j,
            s;
          if (!H) for (j = 0; j < e; j++) d[j] = 0;
          for (j = 0; j < e; ++j) 0 < a[j] && f.push(j, a[j]);
          g = Array(f.length / 2);
          h = new (H ? Uint32Array : Array)(f.length / 2);
          if (1 === g.length) return d[f.pop().index] = 1, d;
          j = 0;
          for (s = f.length / 2; j < s; ++j) g[j] = f.pop(), h[j] = g[j].value;
          var n = h.length,
            l = new (H ? Uint16Array : Array)(c),
            q = new (H ? Uint8Array : Array)(c),
            E = new (H ? Uint8Array : Array)(n),
            t = Array(c),
            z = Array(c),
            K = Array(c),
            A = (1 << c) - n,
            x = 1 << c - 1,
            B,
            k,
            p,
            D,
            C;
          l[c - 1] = n;
          for (k = 0; k < c; ++k) A < x ? q[k] = 0 : (q[k] = 1, A -= x), A <<= 1, l[c - 2 - k] = (l[c - 1 - k] / 2 | 0) + n;
          l[0] = q[0];
          t[0] = Array(l[0]);
          z[0] = Array(l[0]);
          for (k = 1; k < c; ++k) l[k] > 2 * l[k - 1] + q[k] && (l[k] = 2 * l[k - 1] + q[k]), t[k] = Array(l[k]), z[k] = Array(l[k]);
          for (B = 0; B < n; ++B) E[B] = c;
          for (p = 0; p < l[c - 1]; ++p) t[c - 1][p] = h[p], z[c - 1][p] = p;
          for (B = 0; B < c; ++B) K[B] = 0;
          1 === q[c - 1] && (--E[0], ++K[c - 1]);
          for (k = c - 2; 0 <= k; --k) {
            D = B = 0;
            C = K[k + 1];
            for (p = 0; p < l[k]; p++) D = t[k + 1][C] + t[k + 1][C + 1], D > h[B] ? (t[k][p] = D, z[k][p] = n, C += 2) : (t[k][p] = h[B], z[k][p] = B, ++B);
            K[k] = 0;
            1 === q[k] && b(k);
          }
          m = E;
          j = 0;
          for (s = g.length; j < s; ++j) d[g[j].index] = m[j];
          return d;
        }
        function ua(a) {
          var c = new (H ? Uint16Array : Array)(a.length),
            b = [],
            e = [],
            f = 0,
            d,
            g,
            h,
            m;
          d = 0;
          for (g = a.length; d < g; d++) b[a[d]] = (b[a[d]] | 0) + 1;
          d = 1;
          for (g = 16; d <= g; d++) e[d] = f, f += b[d] | 0, f > 1 << d && i("overcommitted"), f <<= 1;
          65536 > f && i("undercommitted");
          d = 0;
          for (g = a.length; d < g; d++) {
            f = e[a[d]];
            e[a[d]] += 1;
            h = c[d] = 0;
            for (m = a[d]; h < m; h++) c[d] = c[d] << 1 | f & 1, f >>>= 1;
          }
          return c;
        }
        function Da(a, c) {
          this.input = a;
          this.a = new (H ? Uint8Array : Array)(32768);
          this.h = U.j;
          var b = {},
            e;
          if ((c || !(c = {})) && "number" === typeof c.compressionType) this.h = c.compressionType;
          for (e in c) b[e] = c[e];
          b.outputBuffer = this.a;
          this.z = new ma(this.input, b);
        }
        var U = qa;
        Da.prototype.n = function () {
          var a,
            c,
            b,
            e,
            f,
            d,
            g,
            h = 0;
          g = this.a;
          a = Ea;
          switch (a) {
            case Ea:
              c = Math.LOG2E * Math.log(32768) - 8;
              break;
            default:
              i(Error("invalid compression method"));
          }
          b = c << 4 | a;
          g[h++] = b;
          switch (a) {
            case Ea:
              switch (this.h) {
                case U.NONE:
                  f = 0;
                  break;
                case U.r:
                  f = 1;
                  break;
                case U.j:
                  f = 2;
                  break;
                default:
                  i(Error("unsupported compression type"));
              }
              break;
            default:
              i(Error("invalid compression method"));
          }
          e = f << 6 | 0;
          g[h++] = e | 31 - (256 * b + e) % 31;
          d = ba(this.input);
          this.z.b = h;
          g = this.z.n();
          h = g.length;
          H && (g = new Uint8Array(g.buffer), g.length <= h + 4 && (this.a = new Uint8Array(g.length + 4), this.a.set(g), g = this.a), g = g.subarray(0, h + 4));
          g[h++] = d >> 24 & 255;
          g[h++] = d >> 16 & 255;
          g[h++] = d >> 8 & 255;
          g[h++] = d & 255;
          return g;
        };
        y("Zlib.Deflate", Da);
        y("Zlib.Deflate.compress", function (a, c) {
          return new Da(a, c).n();
        });
        y("Zlib.Deflate.CompressionType", U);
        y("Zlib.Deflate.CompressionType.NONE", U.NONE);
        y("Zlib.Deflate.CompressionType.FIXED", U.r);
        y("Zlib.Deflate.CompressionType.DYNAMIC", U.j);
        function V(a, c) {
          this.k = [];
          this.l = 32768;
          this.e = this.g = this.c = this.q = 0;
          this.input = H ? new Uint8Array(a) : a;
          this.s = !1;
          this.m = Fa;
          this.B = !1;
          if (c || !(c = {})) c.index && (this.c = c.index), c.bufferSize && (this.l = c.bufferSize), c.bufferType && (this.m = c.bufferType), c.resize && (this.B = c.resize);
          switch (this.m) {
            case Ga:
              this.b = 32768;
              this.a = new (H ? Uint8Array : Array)(32768 + this.l + 258);
              break;
            case Fa:
              this.b = 0;
              this.a = new (H ? Uint8Array : Array)(this.l);
              this.f = this.J;
              this.t = this.H;
              this.o = this.I;
              break;
            default:
              i(Error("invalid inflate mode"));
          }
        }
        var Ga = 0,
          Fa = 1,
          Ha = {
            D: Ga,
            C: Fa
          };
        V.prototype.p = function () {
          for (; !this.s;) {
            var a = X(this, 3);
            a & 1 && (this.s = v);
            a >>>= 1;
            switch (a) {
              case 0:
                var c = this.input,
                  b = this.c,
                  e = this.a,
                  f = this.b,
                  d = r,
                  g = r,
                  h = r,
                  m = e.length,
                  j = r;
                this.e = this.g = 0;
                d = c[b++];
                d === r && i(Error("invalid uncompressed block header: LEN (first byte)"));
                g = d;
                d = c[b++];
                d === r && i(Error("invalid uncompressed block header: LEN (second byte)"));
                g |= d << 8;
                d = c[b++];
                d === r && i(Error("invalid uncompressed block header: NLEN (first byte)"));
                h = d;
                d = c[b++];
                d === r && i(Error("invalid uncompressed block header: NLEN (second byte)"));
                h |= d << 8;
                g === ~h && i(Error("invalid uncompressed block header: length verify"));
                b + g > c.length && i(Error("input buffer is broken"));
                switch (this.m) {
                  case Ga:
                    for (; f + g > e.length;) {
                      j = m - f;
                      g -= j;
                      if (H) e.set(c.subarray(b, b + j), f), f += j, b += j;else for (; j--;) e[f++] = c[b++];
                      this.b = f;
                      e = this.f();
                      f = this.b;
                    }
                    break;
                  case Fa:
                    for (; f + g > e.length;) e = this.f({
                      v: 2
                    });
                    break;
                  default:
                    i(Error("invalid inflate mode"));
                }
                if (H) e.set(c.subarray(b, b + g), f), f += g, b += g;else for (; g--;) e[f++] = c[b++];
                this.c = b;
                this.b = f;
                this.a = e;
                break;
              case 1:
                this.o(Ia, Ja);
                break;
              case 2:
                Ka(this);
                break;
              default:
                i(Error("unknown BTYPE: " + a));
            }
          }
          return this.t();
        };
        var La = [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15],
          Za = H ? new Uint16Array(La) : La,
          $a = [3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 258, 258],
          ab = H ? new Uint16Array($a) : $a,
          bb = [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, 0, 0],
          cb = H ? new Uint8Array(bb) : bb,
          db = [1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577],
          eb = H ? new Uint16Array(db) : db,
          fb = [0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13],
          gb = H ? new Uint8Array(fb) : fb,
          hb = new (H ? Uint8Array : Array)(288),
          Y,
          ib;
        Y = 0;
        for (ib = hb.length; Y < ib; ++Y) hb[Y] = 143 >= Y ? 8 : 255 >= Y ? 9 : 279 >= Y ? 7 : 8;
        var Ia = S(hb),
          jb = new (H ? Uint8Array : Array)(30),
          kb,
          lb;
        kb = 0;
        for (lb = jb.length; kb < lb; ++kb) jb[kb] = 5;
        var Ja = S(jb);
        function X(a, c) {
          for (var b = a.g, e = a.e, f = a.input, d = a.c, g; e < c;) g = f[d++], g === r && i(Error("input buffer is broken")), b |= g << e, e += 8;
          g = b & (1 << c) - 1;
          a.g = b >>> c;
          a.e = e - c;
          a.c = d;
          return g;
        }
        function mb(a, c) {
          for (var b = a.g, e = a.e, f = a.input, d = a.c, g = c[0], h = c[1], m, j, s; e < h;) m = f[d++], m === r && i(Error("input buffer is broken")), b |= m << e, e += 8;
          j = g[b & (1 << h) - 1];
          s = j >>> 16;
          a.g = b >> s;
          a.e = e - s;
          a.c = d;
          return j & 65535;
        }
        function Ka(a) {
          function c(a, b, c) {
            var d, e, f, g;
            for (g = 0; g < a;) switch (d = mb(this, b), d) {
              case 16:
                for (f = 3 + X(this, 2); f--;) c[g++] = e;
                break;
              case 17:
                for (f = 3 + X(this, 3); f--;) c[g++] = 0;
                e = 0;
                break;
              case 18:
                for (f = 11 + X(this, 7); f--;) c[g++] = 0;
                e = 0;
                break;
              default:
                e = c[g++] = d;
            }
            return c;
          }
          var b = X(a, 5) + 257,
            e = X(a, 5) + 1,
            f = X(a, 4) + 4,
            d = new (H ? Uint8Array : Array)(Za.length),
            g,
            h,
            m,
            j;
          for (j = 0; j < f; ++j) d[Za[j]] = X(a, 3);
          g = S(d);
          h = new (H ? Uint8Array : Array)(b);
          m = new (H ? Uint8Array : Array)(e);
          a.o(S(c.call(a, b, g, h)), S(c.call(a, e, g, m)));
        }
        V.prototype.o = function (a, c) {
          var b = this.a,
            e = this.b;
          this.u = a;
          for (var f = b.length - 258, d, g, h, m; 256 !== (d = mb(this, a));) if (256 > d) e >= f && (this.b = e, b = this.f(), e = this.b), b[e++] = d;else {
            g = d - 257;
            m = ab[g];
            0 < cb[g] && (m += X(this, cb[g]));
            d = mb(this, c);
            h = eb[d];
            0 < gb[d] && (h += X(this, gb[d]));
            e >= f && (this.b = e, b = this.f(), e = this.b);
            for (; m--;) b[e] = b[e++ - h];
          }
          for (; 8 <= this.e;) this.e -= 8, this.c--;
          this.b = e;
        };
        V.prototype.I = function (a, c) {
          var b = this.a,
            e = this.b;
          this.u = a;
          for (var f = b.length, d, g, h, m; 256 !== (d = mb(this, a));) if (256 > d) e >= f && (b = this.f(), f = b.length), b[e++] = d;else {
            g = d - 257;
            m = ab[g];
            0 < cb[g] && (m += X(this, cb[g]));
            d = mb(this, c);
            h = eb[d];
            0 < gb[d] && (h += X(this, gb[d]));
            e + m > f && (b = this.f(), f = b.length);
            for (; m--;) b[e] = b[e++ - h];
          }
          for (; 8 <= this.e;) this.e -= 8, this.c--;
          this.b = e;
        };
        V.prototype.f = function () {
          var a = new (H ? Uint8Array : Array)(this.b - 32768),
            c = this.b - 32768,
            b,
            e,
            f = this.a;
          if (H) a.set(f.subarray(32768, a.length));else {
            b = 0;
            for (e = a.length; b < e; ++b) a[b] = f[b + 32768];
          }
          this.k.push(a);
          this.q += a.length;
          if (H) f.set(f.subarray(c, c + 32768));else for (b = 0; 32768 > b; ++b) f[b] = f[c + b];
          this.b = 32768;
          return f;
        };
        V.prototype.J = function (a) {
          var c,
            b = this.input.length / this.c + 1 | 0,
            e,
            f,
            d,
            g = this.input,
            h = this.a;
          a && ("number" === typeof a.v && (b = a.v), "number" === typeof a.F && (b += a.F));
          2 > b ? (e = (g.length - this.c) / this.u[2], d = 258 * (e / 2) | 0, f = d < h.length ? h.length + d : h.length << 1) : f = h.length * b;
          H ? (c = new Uint8Array(f), c.set(h)) : c = h;
          return this.a = c;
        };
        V.prototype.t = function () {
          var a = 0,
            c = this.a,
            b = this.k,
            e,
            f = new (H ? Uint8Array : Array)(this.q + (this.b - 32768)),
            d,
            g,
            h,
            m;
          if (0 === b.length) return H ? this.a.subarray(32768, this.b) : this.a.slice(32768, this.b);
          d = 0;
          for (g = b.length; d < g; ++d) {
            e = b[d];
            h = 0;
            for (m = e.length; h < m; ++h) f[a++] = e[h];
          }
          d = 32768;
          for (g = this.b; d < g; ++d) f[a++] = c[d];
          this.k = [];
          return this.buffer = f;
        };
        V.prototype.H = function () {
          var a,
            c = this.b;
          H ? this.B ? (a = new Uint8Array(c), a.set(this.a.subarray(0, c))) : a = this.a.subarray(0, c) : (this.a.length > c && (this.a.length = c), a = this.a);
          return this.buffer = a;
        };
        function nb(a, c) {
          var b, e;
          this.input = a;
          this.c = 0;
          if (c || !(c = {})) c.index && (this.c = c.index), c.verify && (this.M = c.verify);
          b = a[this.c++];
          e = a[this.c++];
          switch (b & 15) {
            case Ea:
              this.method = Ea;
              break;
            default:
              i(Error("unsupported compression method"));
          }
          0 !== ((b << 8) + e) % 31 && i(Error("invalid fcheck flag:" + ((b << 8) + e) % 31));
          e & 32 && i(Error("fdict flag is not supported"));
          this.A = new V(a, {
            index: this.c,
            bufferSize: c.bufferSize,
            bufferType: c.bufferType,
            resize: c.resize
          });
        }
        nb.prototype.p = function () {
          var a = this.input,
            c,
            b;
          c = this.A.p();
          this.c = this.A.c;
          this.M && (b = (a[this.c++] << 24 | a[this.c++] << 16 | a[this.c++] << 8 | a[this.c++]) >>> 0, b !== ba(c) && i(Error("invalid adler-32 checksum")));
          return c;
        };
        y("Zlib.Inflate", nb);
        y("Zlib.Inflate.BufferType", Ha);
        Ha.ADAPTIVE = Ha.C;
        Ha.BLOCK = Ha.D;
        y("Zlib.Inflate.prototype.decompress", nb.prototype.p);
        var tb = new (H ? Uint8Array : Array)(288),
          Z,
          ub;
        Z = 0;
        for (ub = tb.length; Z < ub; ++Z) tb[Z] = 143 >= Z ? 8 : 255 >= Z ? 9 : 279 >= Z ? 7 : 8;
        S(tb);
        var vb = new (H ? Uint8Array : Array)(30),
          wb,
          xb;
        wb = 0;
        for (xb = vb.length; wb < xb; ++wb) vb[wb] = 5;
        S(vb);
        var Ea = 8;
      }).call(window$1);
      var _p = window$1.Zlib;
      _p.Deflate = _p["Deflate"];
      _p.Deflate.compress = _p.Deflate["compress"];
      _p.Inflate = _p["Inflate"];
      _p.Inflate.BufferType = _p.Inflate["BufferType"];
      _p.Inflate.prototype.decompress = _p.Inflate.prototype["decompress"];

      var _dec$2r, _class$2p, _class2$29, _initializer$1_, _initializer2$1A, _initializer3$13;
      function getIndexStrideCtor(stride) {
        switch (stride) {
          case 1:
            return Uint8Array;
          case 2:
            return Uint16Array;
          case 4:
            return Uint32Array;
          default:
            return Uint8Array;
        }
      }
      var v3_1$4 = new Vec3();
      var v3_2$1 = new Vec3();
      var globalEmptyMeshBuffer = new Uint8Array();
      var Mesh = exports('a1', (_dec$2r = ccclass$n('cc.Mesh'), _dec$2r(_class$2p = (_class2$29 = function (_Asset) {
        _inheritsLoose(Mesh, _Asset);
        function Mesh() {
          var _this;
          _this = _Asset.call(this) || this;
          _this.morphRendering = null;
          _this._struct = _initializer$1_ && _initializer$1_();
          _this._hash = _initializer2$1A && _initializer2$1A();
          _this._data = globalEmptyMeshBuffer;
          _this._initialized = false;
          _this._allowDataAccess = _initializer3$13 && _initializer3$13();
          _this._isMeshDataUploaded = false;
          _this._renderingSubMeshes = null;
          _this._boneSpaceBounds = new Map();
          _this._jointBufferIndices = null;
          return _this;
        }
        var _proto = Mesh.prototype;
        _proto.onLoaded = function onLoaded() {
          this.initialize();
        };
        _proto.initialize = function initialize() {
          if (this._initialized) {
            return;
          }
          this._initialized = true;
          var info = {
            struct: this.struct,
            data: this.data
          };
          if (info.struct.compressed) {
            info = inflateMesh(info);
          }
          if (this.struct.encoded) {
            info = decodeMesh(info);
          }
          if (this.struct.quantized && !(deviceManager.gfxDevice.getFormatFeatures(Format.RGB16F) & FormatFeatureBit.VERTEX_ATTRIBUTE)) {
            info = dequantizeMesh(info);
          }
          this._struct = info.struct;
          this._data = info.data;
          if (this._struct.dynamic) {
            var device = deviceManager.gfxDevice;
            var vertexBuffers = [];
            var subMeshes = [];
            for (var i = 0; i < this._struct.vertexBundles.length; i++) {
              var _vertexBundle = this._struct.vertexBundles[i];
              var vertexBuffer = device.createBuffer(new BufferInfo(BufferUsageBit.VERTEX | BufferUsageBit.TRANSFER_DST, MemoryUsageBit.DEVICE, _vertexBundle.view.length, _vertexBundle.view.stride));
              vertexBuffers.push(vertexBuffer);
            }
            for (var _i = 0; _i < this._struct.primitives.length; _i++) {
              var primitive = this._struct.primitives[_i];
              var indexView = primitive.indexView;
              var indexBuffer = null;
              if (indexView) {
                indexBuffer = device.createBuffer(new BufferInfo(BufferUsageBit.INDEX | BufferUsageBit.TRANSFER_DST, MemoryUsageBit.DEVICE, indexView.length, indexView.stride));
              }
              var subVBs = [];
              for (var k = 0; k < primitive.vertexBundelIndices.length; k++) {
                var idx = primitive.vertexBundelIndices[k];
                subVBs.push(vertexBuffers[idx]);
              }
              var attributes = [];
              for (var _k = 0; _k < primitive.vertexBundelIndices.length; _k++) {
                var _idx = primitive.vertexBundelIndices[_k];
                var _vertexBundle2 = this._struct.vertexBundles[_idx];
                for (var _iterator = _createForOfIteratorHelperLoose(_vertexBundle2.attributes), _step; !(_step = _iterator()).done;) {
                  var attr = _step.value;
                  var attribute = new Attribute();
                  attribute.copy(attr);
                  attributes.push(attribute);
                }
              }
              var subMesh = new RenderingSubMesh(subVBs, attributes, primitive.primitiveMode, indexBuffer);
              subMesh.drawInfo = new DrawInfo();
              subMesh.mesh = this;
              subMesh.subMeshIdx = _i;
              subMeshes.push(subMesh);
            }
            this._renderingSubMeshes = subMeshes;
          } else {
            var buffer = this._data.buffer;
            var gfxDevice = deviceManager.gfxDevice;
            var _vertexBuffers = this._createVertexBuffers(gfxDevice, buffer);
            var indexBuffers = [];
            var _subMeshes = [];
            for (var _i2 = 0; _i2 < this._struct.primitives.length; _i2++) {
              var prim = this._struct.primitives[_i2];
              if (prim.vertexBundelIndices.length === 0) {
                continue;
              }
              var _indexBuffer = null;
              var ib = void 0;
              if (prim.indexView) {
                var idxView = prim.indexView;
                var dstStride = idxView.stride;
                var dstSize = idxView.length;
                if (dstStride === 4 && !gfxDevice.hasFeature(Feature.ELEMENT_INDEX_UINT)) {
                  var vertexCount = this._struct.vertexBundles[prim.vertexBundelIndices[0]].view.count;
                  if (vertexCount >= 65536) {
                    warnID(10001, vertexCount, 65536);
                    continue;
                  } else {
                    dstStride >>= 1;
                    dstSize >>= 1;
                  }
                }
                _indexBuffer = gfxDevice.createBuffer(new BufferInfo(BufferUsageBit.INDEX, MemoryUsageBit.DEVICE, dstSize, dstStride));
                indexBuffers.push(_indexBuffer);
                ib = new (getIndexStrideCtor(idxView.stride))(buffer, idxView.offset, idxView.count);
                if (idxView.stride !== dstStride) {
                  ib = getIndexStrideCtor(dstStride).from(ib);
                }
                _indexBuffer.update(ib);
              }
              var vbReference = prim.vertexBundelIndices.map(function (idx) {
                return _vertexBuffers[idx];
              });
              var gfxAttributes = [];
              if (prim.vertexBundelIndices.length > 0) {
                var _idx2 = prim.vertexBundelIndices[0];
                var _vertexBundle3 = this._struct.vertexBundles[_idx2];
                var attrs = _vertexBundle3.attributes;
                for (var j = 0; j < attrs.length; ++j) {
                  var _attr = attrs[j];
                  gfxAttributes[j] = new Attribute(_attr.name, _attr.format, _attr.isNormalized, _attr.stream, _attr.isInstanced, _attr.location);
                }
              }
              var _subMesh = new RenderingSubMesh(vbReference, gfxAttributes, prim.primitiveMode, _indexBuffer);
              _subMesh.mesh = this;
              _subMesh.subMeshIdx = _i2;
              _subMeshes.push(_subMesh);
            }
            this._renderingSubMeshes = _subMeshes;
            if (this._struct.morph) {
              this.morphRendering = createMorphRendering(this, gfxDevice);
            }
            this._isMeshDataUploaded = true;
            if (!this._allowDataAccess && !EDITOR) {
              this.releaseData();
            }
          }
        };
        _proto.updateSubMesh = function updateSubMesh(primitiveIndex, dynamicGeometry) {
          if (!this._struct.dynamic) {
            warnID(14200);
            return;
          }
          if (primitiveIndex >= this._struct.primitives.length) {
            warnID(14201);
            return;
          }
          var buffers = [];
          if (dynamicGeometry.positions.length > 0) {
            buffers.push(dynamicGeometry.positions);
          }
          if (dynamicGeometry.normals && dynamicGeometry.normals.length > 0) {
            buffers.push(dynamicGeometry.normals);
          }
          if (dynamicGeometry.uvs && dynamicGeometry.uvs.length > 0) {
            buffers.push(dynamicGeometry.uvs);
          }
          if (dynamicGeometry.tangents && dynamicGeometry.tangents.length > 0) {
            buffers.push(dynamicGeometry.tangents);
          }
          if (dynamicGeometry.colors && dynamicGeometry.colors.length > 0) {
            buffers.push(dynamicGeometry.colors);
          }
          if (dynamicGeometry.customAttributes) {
            for (var k = 0; k < dynamicGeometry.customAttributes.length; k++) {
              buffers.push(dynamicGeometry.customAttributes[k].values);
            }
          }
          var dynamic = this._struct.dynamic;
          var info = dynamic.info;
          var primitive = this._struct.primitives[primitiveIndex];
          var subMesh = this._renderingSubMeshes[primitiveIndex];
          var drawInfo = subMesh.drawInfo;
          for (var index = 0; index < buffers.length; index++) {
            var vertices = buffers[index];
            var bundle = this._struct.vertexBundles[primitive.vertexBundelIndices[index]];
            var stride = bundle.view.stride;
            var vertexCount = vertices.byteLength / stride;
            var updateSize = vertices.byteLength;
            var dstBuffer = new Uint8Array(this._data.buffer, bundle.view.offset, updateSize);
            var srcBuffer = new Uint8Array(vertices.buffer, vertices.byteOffset, updateSize);
            var vertexBuffer = subMesh.vertexBuffers[index];
            assertIsTrue(vertexCount <= info.maxSubMeshVertices, 'Too many vertices.');
            if (updateSize > 0) {
              dstBuffer.set(srcBuffer);
              vertexBuffer.update(srcBuffer, updateSize);
            }
            bundle.view.count = vertexCount;
            drawInfo.vertexCount = vertexCount;
          }
          if (primitive.indexView) {
            var indexView = primitive.indexView;
            var _stride = indexView.stride;
            var indexCount = _stride === 2 ? dynamicGeometry.indices16.length : dynamicGeometry.indices32.length;
            var _updateSize = indexCount * _stride;
            var _dstBuffer = new Uint8Array(this._data.buffer, indexView.offset, _updateSize);
            var _srcBuffer = _stride === 2 ? new Uint8Array(dynamicGeometry.indices16.buffer, dynamicGeometry.indices16.byteOffset, _updateSize) : new Uint8Array(dynamicGeometry.indices32.buffer, dynamicGeometry.indices32.byteOffset, _updateSize);
            var indexBuffer = subMesh.indexBuffer;
            assertIsTrue(indexCount <= info.maxSubMeshIndices, 'Too many indices.');
            if (_updateSize > 0) {
              _dstBuffer.set(_srcBuffer);
              indexBuffer.update(_srcBuffer, _updateSize);
            }
            indexView.count = indexCount;
            drawInfo.indexCount = indexCount;
          }
          if (dynamicGeometry.minPos && dynamicGeometry.maxPos) {
            var minPos = new Vec3(dynamicGeometry.minPos.x, dynamicGeometry.minPos.y, dynamicGeometry.minPos.z);
            var maxPos = new Vec3(dynamicGeometry.maxPos.x, dynamicGeometry.maxPos.y, dynamicGeometry.maxPos.z);
            if (!dynamic.bounds[primitiveIndex]) {
              dynamic.bounds[primitiveIndex] = new AABB();
            }
            AABB.fromPoints(dynamic.bounds[primitiveIndex], minPos, maxPos);
            var subMin = new Vec3();
            var subMax = new Vec3();
            for (var _iterator2 = _createForOfIteratorHelperLoose(dynamic.bounds), _step2; !(_step2 = _iterator2()).done;) {
              var bound = _step2.value;
              if (bound) {
                bound.getBoundary(subMin, subMax);
                Vec3.min(minPos, subMin, minPos);
                Vec3.max(maxPos, subMax, maxPos);
              }
            }
            this._struct.minPosition = new Vec3(minPos.x, minPos.y, minPos.z);
            this._struct.maxPosition = new Vec3(maxPos.x, maxPos.y, maxPos.z);
          }
          subMesh.invalidateGeometricInfo();
        };
        _proto.destroy = function destroy() {
          this.destroyRenderingMesh();
          return _Asset.prototype.destroy.call(this);
        };
        _proto.destroyRenderingMesh = function destroyRenderingMesh() {
          if (this._renderingSubMeshes) {
            for (var i = 0; i < this._renderingSubMeshes.length; i++) {
              this._renderingSubMeshes[i].destroy();
            }
            this._renderingSubMeshes = null;
            this._initialized = false;
            this._isMeshDataUploaded = false;
          }
        };
        _proto.assign = function assign(struct, data) {
          this.reset({
            struct: struct,
            data: data
          });
        };
        _proto.reset = function reset(info) {
          this.destroyRenderingMesh();
          this._struct = info.struct;
          this._data = info.data;
          this._hash = 0;
        };
        _proto.getBoneSpaceBounds = function getBoneSpaceBounds(skeleton) {
          if (this._boneSpaceBounds.has(skeleton.hash)) {
            return this._boneSpaceBounds.get(skeleton.hash);
          }
          var bounds = [];
          this._boneSpaceBounds.set(skeleton.hash, bounds);
          var valid = [];
          var bindposes = skeleton.bindposes;
          for (var i = 0; i < bindposes.length; i++) {
            bounds.push(new AABB(Infinity, Infinity, Infinity, -Infinity, -Infinity, -Infinity));
            valid.push(false);
          }
          var primitives = this._struct.primitives;
          for (var p = 0; p < primitives.length; p++) {
            var joints = this.readAttribute(p, AttributeName.ATTR_JOINTS);
            var weights = this.readAttribute(p, AttributeName.ATTR_WEIGHTS);
            var positions = this.readAttribute(p, AttributeName.ATTR_POSITION);
            if (!joints || !weights || !positions) {
              continue;
            }
            var vertCount = Math.min(joints.length / 4, weights.length / 4, positions.length / 3);
            for (var _i3 = 0; _i3 < vertCount; _i3++) {
              Vec3.set(v3_1$4, positions[3 * _i3 + 0], positions[3 * _i3 + 1], positions[3 * _i3 + 2]);
              for (var j = 0; j < 4; ++j) {
                var idx = 4 * _i3 + j;
                var joint = joints[idx];
                if (weights[idx] === 0 || joint >= bindposes.length) {
                  continue;
                }
                Vec3.transformMat4(v3_2$1, v3_1$4, bindposes[joint]);
                valid[joint] = true;
                var b = bounds[joint];
                Vec3.min(b.center, b.center, v3_2$1);
                Vec3.max(b.halfExtents, b.halfExtents, v3_2$1);
              }
            }
          }
          for (var _i4 = 0; _i4 < bindposes.length; _i4++) {
            var _b = bounds[_i4];
            if (!valid[_i4]) {
              bounds[_i4] = null;
            } else {
              AABB.fromPoints(_b, _b.center, _b.halfExtents);
            }
          }
          return bounds;
        };
        _proto.merge = function merge(mesh, worldMatrix, validate) {
          if (validate) {
            if (!this.validateMergingMesh(mesh)) {
              return false;
            }
          }
          var vec3_temp = new Vec3();
          var rotate = worldMatrix && new Quat();
          var boundingBox = worldMatrix && new AABB();
          if (rotate) {
            worldMatrix.getRotation(rotate);
          }
          if (!this._initialized) {
            var struct = JSON.parse(JSON.stringify(mesh._struct));
            var data = mesh._data.slice();
            if (worldMatrix) {
              if (struct.maxPosition && struct.minPosition) {
                Vec3.add(boundingBox.center, struct.maxPosition, struct.minPosition);
                Vec3.multiplyScalar(boundingBox.center, boundingBox.center, 0.5);
                Vec3.subtract(boundingBox.halfExtents, struct.maxPosition, struct.minPosition);
                Vec3.multiplyScalar(boundingBox.halfExtents, boundingBox.halfExtents, 0.5);
                AABB.transform(boundingBox, boundingBox, worldMatrix);
                Vec3.add(struct.maxPosition, boundingBox.center, boundingBox.halfExtents);
                Vec3.subtract(struct.minPosition, boundingBox.center, boundingBox.halfExtents);
              }
              for (var i = 0; i < struct.vertexBundles.length; i++) {
                var vtxBdl = struct.vertexBundles[i];
                for (var j = 0; j < vtxBdl.attributes.length; j++) {
                  if (vtxBdl.attributes[j].name === AttributeName.ATTR_POSITION || vtxBdl.attributes[j].name === AttributeName.ATTR_NORMAL) {
                    var format = vtxBdl.attributes[j].format;
                    var inputView = new DataView(data.buffer, vtxBdl.view.offset + getOffset(vtxBdl.attributes, j));
                    var reader = getReader(inputView, format);
                    var writer = getWriter(inputView, format);
                    if (!reader || !writer) {
                      continue;
                    }
                    var vertexCount = vtxBdl.view.count;
                    var vertexStride = vtxBdl.view.stride;
                    var attrComponentByteLength = getComponentByteLength(format);
                    for (var vtxIdx = 0; vtxIdx < vertexCount; vtxIdx++) {
                      var xOffset = vtxIdx * vertexStride;
                      var yOffset = xOffset + attrComponentByteLength;
                      var zOffset = yOffset + attrComponentByteLength;
                      vec3_temp.set(reader(xOffset), reader(yOffset), reader(zOffset));
                      switch (vtxBdl.attributes[j].name) {
                        case AttributeName.ATTR_POSITION:
                          vec3_temp.transformMat4(worldMatrix);
                          break;
                        case AttributeName.ATTR_NORMAL:
                          Vec3.transformQuat(vec3_temp, vec3_temp, rotate);
                          break;
                      }
                      writer(xOffset, vec3_temp.x);
                      writer(yOffset, vec3_temp.y);
                      writer(zOffset, vec3_temp.z);
                    }
                  }
                }
              }
            }
            this.reset({
              struct: struct,
              data: data
            });
            this.initialize();
            return true;
          }
          var bufferBlob = new BufferBlob();
          var vertCount = 0;
          var vertStride = 0;
          var srcOffset = 0;
          var dstOffset = 0;
          var vb;
          var vbView;
          var srcVBView;
          var dstVBView;
          var srcAttrOffset = 0;
          var srcVBOffset = 0;
          var dstVBOffset = 0;
          var attrSize = 0;
          var dstAttrView;
          var hasAttr = false;
          var vertexBundles = new Array(this._struct.vertexBundles.length);
          for (var _i5 = 0; _i5 < this._struct.vertexBundles.length; ++_i5) {
            var bundle = this._struct.vertexBundles[_i5];
            var dstBundle = mesh._struct.vertexBundles[_i5];
            srcOffset = bundle.view.offset;
            dstOffset = dstBundle.view.offset;
            vertStride = bundle.view.stride;
            vertCount = bundle.view.count + dstBundle.view.count;
            vb = new ArrayBuffer(vertCount * vertStride);
            vbView = new Uint8Array(vb);
            srcVBView = this._data.subarray(srcOffset, srcOffset + bundle.view.length);
            srcOffset += srcVBView.length;
            dstVBView = mesh._data.subarray(dstOffset, dstOffset + dstBundle.view.length);
            dstOffset += dstVBView.length;
            vbView.set(srcVBView);
            srcAttrOffset = 0;
            for (var _iterator3 = _createForOfIteratorHelperLoose(bundle.attributes), _step3; !(_step3 = _iterator3()).done;) {
              var attr = _step3.value;
              dstVBOffset = 0;
              hasAttr = false;
              for (var _iterator4 = _createForOfIteratorHelperLoose(dstBundle.attributes), _step4; !(_step4 = _iterator4()).done;) {
                var dstAttr = _step4.value;
                if (attr.name === dstAttr.name && attr.format === dstAttr.format) {
                  hasAttr = true;
                  break;
                }
                dstVBOffset += FormatInfos[dstAttr.format].size;
              }
              if (hasAttr) {
                attrSize = FormatInfos[attr.format].size;
                srcVBOffset = bundle.view.length + srcAttrOffset;
                for (var v = 0; v < dstBundle.view.count; ++v) {
                  dstAttrView = dstVBView.subarray(dstVBOffset, dstVBOffset + attrSize);
                  vbView.set(dstAttrView, srcVBOffset);
                  if ((attr.name === AttributeName.ATTR_POSITION || attr.name === AttributeName.ATTR_NORMAL) && worldMatrix) {
                    var f32_temp = new Float32Array(vbView.buffer, srcVBOffset, 3);
                    vec3_temp.set(f32_temp[0], f32_temp[1], f32_temp[2]);
                    switch (attr.name) {
                      case AttributeName.ATTR_POSITION:
                        vec3_temp.transformMat4(worldMatrix);
                        break;
                      case AttributeName.ATTR_NORMAL:
                        Vec3.transformQuat(vec3_temp, vec3_temp, rotate);
                        break;
                    }
                    f32_temp[0] = vec3_temp.x;
                    f32_temp[1] = vec3_temp.y;
                    f32_temp[2] = vec3_temp.z;
                  }
                  srcVBOffset += bundle.view.stride;
                  dstVBOffset += dstBundle.view.stride;
                }
              }
              srcAttrOffset += FormatInfos[attr.format].size;
            }
            vertexBundles[_i5] = {
              attributes: bundle.attributes,
              view: {
                offset: bufferBlob.getLength(),
                length: vb.byteLength,
                count: vertCount,
                stride: vertStride
              }
            };
            bufferBlob.addBuffer(vb);
          }
          var idxCount = 0;
          var idxStride = 2;
          var ibView;
          var srcIBView;
          var dstIBView;
          var primitives = new Array(this._struct.primitives.length);
          for (var _i6 = 0; _i6 < this._struct.primitives.length; ++_i6) {
            var prim = this._struct.primitives[_i6];
            var dstPrim = mesh._struct.primitives[_i6];
            primitives[_i6] = {
              primitiveMode: prim.primitiveMode,
              vertexBundelIndices: prim.vertexBundelIndices
            };
            var vertBatchCount = 0;
            for (var _iterator5 = _createForOfIteratorHelperLoose(prim.vertexBundelIndices), _step5; !(_step5 = _iterator5()).done;) {
              var bundleIdx = _step5.value;
              vertBatchCount = Math.max(vertBatchCount, this._struct.vertexBundles[bundleIdx].view.count);
            }
            if (prim.indexView && dstPrim.indexView) {
              idxCount = prim.indexView.count;
              idxCount += dstPrim.indexView.count;
              srcOffset = prim.indexView.offset;
              dstOffset = dstPrim.indexView.offset;
              if (idxCount < 256) {
                idxStride = 1;
              } else if (idxCount < 65536) {
                idxStride = 2;
              } else {
                idxStride = 4;
              }
              var ib = new ArrayBuffer(idxCount * idxStride);
              if (idxStride === 2) {
                ibView = new Uint16Array(ib);
              } else if (idxStride === 1) {
                ibView = new Uint8Array(ib);
              } else {
                ibView = new Uint32Array(ib);
              }
              if (prim.indexView.stride === 2) {
                srcIBView = new Uint16Array(this._data.buffer, srcOffset, prim.indexView.count);
              } else if (prim.indexView.stride === 1) {
                srcIBView = new Uint8Array(this._data.buffer, srcOffset, prim.indexView.count);
              } else {
                srcIBView = new Uint32Array(this._data.buffer, srcOffset, prim.indexView.count);
              }
              if (idxStride === prim.indexView.stride) {
                ibView.set(srcIBView);
              } else {
                for (var n = 0; n < prim.indexView.count; ++n) {
                  ibView[n] = srcIBView[n];
                }
              }
              srcOffset += prim.indexView.length;
              if (dstPrim.indexView.stride === 2) {
                dstIBView = new Uint16Array(mesh._data.buffer, dstOffset, dstPrim.indexView.count);
              } else if (dstPrim.indexView.stride === 1) {
                dstIBView = new Uint8Array(mesh._data.buffer, dstOffset, dstPrim.indexView.count);
              } else {
                dstIBView = new Uint32Array(mesh._data.buffer, dstOffset, dstPrim.indexView.count);
              }
              for (var _n = 0; _n < dstPrim.indexView.count; ++_n) {
                ibView[prim.indexView.count + _n] = vertBatchCount + dstIBView[_n];
              }
              dstOffset += dstPrim.indexView.length;
              primitives[_i6].indexView = {
                offset: bufferBlob.getLength(),
                length: ib.byteLength,
                count: idxCount,
                stride: idxStride
              };
              bufferBlob.setNextAlignment(idxStride);
              bufferBlob.addBuffer(ib);
            }
          }
          var meshStruct = {
            vertexBundles: vertexBundles,
            primitives: primitives,
            minPosition: this._struct.minPosition,
            maxPosition: this._struct.maxPosition
          };
          if (meshStruct.minPosition && mesh._struct.minPosition && meshStruct.maxPosition && mesh._struct.maxPosition) {
            if (worldMatrix) {
              Vec3.add(boundingBox.center, mesh._struct.maxPosition, mesh._struct.minPosition);
              Vec3.multiplyScalar(boundingBox.center, boundingBox.center, 0.5);
              Vec3.subtract(boundingBox.halfExtents, mesh._struct.maxPosition, mesh._struct.minPosition);
              Vec3.multiplyScalar(boundingBox.halfExtents, boundingBox.halfExtents, 0.5);
              AABB.transform(boundingBox, boundingBox, worldMatrix);
              Vec3.add(vec3_temp, boundingBox.center, boundingBox.halfExtents);
              Vec3.max(meshStruct.maxPosition, meshStruct.maxPosition, vec3_temp);
              Vec3.subtract(vec3_temp, boundingBox.center, boundingBox.halfExtents);
              Vec3.min(meshStruct.minPosition, meshStruct.minPosition, vec3_temp);
            } else {
              Vec3.min(meshStruct.minPosition, meshStruct.minPosition, mesh._struct.minPosition);
              Vec3.max(meshStruct.maxPosition, meshStruct.maxPosition, mesh._struct.maxPosition);
            }
          }
          this.reset({
            struct: meshStruct,
            data: new Uint8Array(bufferBlob.getCombined())
          });
          this.initialize();
          return true;
        };
        _proto.validateMergingMesh = function validateMergingMesh(mesh) {
          if (this._struct.dynamic || mesh._struct.dynamic) {
            return false;
          }
          if (this._struct.vertexBundles.length !== mesh._struct.vertexBundles.length) {
            return false;
          }
          for (var i = 0; i < this._struct.vertexBundles.length; ++i) {
            var bundle = this._struct.vertexBundles[i];
            var dstBundle = mesh._struct.vertexBundles[i];
            if (bundle.attributes.length !== dstBundle.attributes.length) {
              return false;
            }
            for (var j = 0; j < bundle.attributes.length; ++j) {
              if (bundle.attributes[j].format !== dstBundle.attributes[j].format) {
                return false;
              }
            }
          }
          if (this._struct.primitives.length !== mesh._struct.primitives.length) {
            return false;
          }
          for (var _i7 = 0; _i7 < this._struct.primitives.length; ++_i7) {
            var prim = this._struct.primitives[_i7];
            var dstPrim = mesh._struct.primitives[_i7];
            if (prim.vertexBundelIndices.length !== dstPrim.vertexBundelIndices.length) {
              return false;
            }
            for (var _j = 0; _j < prim.vertexBundelIndices.length; ++_j) {
              if (prim.vertexBundelIndices[_j] !== dstPrim.vertexBundelIndices[_j]) {
                return false;
              }
            }
            if (prim.primitiveMode !== dstPrim.primitiveMode) {
              return false;
            }
            if (prim.indexView) {
              if (dstPrim.indexView === undefined) {
                return false;
              }
            } else if (dstPrim.indexView) {
              return false;
            }
          }
          return true;
        };
        _proto.readAttribute = function readAttribute(primitiveIndex, attributeName) {
          var _this2 = this;
          var result = null;
          this._accessAttribute(primitiveIndex, attributeName, function (vertexBundle, iAttribute) {
            var vertexCount = vertexBundle.view.count;
            var format = vertexBundle.attributes[iAttribute].format;
            var StorageConstructor = getTypedArrayConstructor(FormatInfos[format]);
            if (vertexCount === 0) {
              return;
            }
            var inputView = new DataView(_this2._data.buffer, vertexBundle.view.offset + getOffset(vertexBundle.attributes, iAttribute));
            var formatInfo = FormatInfos[format];
            var reader = getReader(inputView, format);
            if (!StorageConstructor || !reader) {
              return;
            }
            var componentCount = formatInfo.count;
            var storage = new StorageConstructor(vertexCount * componentCount);
            var inputStride = vertexBundle.view.stride;
            for (var iVertex = 0; iVertex < vertexCount; ++iVertex) {
              for (var iComponent = 0; iComponent < componentCount; ++iComponent) {
                storage[componentCount * iVertex + iComponent] = reader(inputStride * iVertex + storage.BYTES_PER_ELEMENT * iComponent);
              }
            }
            result = storage;
          });
          return result;
        };
        _proto.copyAttribute = function copyAttribute(primitiveIndex, attributeName, buffer, stride, offset) {
          var _this3 = this;
          var written = false;
          this._accessAttribute(primitiveIndex, attributeName, function (vertexBundle, iAttribute) {
            var vertexCount = vertexBundle.view.count;
            if (vertexCount === 0) {
              written = true;
              return;
            }
            var format = vertexBundle.attributes[iAttribute].format;
            var inputView = new DataView(_this3._data.buffer, vertexBundle.view.offset + getOffset(vertexBundle.attributes, iAttribute));
            var outputView = new DataView(buffer, offset);
            var formatInfo = FormatInfos[format];
            var reader = getReader(inputView, format);
            var writer = getWriter(outputView, format);
            if (!reader || !writer) {
              return;
            }
            var componentCount = formatInfo.count;
            var inputStride = vertexBundle.view.stride;
            var inputComponentByteLength = getComponentByteLength(format);
            var outputStride = stride;
            var outputComponentByteLength = inputComponentByteLength;
            for (var iVertex = 0; iVertex < vertexCount; ++iVertex) {
              for (var iComponent = 0; iComponent < componentCount; ++iComponent) {
                var inputOffset = inputStride * iVertex + inputComponentByteLength * iComponent;
                var outputOffset = outputStride * iVertex + outputComponentByteLength * iComponent;
                writer(outputOffset, reader(inputOffset));
              }
            }
            written = true;
          });
          return written;
        };
        _proto.readIndices = function readIndices(primitiveIndex) {
          if (primitiveIndex >= this._struct.primitives.length) {
            return null;
          }
          var primitive = this._struct.primitives[primitiveIndex];
          if (!primitive.indexView) {
            return null;
          }
          var stride = primitive.indexView.stride;
          var Ctor = stride === 1 ? Uint8Array : stride === 2 ? Uint16Array : Uint32Array;
          return new Ctor(this._data.buffer, primitive.indexView.offset, primitive.indexView.count);
        };
        _proto.copyIndices = function copyIndices(primitiveIndex, outputArray) {
          if (primitiveIndex >= this._struct.primitives.length) {
            return false;
          }
          var primitive = this._struct.primitives[primitiveIndex];
          if (!primitive.indexView) {
            return false;
          }
          var indexCount = primitive.indexView.count;
          var indexFormat = primitive.indexView.stride === 1 ? Format.R8UI : primitive.indexView.stride === 2 ? Format.R16UI : Format.R32UI;
          var reader = getReader(new DataView(this._data.buffer), indexFormat);
          for (var i = 0; i < indexCount; ++i) {
            outputArray[i] = reader(primitive.indexView.offset + FormatInfos[indexFormat].size * i);
          }
          return true;
        };
        _proto.readAttributeFormat = function readAttributeFormat(primitiveIndex, attributeName) {
          var result = null;
          this._accessAttribute(primitiveIndex, attributeName, function (vertexBundle, iAttribute) {
            var format = vertexBundle.attributes[iAttribute].format;
            result = FormatInfos[format];
          });
          return result;
        };
        _proto._accessAttribute = function _accessAttribute(primitiveIndex, attributeName, accessor) {
          if (primitiveIndex >= this._struct.primitives.length) {
            return;
          }
          var primitive = this._struct.primitives[primitiveIndex];
          for (var _iterator6 = _createForOfIteratorHelperLoose(primitive.vertexBundelIndices), _step6; !(_step6 = _iterator6()).done;) {
            var vertexBundleIndex = _step6.value;
            var _vertexBundle4 = this._struct.vertexBundles[vertexBundleIndex];
            var _iAttribute = _vertexBundle4.attributes.findIndex(function (a) {
              return a.name === attributeName;
            });
            if (_iAttribute < 0) {
              continue;
            }
            accessor(_vertexBundle4, _iAttribute);
            break;
          }
        };
        _proto._createVertexBuffers = function _createVertexBuffers(gfxDevice, data) {
          return this._struct.vertexBundles.map(function (vertexBundle) {
            var vertexBuffer = gfxDevice.createBuffer(new BufferInfo(BufferUsageBit.VERTEX, MemoryUsageBit.DEVICE, vertexBundle.view.length, vertexBundle.view.stride));
            var view = new Uint8Array(data, vertexBundle.view.offset, vertexBundle.view.length);
            vertexBuffer.update(view);
            return vertexBuffer;
          });
        };
        _proto.initDefault = function initDefault(uuid) {
          _Asset.prototype.initDefault.call(this, uuid);
          this.reset({
            struct: {
              vertexBundles: [],
              primitives: []
            },
            data: globalEmptyMeshBuffer
          });
        };
        _proto.releaseData = function releaseData() {
          this._data = globalEmptyMeshBuffer;
        };
        _createClass(Mesh, [{
          key: "_nativeAsset",
          get: function get() {
            return this._data.buffer;
          },
          set: function set(value) {
            this._data = new Uint8Array(value);
          }
        }, {
          key: "subMeshCount",
          get: function get() {
            var renderingMesh = this.renderingSubMeshes;
            return renderingMesh ? renderingMesh.length : 0;
          }
        }, {
          key: "minPosition",
          get: function get() {
            return this.struct.minPosition;
          }
        }, {
          key: "maxPosition",
          get: function get() {
            return this.struct.maxPosition;
          }
        }, {
          key: "struct",
          get: function get() {
            return this._struct;
          }
        }, {
          key: "data",
          get: function get() {
            return this._data;
          }
        }, {
          key: "hash",
          get: function get() {
            if (!this._hash) {
              this._hash = murmurhash2_32_gc(this._data, 666);
            }
            return this._hash;
          }
        }, {
          key: "jointBufferIndices",
          get: function get() {
            if (this._jointBufferIndices) {
              return this._jointBufferIndices;
            }
            return this._jointBufferIndices = this._struct.primitives.map(function (p) {
              return p.jointMapIndex || 0;
            });
          }
        }, {
          key: "renderingSubMeshes",
          get: function get() {
            this.initialize();
            return this._renderingSubMeshes;
          }
        }, {
          key: "allowDataAccess",
          get: function get() {
            return this._allowDataAccess;
          },
          set: function set(allowDataAccess) {
            this._allowDataAccess = allowDataAccess;
            if (this._isMeshDataUploaded && !this._allowDataAccess && !EDITOR) {
              this.releaseData();
            }
          }
        }]);
        return Mesh;
      }(Asset), (_initializer$1_ = applyDecoratedInitializer(_class2$29.prototype, "_struct", [serializable$j], function () {
        return {
          vertexBundles: [],
          primitives: []
        };
      }), _initializer2$1A = applyDecoratedInitializer(_class2$29.prototype, "_hash", [serializable$j], function () {
        return 0;
      }), _initializer3$13 = applyDecoratedInitializer(_class2$29.prototype, "_allowDataAccess", [serializable$j], function () {
        return true;
      })), _class2$29)) || _class$2p));
      legacyCC.Mesh = Mesh;
      function getOffset(attributes, attributeIndex) {
        var result = 0;
        for (var i = 0; i < attributeIndex; ++i) {
          var attribute = attributes[i];
          result += FormatInfos[attribute.format].size;
        }
        return result;
      }
      var isLittleEndian = sys.isLittleEndian;
      function getComponentByteLength(format) {
        var info = FormatInfos[format];
        return info.size / info.count;
      }
      function getReader(dataView, format) {
        var info = FormatInfos[format];
        var stride = info.size / info.count;
        switch (info.type) {
          case FormatType.UNORM:
            {
              switch (stride) {
                case 1:
                  return function (offset) {
                    return dataView.getUint8(offset);
                  };
                case 2:
                  return function (offset) {
                    return dataView.getUint16(offset, isLittleEndian);
                  };
                case 4:
                  return function (offset) {
                    return dataView.getUint32(offset, isLittleEndian);
                  };
              }
              break;
            }
          case FormatType.SNORM:
            {
              switch (stride) {
                case 1:
                  return function (offset) {
                    return dataView.getInt8(offset);
                  };
                case 2:
                  return function (offset) {
                    return dataView.getInt16(offset, isLittleEndian);
                  };
                case 4:
                  return function (offset) {
                    return dataView.getInt32(offset, isLittleEndian);
                  };
              }
              break;
            }
          case FormatType.INT:
            {
              switch (stride) {
                case 1:
                  return function (offset) {
                    return dataView.getInt8(offset);
                  };
                case 2:
                  return function (offset) {
                    return dataView.getInt16(offset, isLittleEndian);
                  };
                case 4:
                  return function (offset) {
                    return dataView.getInt32(offset, isLittleEndian);
                  };
              }
              break;
            }
          case FormatType.UINT:
            {
              switch (stride) {
                case 1:
                  return function (offset) {
                    return dataView.getUint8(offset);
                  };
                case 2:
                  return function (offset) {
                    return dataView.getUint16(offset, isLittleEndian);
                  };
                case 4:
                  return function (offset) {
                    return dataView.getUint32(offset, isLittleEndian);
                  };
              }
              break;
            }
          case FormatType.FLOAT:
            {
              switch (stride) {
                case 2:
                  return function (offset) {
                    return dataView.getUint16(offset, isLittleEndian);
                  };
                case 4:
                  return function (offset) {
                    return dataView.getFloat32(offset, isLittleEndian);
                  };
              }
              break;
            }
        }
        return null;
      }
      function getWriter(dataView, format) {
        var info = FormatInfos[format];
        var stride = info.size / info.count;
        switch (info.type) {
          case FormatType.UNORM:
            {
              switch (stride) {
                case 1:
                  return function (offset, value) {
                    return dataView.setUint8(offset, value);
                  };
                case 2:
                  return function (offset, value) {
                    return dataView.setUint16(offset, value, isLittleEndian);
                  };
                case 4:
                  return function (offset, value) {
                    return dataView.setUint32(offset, value, isLittleEndian);
                  };
              }
              break;
            }
          case FormatType.SNORM:
            {
              switch (stride) {
                case 1:
                  return function (offset, value) {
                    return dataView.setInt8(offset, value);
                  };
                case 2:
                  return function (offset, value) {
                    return dataView.setInt16(offset, value, isLittleEndian);
                  };
                case 4:
                  return function (offset, value) {
                    return dataView.setInt32(offset, value, isLittleEndian);
                  };
              }
              break;
            }
          case FormatType.INT:
            {
              switch (stride) {
                case 1:
                  return function (offset, value) {
                    return dataView.setInt8(offset, value);
                  };
                case 2:
                  return function (offset, value) {
                    return dataView.setInt16(offset, value, isLittleEndian);
                  };
                case 4:
                  return function (offset, value) {
                    return dataView.setInt32(offset, value, isLittleEndian);
                  };
              }
              break;
            }
          case FormatType.UINT:
            {
              switch (stride) {
                case 1:
                  return function (offset, value) {
                    return dataView.setUint8(offset, value);
                  };
                case 2:
                  return function (offset, value) {
                    return dataView.setUint16(offset, value, isLittleEndian);
                  };
                case 4:
                  return function (offset, value) {
                    return dataView.setUint32(offset, value, isLittleEndian);
                  };
              }
              break;
            }
          case FormatType.FLOAT:
            {
              switch (stride) {
                case 2:
                  return function (offset, value) {
                    return dataView.setUint16(offset, value, isLittleEndian);
                  };
                case 4:
                  return function (offset, value) {
                    return dataView.setFloat32(offset, value, isLittleEndian);
                  };
              }
              break;
            }
        }
        return null;
      }
      function decodeMesh(mesh) {
        if (!mesh.struct.encoded) {
          return mesh;
        }
        var res_checker = function res_checker(res) {
          if (res < 0) {
            errorID(14204, res);
          }
        };
        var struct = JSON.parse(JSON.stringify(mesh.struct));
        var bufferBlob = new BufferBlob();
        bufferBlob.setNextAlignment(0);
        for (var _iterator7 = _createForOfIteratorHelperLoose(struct.vertexBundles), _step7; !(_step7 = _iterator7()).done;) {
          var bundle = _step7.value;
          var view = bundle.view;
          var bound = view.count * view.stride;
          var buffer = new Uint8Array(bound);
          var vertex = new Uint8Array(mesh.data.buffer, view.offset, view.length);
          var res = MeshoptDecoder.decodeVertexBuffer(buffer, view.count, view.stride, vertex);
          res_checker(res);
          bufferBlob.setNextAlignment(view.stride);
          var newView = {
            offset: bufferBlob.getLength(),
            length: buffer.byteLength,
            count: view.count,
            stride: view.stride
          };
          bundle.view = newView;
          bufferBlob.addBuffer(buffer);
        }
        for (var _iterator8 = _createForOfIteratorHelperLoose(struct.primitives), _step8; !(_step8 = _iterator8()).done;) {
          var primitive = _step8.value;
          if (primitive.indexView === undefined) {
            continue;
          }
          var _view = primitive.indexView;
          var _bound = _view.count * _view.stride;
          var _buffer = new Uint8Array(_bound);
          var index = new Uint8Array(mesh.data.buffer, _view.offset, _view.length);
          var _res = MeshoptDecoder.decodeIndexBuffer(_buffer, _view.count, _view.stride, index);
          res_checker(_res);
          bufferBlob.setNextAlignment(_view.stride);
          var _newView = {
            offset: bufferBlob.getLength(),
            length: _buffer.byteLength,
            count: _view.count,
            stride: _view.stride
          };
          primitive.indexView = _newView;
          bufferBlob.addBuffer(_buffer);
        }
        var data = new Uint8Array(bufferBlob.getCombined());
        return {
          struct: struct,
          data: data
        };
      }
      function inflateMesh(mesh) {
        var inflator = new _p.Inflate(mesh.data);
        var decompressed = inflator.decompress();
        mesh.data = decompressed;
        mesh.struct.compressed = false;
        return mesh;
      }
      function dequantizeMesh(mesh) {
        var struct = JSON.parse(JSON.stringify(mesh.struct));
        var bufferBlob = new BufferBlob();
        bufferBlob.setNextAlignment(0);
        function transformVertex(reader, writer, count, components, componentSize, readerStride, writerStride) {
          for (var i = 0; i < count; i++) {
            for (var j = 0; j < components; j++) {
              var inputOffset = readerStride * i + componentSize * j;
              var outputOffset = writerStride * i + componentSize * j;
              writer(outputOffset, reader(inputOffset));
            }
          }
        }
        function dequantizeHalf(reader, writer, count, components, readerStride, writerStride) {
          for (var i = 0; i < count; i++) {
            for (var j = 0; j < components; j++) {
              var inputOffset = readerStride * i + 2 * j;
              var outputOffset = writerStride * i + 4 * j;
              var _value = halfToFloat(reader(inputOffset));
              writer(outputOffset, _value);
            }
          }
        }
        for (var i = 0; i < struct.vertexBundles.length; ++i) {
          var bundle = struct.vertexBundles[i];
          var view = bundle.view;
          var attributes = bundle.attributes;
          var oldAttributes = mesh.struct.vertexBundles[i].attributes;
          var strides = [];
          var dequantizes = [];
          var readers = [];
          for (var j = 0; j < attributes.length; ++j) {
            var attr = attributes[j];
            var inputView = new DataView(mesh.data.buffer, view.offset + getOffset(oldAttributes, j));
            var reader = getReader(inputView, attr.format);
            var dequantize = true;
            switch (attr.format) {
              case Format.R16F:
                attr.format = Format.R32F;
                break;
              case Format.RG16F:
                attr.format = Format.RG32F;
                break;
              case Format.RGB16F:
                attr.format = Format.RGB32F;
                break;
              case Format.RGBA16F:
                attr.format = Format.RGBA32F;
                break;
              default:
                dequantize = false;
                break;
            }
            strides.push(FormatInfos[attr.format].size);
            dequantizes.push(dequantize);
            readers.push(reader);
          }
          var netStride = strides.reduce(function (acc, cur) {
            return acc + cur;
          }, 0);
          var newBuffer = new Uint8Array(netStride * view.count);
          for (var _j2 = 0; _j2 < attributes.length; ++_j2) {
            var attribute = attributes[_j2];
            var _reader = readers[_j2];
            var outputView = new DataView(newBuffer.buffer, getOffset(attributes, _j2));
            var writer = getWriter(outputView, attribute.format);
            var _dequantize = dequantizes[_j2];
            var formatInfo = FormatInfos[attribute.format];
            if (_dequantize) {
              dequantizeHalf(_reader, writer, view.count, formatInfo.count, view.stride, netStride);
            } else {
              transformVertex(_reader, writer, view.count, formatInfo.count, formatInfo.size / formatInfo.count, view.stride, netStride);
            }
          }
          bufferBlob.setNextAlignment(netStride);
          var newView = {
            offset: bufferBlob.getLength(),
            length: newBuffer.byteLength,
            count: view.count,
            stride: netStride
          };
          bundle.view = newView;
          bufferBlob.addBuffer(newBuffer);
        }
        for (var _iterator9 = _createForOfIteratorHelperLoose(struct.primitives), _step9; !(_step9 = _iterator9()).done;) {
          var primitive = _step9.value;
          if (primitive.indexView === undefined) {
            continue;
          }
          var _view2 = primitive.indexView;
          var buffer = new Uint8Array(mesh.data.buffer, _view2.offset, _view2.length);
          bufferBlob.setNextAlignment(_view2.stride);
          var _newView2 = {
            offset: bufferBlob.getLength(),
            length: buffer.byteLength,
            count: _view2.count,
            stride: _view2.stride
          };
          primitive.indexView = _newView2;
          bufferBlob.addBuffer(buffer);
        }
        var data = new Uint8Array(bufferBlob.getCombined());
        struct.quantized = false;
        return {
          struct: struct,
          data: data
        };
      }

      var _defAttrs = [new Attribute(AttributeName.ATTR_POSITION, Format.RGB32F), new Attribute(AttributeName.ATTR_NORMAL, Format.RGB32F), new Attribute(AttributeName.ATTR_TEX_COORD, Format.RG32F), new Attribute(AttributeName.ATTR_TANGENT, Format.RGBA32F), new Attribute(AttributeName.ATTR_COLOR, Format.RGBA32F)];
      var v3_1$3 = new Vec3();
      function _createMesh(geometry, out, options) {
        options = options || {};
        var attributes = [];
        var stride = 0;
        var channels = [];
        var vertCount = 0;
        var attr;
        var positions = geometry.positions.slice();
        if (positions.length > 0) {
          attr = null;
          if (geometry.attributes) {
            for (var _iterator = _createForOfIteratorHelperLoose(geometry.attributes), _step; !(_step = _iterator()).done;) {
              var att = _step.value;
              if (att.name === AttributeName.ATTR_POSITION) {
                attr = att;
                break;
              }
            }
          }
          if (!attr) {
            attr = _defAttrs[0];
          }
          attributes.push(attr);
          var info = FormatInfos[attr.format];
          vertCount = Math.max(vertCount, Math.floor(positions.length / info.count));
          channels.push({
            offset: stride,
            data: positions,
            attribute: attr
          });
          stride += info.size;
        }
        if (geometry.normals && geometry.normals.length > 0) {
          attr = null;
          if (geometry.attributes) {
            for (var _iterator2 = _createForOfIteratorHelperLoose(geometry.attributes), _step2; !(_step2 = _iterator2()).done;) {
              var _att = _step2.value;
              if (_att.name === AttributeName.ATTR_NORMAL) {
                attr = _att;
                break;
              }
            }
          }
          if (!attr) {
            attr = _defAttrs[1];
          }
          var _info = FormatInfos[attr.format];
          attributes.push(attr);
          vertCount = Math.max(vertCount, Math.floor(geometry.normals.length / _info.count));
          channels.push({
            offset: stride,
            data: geometry.normals,
            attribute: attr
          });
          stride += _info.size;
        }
        if (geometry.uvs && geometry.uvs.length > 0) {
          attr = null;
          if (geometry.attributes) {
            for (var _iterator3 = _createForOfIteratorHelperLoose(geometry.attributes), _step3; !(_step3 = _iterator3()).done;) {
              var _att2 = _step3.value;
              if (_att2.name === AttributeName.ATTR_TEX_COORD) {
                attr = _att2;
                break;
              }
            }
          }
          if (!attr) {
            attr = _defAttrs[2];
          }
          var _info2 = FormatInfos[attr.format];
          attributes.push(attr);
          vertCount = Math.max(vertCount, Math.floor(geometry.uvs.length / _info2.count));
          channels.push({
            offset: stride,
            data: geometry.uvs,
            attribute: attr
          });
          stride += _info2.size;
        }
        if (geometry.tangents && geometry.tangents.length > 0) {
          attr = null;
          if (geometry.attributes) {
            for (var _iterator4 = _createForOfIteratorHelperLoose(geometry.attributes), _step4; !(_step4 = _iterator4()).done;) {
              var _att3 = _step4.value;
              if (_att3.name === AttributeName.ATTR_TANGENT) {
                attr = _att3;
                break;
              }
            }
          }
          if (!attr) {
            attr = _defAttrs[3];
          }
          var _info3 = FormatInfos[attr.format];
          attributes.push(attr);
          vertCount = Math.max(vertCount, Math.floor(geometry.tangents.length / _info3.count));
          channels.push({
            offset: stride,
            data: geometry.tangents,
            attribute: attr
          });
          stride += _info3.size;
        }
        if (geometry.colors && geometry.colors.length > 0) {
          attr = null;
          if (geometry.attributes) {
            for (var _iterator5 = _createForOfIteratorHelperLoose(geometry.attributes), _step5; !(_step5 = _iterator5()).done;) {
              var _att4 = _step5.value;
              if (_att4.name === AttributeName.ATTR_COLOR) {
                attr = _att4;
                break;
              }
            }
          }
          if (!attr) {
            attr = _defAttrs[4];
          }
          var _info4 = FormatInfos[attr.format];
          attributes.push(attr);
          vertCount = Math.max(vertCount, Math.floor(geometry.colors.length / _info4.count));
          channels.push({
            offset: stride,
            data: geometry.colors,
            attribute: attr
          });
          stride += _info4.size;
        }
        if (geometry.customAttributes) {
          for (var k = 0; k < geometry.customAttributes.length; k++) {
            var ca = geometry.customAttributes[k];
            var _info5 = FormatInfos[ca.attr.format];
            attributes.push(ca.attr);
            vertCount = Math.max(vertCount, Math.floor(ca.values.length / _info5.count));
            channels.push({
              offset: stride,
              data: ca.values,
              attribute: ca.attr
            });
            stride += _info5.size;
          }
        }
        var bufferBlob = new BufferBlob();
        var vertexBuffer = new ArrayBuffer(vertCount * stride);
        var vertexBufferView = new DataView(vertexBuffer);
        for (var _i = 0, _channels = channels; _i < _channels.length; _i++) {
          var channel = _channels[_i];
          writeBuffer(vertexBufferView, channel.data, channel.attribute.format, channel.offset, stride);
        }
        bufferBlob.setNextAlignment(0);
        var vertexBundle = {
          attributes: attributes,
          view: {
            offset: bufferBlob.getLength(),
            length: vertexBuffer.byteLength,
            count: vertCount,
            stride: stride
          }
        };
        bufferBlob.addBuffer(vertexBuffer);
        var indexBuffer = null;
        var idxCount = 0;
        var idxStride = 2;
        if (geometry.indices) {
          var indices = geometry.indices;
          idxCount = indices.length;
          indexBuffer = new ArrayBuffer(idxStride * idxCount);
          var indexBufferView = new DataView(indexBuffer);
          writeBuffer(indexBufferView, indices, Format.R16UI);
        }
        var primitive = {
          primitiveMode: geometry.primitiveMode || PrimitiveMode.TRIANGLE_LIST,
          vertexBundelIndices: [0]
        };
        if (indexBuffer) {
          bufferBlob.setNextAlignment(idxStride);
          primitive.indexView = {
            offset: bufferBlob.getLength(),
            length: indexBuffer.byteLength,
            count: idxCount,
            stride: idxStride
          };
          bufferBlob.addBuffer(indexBuffer);
        }
        var minPosition = geometry.minPos;
        if (!minPosition && options.calculateBounds) {
          minPosition = Vec3.set(new Vec3(), Infinity, Infinity, Infinity);
          for (var iVertex = 0; iVertex < vertCount; ++iVertex) {
            Vec3.set(v3_1$3, positions[iVertex * 3 + 0], positions[iVertex * 3 + 1], positions[iVertex * 3 + 2]);
            Vec3.min(minPosition, minPosition, v3_1$3);
          }
        }
        var maxPosition = geometry.maxPos;
        if (!maxPosition && options.calculateBounds) {
          maxPosition = Vec3.set(new Vec3(), -Infinity, -Infinity, -Infinity);
          for (var _iVertex = 0; _iVertex < vertCount; ++_iVertex) {
            Vec3.set(v3_1$3, positions[_iVertex * 3 + 0], positions[_iVertex * 3 + 1], positions[_iVertex * 3 + 2]);
            Vec3.max(maxPosition, maxPosition, v3_1$3);
          }
        }
        var meshStruct = {
          vertexBundles: [vertexBundle],
          primitives: [primitive]
        };
        if (minPosition) {
          meshStruct.minPosition = new Vec3(minPosition.x, minPosition.y, minPosition.z);
        }
        if (maxPosition) {
          meshStruct.maxPosition = new Vec3(maxPosition.x, maxPosition.y, maxPosition.z);
        }
        if (!out) {
          out = new Mesh();
        }
        out.reset({
          struct: meshStruct,
          data: new Uint8Array(bufferBlob.getCombined())
        });
        return out;
      }
      function getPadding(length, align) {
        if (align > 0) {
          var remainder = length % align;
          if (remainder !== 0) {
            var padding = align - remainder;
            return padding;
          }
        }
        return 0;
      }
      function _createDynamicMesh(primitiveIndex, geometry, out, options) {
        options = options || {
          maxSubMeshes: 1,
          maxSubMeshVertices: 1024,
          maxSubMeshIndices: 1024
        };
        var attributes = [];
        var stream = 0;
        if (geometry.positions.length > 0) {
          attributes.push(new Attribute(AttributeName.ATTR_POSITION, Format.RGB32F, false, stream++, false, 0));
        }
        if (geometry.normals && geometry.normals.length > 0) {
          attributes.push(new Attribute(AttributeName.ATTR_NORMAL, Format.RGB32F, false, stream++, false, 0));
        }
        if (geometry.uvs && geometry.uvs.length > 0) {
          attributes.push(new Attribute(AttributeName.ATTR_TEX_COORD, Format.RG32F, false, stream++, false, 0));
        }
        if (geometry.tangents && geometry.tangents.length > 0) {
          attributes.push(new Attribute(AttributeName.ATTR_TANGENT, Format.RGBA32F, false, stream++, false, 0));
        }
        if (geometry.colors && geometry.colors.length > 0) {
          attributes.push(new Attribute(AttributeName.ATTR_COLOR, Format.RGBA32F, false, stream++, false, 0));
        }
        if (geometry.customAttributes) {
          for (var k = 0; k < geometry.customAttributes.length; k++) {
            var ca = geometry.customAttributes[k];
            var attr = new Attribute();
            attr.copy(ca.attr);
            attr.stream = stream++;
            attributes.push(attr);
          }
        }
        var vertexBundles = [];
        var primitives = [];
        var dataSize = 0;
        for (var i = 0; i < options.maxSubMeshes; i++) {
          var primitive = {
            vertexBundelIndices: [],
            primitiveMode: geometry.primitiveMode || PrimitiveMode.TRIANGLE_LIST
          };
          for (var _iterator6 = _createForOfIteratorHelperLoose(attributes), _step6; !(_step6 = _iterator6()).done;) {
            var _attr = _step6.value;
            var formatInfo = FormatInfos[_attr.format];
            var vertexBufferSize = options.maxSubMeshVertices * formatInfo.size;
            var vertexView = {
              offset: dataSize,
              length: vertexBufferSize,
              count: 0,
              stride: formatInfo.size
            };
            var vertexBundle = {
              view: vertexView,
              attributes: [_attr]
            };
            var vertexBundleIndex = vertexBundles.length;
            primitive.vertexBundelIndices.push(vertexBundleIndex);
            vertexBundles.push(vertexBundle);
            dataSize += vertexBufferSize;
          }
          var stride = 0;
          if (geometry.indices16 && geometry.indices16.length > 0) {
            stride = 2;
          } else if (geometry.indices32 && geometry.indices32.length > 0) {
            stride = 4;
          }
          if (stride > 0) {
            dataSize += getPadding(dataSize, stride);
            var indexBufferSize = options.maxSubMeshIndices * stride;
            var indexView = {
              offset: dataSize,
              length: indexBufferSize,
              count: 0,
              stride: stride
            };
            primitive.indexView = indexView;
            dataSize += indexBufferSize;
          }
          primitives.push(primitive);
        }
        var dynamicInfo = {
          maxSubMeshes: options.maxSubMeshes,
          maxSubMeshVertices: options.maxSubMeshVertices,
          maxSubMeshIndices: options.maxSubMeshIndices
        };
        var dynamicStruct = {
          info: dynamicInfo,
          bounds: []
        };
        dynamicStruct.bounds.length = options.maxSubMeshes;
        var meshStruct = {
          vertexBundles: vertexBundles,
          primitives: primitives,
          dynamic: dynamicStruct
        };
        var createInfo = {
          struct: meshStruct,
          data: new Uint8Array(dataSize)
        };
        if (!out) {
          out = new Mesh();
        }
        out.reset(createInfo);
        out.initialize();
        out.updateSubMesh(primitiveIndex, geometry);
        return out;
      }
      var MeshUtils = function () {
        function MeshUtils() {}
        MeshUtils.createMesh = function createMesh(geometry, out, options) {
          return _createMesh(geometry, out, options);
        };
        MeshUtils.createDynamicMesh = function createDynamicMesh(primitiveIndex, geometry, out, options) {
          return _createDynamicMesh(primitiveIndex, geometry, out, options);
        };
        MeshUtils.decodeMesh = function decodeMesh$1(mesh) {
          return decodeMesh(mesh);
        };
        MeshUtils.inflateMesh = function inflateMesh$1(mesh) {
          return inflateMesh(mesh);
        };
        return MeshUtils;
      }();

      var utils = /*#__PURE__*/Object.freeze({
        __proto__: null,
        find: find,
        toPPM: toPPM,
        readMesh: readMesh,
        createMesh: _createMesh,
        MeshUtils: MeshUtils,
        readBuffer: readBuffer,
        writeBuffer: writeBuffer,
        mapBuffer: mapBuffer
      });
      exports('$', utils);

      var _dec$2q, _class$2o, _class2$28;
      var INSET_LEFT = 0;
      var INSET_TOP = 1;
      var INSET_RIGHT = 2;
      var INSET_BOTTOM = 3;
      var temp_vec3 = new Vec3();
      var temp_matrix = new Mat4();
      var MeshType;
      (function (MeshType) {
        MeshType[MeshType["RECT"] = 0] = "RECT";
        MeshType[MeshType["POLYGON"] = 1] = "POLYGON";
      })(MeshType || (MeshType = {}));
      var temp_uvs = [{
        u: 0,
        v: 0
      }, {
        u: 0,
        v: 0
      }, {
        u: 0,
        v: 0
      }, {
        u: 0,
        v: 0
      }];
      var SpriteFrame = exports('b', (_dec$2q = ccclass$n('cc.SpriteFrame'), _dec$2q(_class$2o = (_class2$28 = function (_Asset) {
        _inheritsLoose(SpriteFrame, _Asset);
        SpriteFrame.createWithImage = function createWithImage(imageSourceOrImageAsset) {
          var img = imageSourceOrImageAsset instanceof ImageAsset ? imageSourceOrImageAsset : new ImageAsset(imageSourceOrImageAsset);
          var tex = new Texture2D();
          tex.image = img;
          var spf = new SpriteFrame();
          spf.texture = tex;
          return spf;
        };
        function SpriteFrame() {
          var _this;
          _this = _Asset.call(this) || this;
          _this.vertices = null;
          _this.uv = [];
          _this.unbiasUV = [];
          _this.uvSliced = [];
          _this._rect = new Rect$1();
          _this._trimmedBorder = new Vec4();
          _this._offset = new Vec2();
          _this._originalSize = new Size$1();
          _this._rotated = false;
          _this._capInsets = [0, 0, 0, 0];
          _this._atlasUuid = '';
          _this._texture = void 0;
          _this._isFlipUVY = false;
          _this._isFlipUVX = false;
          _this._original = null;
          _this._packable = true;
          _this._pixelsToUnit = 100;
          _this._pivot = new Vec2(0.5, 0.5);
          _this._meshType = MeshType.RECT;
          _this._extrude = 0;
          _this._customOutLine = [];
          _this._minPos = new Vec3();
          _this._maxPos = new Vec3();
          return _this;
        }
        var _proto = SpriteFrame.prototype;
        _proto.textureLoaded = function textureLoaded() {
          return !!this.texture;
        };
        _proto.isRotated = function isRotated() {
          return this._rotated;
        };
        _proto.setRotated = function setRotated(rotated) {
          this.rotated = rotated;
        };
        _proto.getRect = function getRect(out) {
          if (out) {
            out.set(this._rect);
            return out;
          }
          return this._rect.clone();
        };
        _proto.setRect = function setRect(rect) {
          this.rect = rect;
        };
        _proto.getOriginalSize = function getOriginalSize(out) {
          if (out) {
            out.set(this._originalSize);
            return out;
          }
          return this._originalSize.clone();
        };
        _proto.setOriginalSize = function setOriginalSize(size) {
          this.originalSize = size;
        };
        _proto.getOffset = function getOffset(out) {
          if (out) {
            out.set(this._offset);
            return out;
          }
          return this._offset.clone();
        };
        _proto.setOffset = function setOffset(offset) {
          this.offset = offset;
        };
        _proto.getGFXTexture = function getGFXTexture() {
          return this._texture.getGFXTexture();
        };
        _proto.getGFXSampler = function getGFXSampler() {
          return this._texture.getGFXSampler();
        };
        _proto.getHash = function getHash() {
          return this._texture.getHash();
        };
        _proto.getSamplerInfo = function getSamplerInfo() {
          return this._texture.getSamplerInfo();
        };
        _proto.reset = function reset(info, clearData) {
          if (clearData === void 0) {
            clearData = false;
          }
          var calUV = false;
          if (clearData) {
            this._originalSize.set(0, 0);
            this._rect.set(0, 0, 0, 0);
            this._offset.set(0, 0);
            this._capInsets = [0, 0, 0, 0];
            this._rotated = false;
            calUV = true;
          }
          if (info) {
            if (info.texture) {
              this._rect.x = this._rect.y = 0;
              this._rect.width = info.texture.width;
              this._rect.height = info.texture.height;
              this._refreshTexture(info.texture);
              this.checkRect(this._texture);
            }
            if (info.originalSize) {
              this._originalSize.set(info.originalSize);
            }
            if (info.rect) {
              this._rect.set(info.rect);
            }
            if (info.offset) {
              this._offset.set(info.offset);
            }
            if (info.borderTop !== undefined) {
              this._capInsets[INSET_TOP] = info.borderTop;
            }
            if (info.borderBottom !== undefined) {
              this._capInsets[INSET_BOTTOM] = info.borderBottom;
            }
            if (info.borderLeft !== undefined) {
              this._capInsets[INSET_LEFT] = info.borderLeft;
            }
            if (info.borderRight !== undefined) {
              this._capInsets[INSET_RIGHT] = info.borderRight;
            }
            if (info.isRotate !== undefined) {
              this._rotated = !!info.isRotate;
            }
            if (info.isFlipUv !== undefined) {
              this._isFlipUVY = !!info.isFlipUv;
            }
            calUV = true;
          }
          if (calUV && this.texture) {
            this._calculateUV();
          }
          this._calcTrimmedBorder();
        };
        _proto.checkRect = function checkRect(texture) {
          var rect = this._rect;
          var maxX = rect.x;
          var maxY = rect.y;
          if (this._rotated) {
            maxX += rect.height;
            maxY += rect.width;
          } else {
            maxX += rect.width;
            maxY += rect.height;
          }
          if (maxX > texture.width) {
            errorID(3300, this.name + "/" + texture.name, maxX, texture.width);
            return false;
          }
          if (maxY > texture.height) {
            errorID(3301, this.name + "/" + texture.name, maxY, texture.height);
            return false;
          }
          return true;
        };
        _proto._calcTrimmedBorder = function _calcTrimmedBorder() {
          var ow = this._originalSize.width;
          var oh = this._originalSize.height;
          var rw = this._rect.width;
          var rh = this._rect.height;
          var halfTrimmedWidth = (ow - rw) * 0.5;
          var halfTrimmedHeight = (oh - rh) * 0.5;
          this._trimmedBorder.x = this._offset.x + halfTrimmedWidth;
          this._trimmedBorder.y = this._offset.x - halfTrimmedWidth;
          this._trimmedBorder.z = this._offset.y + halfTrimmedHeight;
          this._trimmedBorder.w = this._offset.y - halfTrimmedHeight;
        };
        _proto.ensureMeshData = function ensureMeshData() {
          if (this._mesh) return;
          this._initVertices();
          this._createMesh();
        };
        _proto.destroy = function destroy() {
          if (this._packable && dynamicAtlasManager) {
            dynamicAtlasManager.deleteAtlasSpriteFrame(this);
          }
          return _Asset.prototype.destroy.call(this);
        };
        _proto._calculateSlicedUV = function _calculateSlicedUV() {
          var rect = this._rect;
          var tex = this.texture;
          var atlasWidth = tex.width;
          var atlasHeight = tex.height;
          var leftWidth = this._capInsets[INSET_LEFT];
          var rightWidth = this._capInsets[INSET_RIGHT];
          var centerWidth = rect.width - leftWidth - rightWidth;
          var topHeight = this._capInsets[INSET_TOP];
          var bottomHeight = this._capInsets[INSET_BOTTOM];
          var centerHeight = rect.height - topHeight - bottomHeight;
          var uvSliced = this.uvSliced;
          uvSliced.length = 0;
          if (this._rotated) {
            temp_uvs[0].u = rect.x / atlasWidth;
            temp_uvs[1].u = (rect.x + bottomHeight) / atlasWidth;
            temp_uvs[2].u = (rect.x + bottomHeight + centerHeight) / atlasWidth;
            temp_uvs[3].u = (rect.x + rect.height) / atlasWidth;
            temp_uvs[3].v = rect.y / atlasHeight;
            temp_uvs[2].v = (rect.y + leftWidth) / atlasHeight;
            temp_uvs[1].v = (rect.y + leftWidth + centerWidth) / atlasHeight;
            temp_uvs[0].v = (rect.y + rect.width) / atlasHeight;
            for (var row = 0; row < 4; ++row) {
              var rowD = temp_uvs[row];
              for (var col = 0; col < 4; ++col) {
                var colD = temp_uvs[3 - col];
                uvSliced.push({
                  u: rowD.u,
                  v: colD.v
                });
              }
            }
          } else {
            temp_uvs[0].u = rect.x / atlasWidth;
            temp_uvs[1].u = (rect.x + leftWidth) / atlasWidth;
            temp_uvs[2].u = (rect.x + leftWidth + centerWidth) / atlasWidth;
            temp_uvs[3].u = (rect.x + rect.width) / atlasWidth;
            temp_uvs[3].v = rect.y / atlasHeight;
            temp_uvs[2].v = (rect.y + topHeight) / atlasHeight;
            temp_uvs[1].v = (rect.y + topHeight + centerHeight) / atlasHeight;
            temp_uvs[0].v = (rect.y + rect.height) / atlasHeight;
            for (var _row = 0; _row < 4; ++_row) {
              var _rowD = temp_uvs[_row];
              for (var _col = 0; _col < 4; ++_col) {
                var _colD = temp_uvs[_col];
                uvSliced.push({
                  u: _colD.u,
                  v: _rowD.v
                });
              }
            }
          }
          this.emit(SpriteFrame.EVENT_UV_UPDATED, this);
        };
        _proto._calculateUV = function _calculateUV() {
          var rect = this._rect;
          var uv = this.uv;
          var unbiasUV = this.unbiasUV;
          var tex = this.texture;
          var texw = tex.width;
          var texh = tex.height;
          if (this._rotated) {
            var l = texw === 0 ? 0 : rect.x / texw;
            var r = texw === 0 ? 1 : (rect.x + rect.height) / texw;
            var t = texh === 0 ? 0 : rect.y / texh;
            var b = texh === 0 ? 1 : (rect.y + rect.width) / texh;
            if (this._isFlipUVX && this._isFlipUVY) {
              uv[0] = r;
              uv[1] = b;
              uv[2] = r;
              uv[3] = t;
              uv[4] = l;
              uv[5] = b;
              uv[6] = l;
              uv[7] = t;
            } else if (this._isFlipUVX) {
              uv[0] = r;
              uv[1] = t;
              uv[2] = r;
              uv[3] = b;
              uv[4] = l;
              uv[5] = t;
              uv[6] = l;
              uv[7] = b;
            } else if (this._isFlipUVY) {
              uv[0] = l;
              uv[1] = b;
              uv[2] = l;
              uv[3] = t;
              uv[4] = r;
              uv[5] = b;
              uv[6] = r;
              uv[7] = t;
            } else {
              uv[0] = l;
              uv[1] = t;
              uv[2] = l;
              uv[3] = b;
              uv[4] = r;
              uv[5] = t;
              uv[6] = r;
              uv[7] = b;
            }
            var ul = texw === 0 ? 0 : rect.x / texw;
            var ur = texw === 0 ? 1 : (rect.x + rect.height) / texw;
            var ut = texh === 0 ? 0 : rect.y / texh;
            var ub = texh === 0 ? 1 : (rect.y + rect.width) / texh;
            if (this._isFlipUVX && this._isFlipUVY) {
              unbiasUV[0] = ur;
              unbiasUV[1] = ub;
              unbiasUV[2] = ur;
              unbiasUV[3] = ut;
              unbiasUV[4] = ul;
              unbiasUV[5] = ub;
              unbiasUV[6] = ul;
              unbiasUV[7] = ut;
            } else if (this._isFlipUVX) {
              unbiasUV[0] = ur;
              unbiasUV[1] = ut;
              unbiasUV[2] = ur;
              unbiasUV[3] = ub;
              unbiasUV[4] = ul;
              unbiasUV[5] = ut;
              unbiasUV[6] = ul;
              unbiasUV[7] = ub;
            } else if (this._isFlipUVY) {
              unbiasUV[0] = ul;
              unbiasUV[1] = ub;
              unbiasUV[2] = ul;
              unbiasUV[3] = ut;
              unbiasUV[4] = ur;
              unbiasUV[5] = ub;
              unbiasUV[6] = ur;
              unbiasUV[7] = ut;
            } else {
              unbiasUV[0] = ul;
              unbiasUV[1] = ut;
              unbiasUV[2] = ul;
              unbiasUV[3] = ub;
              unbiasUV[4] = ur;
              unbiasUV[5] = ut;
              unbiasUV[6] = ur;
              unbiasUV[7] = ub;
            }
          } else {
            var _l = texw === 0 ? 0 : rect.x / texw;
            var _r = texw === 0 ? 1 : (rect.x + rect.width) / texw;
            var _b = texh === 0 ? 1 : (rect.y + rect.height) / texh;
            var _t = texh === 0 ? 0 : rect.y / texh;
            if (this._isFlipUVX && this._isFlipUVY) {
              uv[0] = _r;
              uv[1] = _t;
              uv[2] = _l;
              uv[3] = _t;
              uv[4] = _r;
              uv[5] = _b;
              uv[6] = _l;
              uv[7] = _b;
            } else if (this._isFlipUVX) {
              uv[0] = _r;
              uv[1] = _b;
              uv[2] = _l;
              uv[3] = _b;
              uv[4] = _r;
              uv[5] = _t;
              uv[6] = _l;
              uv[7] = _t;
            } else if (this._isFlipUVY) {
              uv[0] = _l;
              uv[1] = _t;
              uv[2] = _r;
              uv[3] = _t;
              uv[4] = _l;
              uv[5] = _b;
              uv[6] = _r;
              uv[7] = _b;
            } else {
              uv[0] = _l;
              uv[1] = _b;
              uv[2] = _r;
              uv[3] = _b;
              uv[4] = _l;
              uv[5] = _t;
              uv[6] = _r;
              uv[7] = _t;
            }
            var _ul = texw === 0 ? 0 : rect.x / texw;
            var _ur = texw === 0 ? 1 : (rect.x + rect.width) / texw;
            var _ub = texh === 0 ? 1 : (rect.y + rect.height) / texh;
            var _ut = texh === 0 ? 0 : rect.y / texh;
            if (this._isFlipUVX && this._isFlipUVY) {
              unbiasUV[0] = _ur;
              unbiasUV[1] = _ut;
              unbiasUV[2] = _ul;
              unbiasUV[3] = _ut;
              unbiasUV[4] = _ur;
              unbiasUV[5] = _ub;
              unbiasUV[6] = _ul;
              unbiasUV[7] = _ub;
            } else if (this._isFlipUVX) {
              unbiasUV[0] = _ur;
              unbiasUV[1] = _ub;
              unbiasUV[2] = _ul;
              unbiasUV[3] = _ub;
              unbiasUV[4] = _ur;
              unbiasUV[5] = _ut;
              unbiasUV[6] = _ul;
              unbiasUV[7] = _ut;
            } else if (this._isFlipUVY) {
              unbiasUV[0] = _ul;
              unbiasUV[1] = _ut;
              unbiasUV[2] = _ur;
              unbiasUV[3] = _ut;
              unbiasUV[4] = _ul;
              unbiasUV[5] = _ub;
              unbiasUV[6] = _ur;
              unbiasUV[7] = _ub;
            } else {
              unbiasUV[0] = _ul;
              unbiasUV[1] = _ub;
              unbiasUV[2] = _ur;
              unbiasUV[3] = _ub;
              unbiasUV[4] = _ul;
              unbiasUV[5] = _ut;
              unbiasUV[6] = _ur;
              unbiasUV[7] = _ut;
            }
          }
          this._calculateSlicedUV();
        };
        _proto._setDynamicAtlasFrame = function _setDynamicAtlasFrame(frame) {
          if (!frame) return;
          this._original = {
            _texture: this._texture,
            _x: this._rect.x,
            _y: this._rect.y
          };
          this._texture = frame.texture;
          this._rect.x = frame.x;
          this._rect.y = frame.y;
          this._calculateUV();
        };
        _proto._resetDynamicAtlasFrame = function _resetDynamicAtlasFrame() {
          if (!this._original) return;
          this._rect.x = this._original._x;
          this._rect.y = this._original._y;
          this._texture = this._original._texture;
          this._original = null;
          this._calculateUV();
        };
        _proto._checkPackable = function _checkPackable() {
          var dynamicAtlas = dynamicAtlasManager;
          if (!dynamicAtlas) return;
          var texture = this._texture;
          if (!(texture instanceof Texture2D) || texture.isCompressed) {
            this._packable = false;
            return;
          }
          var w = this.width;
          var h = this.height;
          if (!texture.image || w > dynamicAtlas.maxFrameSize || h > dynamicAtlas.maxFrameSize) {
            this._packable = false;
            return;
          }
          var CanvasElement = ccwindow.HTMLCanvasElement;
          if (texture.image && texture.image instanceof CanvasElement) {
            this._packable = true;
          }
        };
        _proto._serialize = function _serialize(ctxForExporting) {
          return null;
        };
        _proto._deserialize = function _deserialize(serializeData, handle) {
          var data = serializeData;
          var rect = data.rect;
          if (rect) {
            this._rect = new Rect$1(rect.x, rect.y, rect.width, rect.height);
          }
          var offset = data.offset;
          if (data.offset) {
            this._offset = new Vec2(offset.x, offset.y);
          }
          var originalSize = data.originalSize;
          if (data.originalSize) {
            this._originalSize = new Size$1(originalSize.width, originalSize.height);
          }
          this._rotated = !!data.rotated;
          this._name = data.name;
          this._packable = !!data.packable;
          this._pixelsToUnit = data.pixelsToUnit;
          var pivot = data.pivot;
          if (pivot) {
            this._pivot = new Vec2(pivot.x, pivot.y);
          }
          this._meshType = data.meshType;
          var capInsets = data.capInsets;
          if (capInsets) {
            this._capInsets[INSET_LEFT] = capInsets[INSET_LEFT];
            this._capInsets[INSET_TOP] = capInsets[INSET_TOP];
            this._capInsets[INSET_RIGHT] = capInsets[INSET_RIGHT];
            this._capInsets[INSET_BOTTOM] = capInsets[INSET_BOTTOM];
          }
          var vertices = data.vertices;
          if (vertices) {
            if (!this.vertices) {
              this.vertices = {
                rawPosition: [],
                positions: [],
                indexes: vertices.indexes,
                uv: vertices.uv,
                nuv: vertices.nuv,
                minPos: new Vec3(vertices.minPos.x, vertices.minPos.y, vertices.minPos.z),
                maxPos: new Vec3(vertices.maxPos.x, vertices.maxPos.y, vertices.maxPos.z)
              };
            }
            this.vertices.rawPosition.length = 0;
            var rawPosition = vertices.rawPosition;
            for (var i = 0; i < rawPosition.length; i += 3) {
              this.vertices.rawPosition.push(new Vec3(rawPosition[i], rawPosition[i + 1], rawPosition[i + 2]));
            }
            this._updateMeshVertices();
          }
        };
        _proto.clone = function clone() {
          var _sp$uv, _sp$unbiasUV, _sp$uvSliced, _sp$_capInsets;
          var sp = new SpriteFrame();
          var v = this.vertices;
          sp.vertices = v ? {
            rawPosition: v.rawPosition.slice(0),
            positions: v.positions.slice(0),
            indexes: v.indexes.slice(0),
            uv: v.uv.slice(0),
            nuv: v.nuv.slice(0),
            minPos: v.minPos.clone(),
            maxPos: v.minPos.clone()
          } : null;
          (_sp$uv = sp.uv).splice.apply(_sp$uv, [0, sp.uv.length].concat(this.uv));
          (_sp$unbiasUV = sp.unbiasUV).splice.apply(_sp$unbiasUV, [0, sp.unbiasUV.length].concat(this.unbiasUV));
          (_sp$uvSliced = sp.uvSliced).splice.apply(_sp$uvSliced, [0, sp.uvSliced.length].concat(this.uvSliced));
          sp._rect.set(this._rect);
          sp._offset.set(this._offset);
          sp._originalSize.set(this._originalSize);
          sp._rotated = this._rotated;
          (_sp$_capInsets = sp._capInsets).splice.apply(_sp$_capInsets, [0, sp._capInsets.length].concat(this._capInsets));
          sp._atlasUuid = this._atlasUuid;
          sp._texture = this._texture;
          sp._isFlipUVX = this._isFlipUVX;
          sp._isFlipUVY = this._isFlipUVY;
          sp._pixelsToUnit = this._pixelsToUnit;
          sp._pivot.set(this._pivot);
          sp._meshType = this._meshType;
          return sp;
        };
        _proto._refreshTexture = function _refreshTexture(texture) {
          this._texture = texture;
          var tex = this._texture;
          var config = {};
          var isReset = false;
          if (this._rect.width === 0 || this._rect.height === 0 || !this.checkRect(tex)) {
            config.rect = new Rect$1(0, 0, tex.width, tex.height);
            isReset = true;
          }
          if (this._originalSize.width === 0 || this._originalSize.height === 0 || isReset) {
            config.originalSize = new Size$1(tex.width, tex.height);
            isReset = true;
          }
          if (isReset) {
            this.reset(config);
          }
          this._checkPackable();
          if (this._mesh) {
            this._updateMesh();
          }
        };
        _proto.onLoaded = function onLoaded() {
          this._calcTrimmedBorder();
        };
        _proto.initDefault = function initDefault(uuid) {
          _Asset.prototype.initDefault.call(this, uuid);
          var texture = new Texture2D();
          texture.initDefault();
          this._refreshTexture(texture);
          this._calculateUV();
        };
        _proto.validate = function validate() {
          return this._texture && this._rect && this._rect.width !== 0 && this._rect.height !== 0;
        };
        _proto._initVertices = function _initVertices() {
          if (!this.vertices) {
            this.vertices = {
              rawPosition: [],
              positions: [],
              indexes: [],
              uv: [],
              nuv: [],
              minPos: new Vec3(),
              maxPos: new Vec3()
            };
          } else {
            this.vertices.rawPosition.length = 0;
            this.vertices.positions.length = 0;
            this.vertices.indexes.length = 0;
            this.vertices.uv.length = 0;
            this.vertices.nuv.length = 0;
            this.vertices.minPos.set(0, 0, 0);
            this.vertices.maxPos.set(0, 0, 0);
          }
          if (this._meshType === MeshType.POLYGON) ; else {
            var tex = this.texture;
            var texw = tex.width;
            var texh = tex.height;
            var rect = this.rect;
            var width = rect.width;
            var height = rect.height;
            var rectX = rect.x;
            var rectY = texh - rect.y - height;
            var halfWidth = width / 2;
            var halfHeight = height / 2;
            var l = texw === 0 ? 0 : rectX / texw;
            var r = texw === 0 ? 1 : (rectX + width) / texw;
            var t = texh === 0 ? 1 : (rectY + height) / texh;
            var b = texh === 0 ? 0 : rect.y / texh;
            temp_vec3.set(-halfWidth, -halfHeight, 0);
            this.vertices.rawPosition.push(temp_vec3.clone());
            this.vertices.uv.push(rectX);
            this.vertices.uv.push(rectY + height);
            this.vertices.nuv.push(l);
            this.vertices.nuv.push(b);
            this.vertices.minPos.set(temp_vec3);
            temp_vec3.set(halfWidth, -halfHeight, 0);
            this.vertices.rawPosition.push(temp_vec3.clone());
            this.vertices.uv.push(rectX + width);
            this.vertices.uv.push(rectY + height);
            this.vertices.nuv.push(r);
            this.vertices.nuv.push(b);
            temp_vec3.set(-halfWidth, halfHeight, 0);
            this.vertices.rawPosition.push(temp_vec3.clone());
            this.vertices.uv.push(rectX);
            this.vertices.uv.push(rectY);
            this.vertices.nuv.push(l);
            this.vertices.nuv.push(t);
            temp_vec3.set(halfWidth, halfHeight, 0);
            this.vertices.rawPosition.push(temp_vec3.clone());
            this.vertices.uv.push(rectX + width);
            this.vertices.uv.push(rectY);
            this.vertices.nuv.push(r);
            this.vertices.nuv.push(t);
            this.vertices.maxPos.set(temp_vec3);
            this.vertices.indexes.push(0);
            this.vertices.indexes.push(1);
            this.vertices.indexes.push(2);
            this.vertices.indexes.push(2);
            this.vertices.indexes.push(1);
            this.vertices.indexes.push(3);
          }
          this._updateMeshVertices();
        };
        _proto._updateMeshVertices = function _updateMeshVertices() {
          temp_matrix.identity();
          var units = 1 / this._pixelsToUnit;
          var PosX = -(this._pivot.x - 0.5) * this.rect.width * units;
          var PosY = -(this._pivot.y - 0.5) * this.rect.height * units;
          var temp_vec3 = new Vec3(PosX, PosY, 0);
          temp_matrix.transform(temp_vec3);
          temp_vec3.set(units, units, 1);
          temp_matrix.scale(temp_vec3);
          var vertices = this.vertices;
          for (var i = 0; i < vertices.rawPosition.length; i++) {
            var pos = vertices.rawPosition[i];
            Vec3.transformMat4(temp_vec3, pos, temp_matrix);
            Vec3.toArray(vertices.positions, temp_vec3, 3 * i);
          }
          Vec3.transformMat4(this._minPos, vertices.minPos, temp_matrix);
          Vec3.transformMat4(this._maxPos, vertices.maxPos, temp_matrix);
        };
        _proto._createMesh = function _createMesh$1() {
          this._mesh = _createMesh({
            primitiveMode: PrimitiveMode.TRIANGLE_LIST,
            positions: this.vertices.positions,
            uvs: this.vertices.nuv,
            indices: this.vertices.indexes,
            minPos: this._minPos,
            maxPos: this._maxPos,
            attributes: [new Attribute(AttributeName.ATTR_POSITION, Format.RGB32F), new Attribute(AttributeName.ATTR_TEX_COORD, Format.RG32F)]
          });
        };
        _proto._updateMesh = function _updateMesh() {
          if (this._mesh) {
            this._mesh.destroy();
          }
          this._initVertices();
          this._createMesh();
        };
        _createClass(SpriteFrame, [{
          key: "insetTop",
          get: function get() {
            return this._capInsets[INSET_TOP];
          },
          set: function set(value) {
            if (this._capInsets[INSET_TOP] === value) {
              return;
            }
            this._capInsets[INSET_TOP] = value;
            if (this._texture) {
              this._calculateSlicedUV();
            }
          }
        }, {
          key: "insetBottom",
          get: function get() {
            return this._capInsets[INSET_BOTTOM];
          },
          set: function set(value) {
            if (this._capInsets[INSET_BOTTOM] === value) {
              return;
            }
            this._capInsets[INSET_BOTTOM] = value;
            if (this._texture) {
              this._calculateSlicedUV();
            }
          }
        }, {
          key: "insetLeft",
          get: function get() {
            return this._capInsets[INSET_LEFT];
          },
          set: function set(value) {
            if (this._capInsets[INSET_LEFT] === value) {
              return;
            }
            this._capInsets[INSET_LEFT] = value;
            if (this._texture) {
              this._calculateSlicedUV();
            }
          }
        }, {
          key: "insetRight",
          get: function get() {
            return this._capInsets[INSET_RIGHT];
          },
          set: function set(value) {
            if (this._capInsets[INSET_RIGHT] === value) {
              return;
            }
            this._capInsets[INSET_RIGHT] = value;
            if (this._texture) {
              this._calculateSlicedUV();
            }
          }
        }, {
          key: "rect",
          get: function get() {
            return this._rect;
          },
          set: function set(value) {
            if (this._rect.equals(value)) {
              return;
            }
            this._rect.set(value);
            if (this._texture) {
              this._calculateUV();
            }
            this._calcTrimmedBorder();
          }
        }, {
          key: "originalSize",
          get: function get() {
            return this._originalSize;
          },
          set: function set(value) {
            if (this._originalSize.equals(value)) {
              return;
            }
            this._originalSize.set(value);
            if (this._texture) {
              this._calculateUV();
            }
            this._calcTrimmedBorder();
          }
        }, {
          key: "offset",
          get: function get() {
            return this._offset;
          },
          set: function set(value) {
            this._offset.set(value);
            this._calcTrimmedBorder();
          }
        }, {
          key: "rotated",
          get: function get() {
            return this._rotated;
          },
          set: function set(rotated) {
            if (this._rotated === rotated) {
              return;
            }
            this._rotated = rotated;
            if (this._texture) {
              this._calculateUV();
            }
          }
        }, {
          key: "texture",
          get: function get() {
            return this._texture;
          },
          set: function set(value) {
            if (!value) {
              warnID(3122, this.name);
              return;
            }
            if (value === this._texture) {
              return;
            }
            this.reset({
              texture: value
            }, true);
          }
        }, {
          key: "atlasUuid",
          get: function get() {
            return this._atlasUuid;
          },
          set: function set(value) {
            this._atlasUuid = value;
          }
        }, {
          key: "width",
          get: function get() {
            return this._texture.width;
          }
        }, {
          key: "height",
          get: function get() {
            return this._texture.height;
          }
        }, {
          key: "_textureSource",
          set: function set(value) {
            if (globalThis.Build) {
              this._texture = value;
              return;
            }
            if (value) {
              this._refreshTexture(value);
              this._calculateUV();
            }
          }
        }, {
          key: "flipUVX",
          get: function get() {
            return this._isFlipUVX;
          },
          set: function set(value) {
            this._isFlipUVX = value;
            this._calculateUV();
          }
        }, {
          key: "flipUVY",
          get: function get() {
            return this._isFlipUVY;
          },
          set: function set(value) {
            this._isFlipUVY = value;
            this._calculateUV();
          }
        }, {
          key: "packable",
          get: function get() {
            return this._packable;
          },
          set: function set(value) {
            this._packable = value;
          }
        }, {
          key: "original",
          get: function get() {
            return this._original;
          }
        }, {
          key: "pixelsToUnit",
          get: function get() {
            return this._pixelsToUnit;
          }
        }, {
          key: "pivot",
          get: function get() {
            return this._pivot;
          }
        }, {
          key: "mesh",
          get: function get() {
            return this._mesh;
          }
        }, {
          key: "trimmedBorder",
          get: function get() {
            return this._trimmedBorder;
          }
        }]);
        return SpriteFrame;
      }(Asset), _class2$28.EVENT_UV_UPDATED = 'uv_updated', _class2$28.MeshType = MeshType, _class2$28)) || _class$2o));
      legacyCC.SpriteFrame = SpriteFrame;

      var _dec$2p, _class$2n, _class2$27, _initializer$1Z;
      var SpriteAtlas = exports('a', (_dec$2p = ccclass$n('cc.SpriteAtlas'), _dec$2p(_class$2n = (_class2$27 = function (_Asset) {
        _inheritsLoose(SpriteAtlas, _Asset);
        function SpriteAtlas() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Asset.call.apply(_Asset, [this].concat(args)) || this;
          _this.spriteFrames = _initializer$1Z && _initializer$1Z();
          return _this;
        }
        var _proto = SpriteAtlas.prototype;
        _proto.getTexture = function getTexture() {
          var keys = Object.keys(this.spriteFrames);
          if (keys.length > 0) {
            var spriteFrame = this.spriteFrames[keys[0]];
            return spriteFrame && spriteFrame.texture;
          } else {
            return null;
          }
        };
        _proto.getSpriteFrame = function getSpriteFrame(key) {
          var sf = this.spriteFrames[key];
          if (!sf) {
            return null;
          }
          if (!sf.name) {
            sf.name = key;
          }
          return sf;
        };
        _proto.getSpriteFrames = function getSpriteFrames() {
          var frames = [];
          var spriteFrames = this.spriteFrames;
          for (var _i = 0, _Object$keys = Object.keys(spriteFrames); _i < _Object$keys.length; _i++) {
            var _key2 = _Object$keys[_i];
            frames.push(spriteFrames[_key2]);
          }
          return frames;
        };
        _proto._serialize = function _serialize(ctxForExporting) {
        };
        _proto._deserialize = function _deserialize(serializeData, handle) {
          var data = serializeData;
          this._name = data.name;
          var frames = data.spriteFrames;
          this.spriteFrames = createMap();
          for (var i = 0; i < frames.length; i += 2) {
            handle.result.push(this.spriteFrames, frames[i], frames[i + 1], getClassId(SpriteFrame));
          }
        };
        return SpriteAtlas;
      }(Asset), (_initializer$1Z = applyDecoratedInitializer(_class2$27.prototype, "spriteFrames", [serializable$j], function () {
        return createMap();
      })), _class2$27)) || _class$2n));
      legacyCC.SpriteAtlas = SpriteAtlas;

      var _dec$2o, _class$2m;
      var Font = exports('F', (_dec$2o = ccclass$n('cc.Font'), _dec$2o(_class$2m = function (_Asset) {
        _inheritsLoose(Font, _Asset);
        function Font() {
          return _Asset.apply(this, arguments) || this;
        }
        return Font;
      }(Asset)) || _class$2m));
      legacyCC.Font = Font;

      var _dec$2n, _class$2l, _class2$26, _initializer$1Y;
      var TTFFont = exports('T', (_dec$2n = ccclass$n('cc.TTFFont'), _dec$2n(_class$2l = (_class2$26 = function (_Font) {
        _inheritsLoose(TTFFont, _Font);
        function TTFFont() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Font.call.apply(_Font, [this].concat(args)) || this;
          _this._fontFamily = _initializer$1Y && _initializer$1Y();
          return _this;
        }
        var _proto = TTFFont.prototype;
        _proto.initDefault = function initDefault(uuid) {
          this._fontFamily = 'Arial';
          _Font.prototype.initDefault.call(this, uuid);
        };
        _createClass(TTFFont, [{
          key: "_nativeAsset",
          get: function get() {
            return this._fontFamily;
          },
          set: function set(value) {
            this._fontFamily = value || 'Arial';
          }
        }, {
          key: "_nativeDep",
          get: function get() {
            return {
              uuid: this._uuid,
              __nativeName__: this._native,
              ext: extname(this._native),
              __isNative__: true
            };
          }
        }]);
        return TTFFont;
      }(Font), (_initializer$1Y = applyDecoratedInitializer(_class2$26.prototype, "_fontFamily", [serializable$j], function () {
        return null;
      }), _applyDecoratedDescriptor(_class2$26.prototype, "_nativeAsset", [override, string], Object.getOwnPropertyDescriptor(_class2$26.prototype, "_nativeAsset"), _class2$26.prototype), _applyDecoratedDescriptor(_class2$26.prototype, "_nativeDep", [override], Object.getOwnPropertyDescriptor(_class2$26.prototype, "_nativeDep"), _class2$26.prototype)), _class2$26)) || _class$2l));
      legacyCC.TTFFont = TTFFont;

      var _dec$2m, _dec2$1R, _class2$25, _class3$B, _initializer$1X, _initializer2$1z, _initializer3$12, _initializer4$Q;
      var FontLetterDefinition$1 = function FontLetterDefinition() {
        this.u = 0;
        this.v = 0;
        this.w = 0;
        this.h = 0;
        this.offsetX = 0;
        this.offsetY = 0;
        this.textureID = 0;
        this.valid = false;
        this.xAdvance = 0;
      };
      var FontAtlas = function () {
        function FontAtlas(texture) {
          this.letterDefinitions = {};
          this.texture = texture;
        }
        var _proto = FontAtlas.prototype;
        _proto.addLetterDefinitions = function addLetterDefinitions(letter, letterDefinition) {
          this.letterDefinitions[letter] = letterDefinition;
        };
        _proto.cloneLetterDefinition = function cloneLetterDefinition() {
          var copyLetterDefinitions = {};
          for (var _i = 0, _Object$keys = Object.keys(this.letterDefinitions); _i < _Object$keys.length; _i++) {
            var _key = _Object$keys[_i];
            var value = new FontLetterDefinition$1();
            mixin(value, this.letterDefinitions[_key]);
            copyLetterDefinitions[_key] = value;
          }
          return copyLetterDefinitions;
        };
        _proto.getTexture = function getTexture() {
          return this.texture;
        };
        _proto.getLetter = function getLetter(key) {
          return this.letterDefinitions[key];
        };
        _proto.getLetterDefinitionForChar = function getLetterDefinitionForChar(_char, labelInfo) {
          var key = _char.charCodeAt(0);
          var hasKey = this.letterDefinitions.hasOwnProperty(key);
          var letter;
          if (hasKey) {
            letter = this.letterDefinitions[key];
          } else {
            letter = null;
          }
          return letter;
        };
        _proto.clear = function clear() {
          this.letterDefinitions = {};
        };
        return FontAtlas;
      }();
      var BitmapFont = exports('B', (_dec$2m = ccclass$n('cc.BitmapFont'), _dec2$1R = type$7(SpriteFrame), _dec$2m(_class2$25 = (_class3$B = function (_Font) {
        _inheritsLoose(BitmapFont, _Font);
        function BitmapFont() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key2 = 0; _key2 < _len; _key2++) {
            args[_key2] = arguments[_key2];
          }
          _this = _Font.call.apply(_Font, [this].concat(args)) || this;
          _this.fntDataStr = _initializer$1X && _initializer$1X();
          _this.spriteFrame = _initializer2$1z && _initializer2$1z();
          _this.fontSize = _initializer3$12 && _initializer3$12();
          _this.fntConfig = _initializer4$Q && _initializer4$Q();
          return _this;
        }
        var _proto2 = BitmapFont.prototype;
        _proto2.onLoaded = function onLoaded() {
          var spriteFrame = this.spriteFrame;
          if (!this.fontDefDictionary && spriteFrame) {
            this.fontDefDictionary = new FontAtlas(spriteFrame.texture);
          }
          var fntConfig = this.fntConfig;
          if (!fntConfig) {
            warn('The fnt config is not exists!');
            return;
          }
          var fontDict = fntConfig.fontDefDictionary;
          for (var fontDef in fontDict) {
            var letter = new FontLetterDefinition$1();
            var rect = fontDict[fontDef].rect;
            letter.offsetX = fontDict[fontDef].xOffset;
            letter.offsetY = fontDict[fontDef].yOffset;
            letter.w = rect.width;
            letter.h = rect.height;
            letter.u = rect.x;
            letter.v = rect.y;
            letter.textureID = 0;
            letter.valid = true;
            letter.xAdvance = fontDict[fontDef].xAdvance;
            this.fontDefDictionary.addLetterDefinitions(fontDef, letter);
          }
        };
        return BitmapFont;
      }(Font), (_initializer$1X = applyDecoratedInitializer(_class3$B.prototype, "fntDataStr", [serializable$j], function () {
        return '';
      }), _initializer2$1z = applyDecoratedInitializer(_class3$B.prototype, "spriteFrame", [_dec2$1R], function () {
        return null;
      }), _initializer3$12 = applyDecoratedInitializer(_class3$B.prototype, "fontSize", [serializable$j], function () {
        return -1;
      }), _initializer4$Q = applyDecoratedInitializer(_class3$B.prototype, "fntConfig", [serializable$j], function () {
        return null;
      })), _class3$B)) || _class2$25));
      legacyCC.BitmapFont = BitmapFont;

      var _dec$2l, _class$2k;
      var LabelAtlas = exports('L', (_dec$2l = ccclass$n('cc.LabelAtlas'), _dec$2l(_class$2k = function (_BitmapFont) {
        _inheritsLoose(LabelAtlas, _BitmapFont);
        function LabelAtlas() {
          return _BitmapFont.apply(this, arguments) || this;
        }
        return LabelAtlas;
      }(BitmapFont)) || _class$2k));
      legacyCC.LabelAtlas = LabelAtlas;

      var BASELINE_RATIO = exports('x', 0.26);
      var _BASELINE_OFFSET$1 = 0;
      var MIDDLE_RATIO = exports('y', (BASELINE_RATIO + 1) / 2 - BASELINE_RATIO);
      function getBaselineOffset() {
        return _BASELINE_OFFSET$1;
      }
      var MAX_CACHE_SIZE = 100;
      var pool$1 = new Pool$1(2);
      pool$1.get = function () {
        return this._get() || {
          key: '',
          value: 0,
          prev: null,
          next: null
        };
      };
      var LRUCache = exports('A', function () {
        function LRUCache(size) {
          this.count = 0;
          this.limit = 0;
          this.datas = {};
          this.limit = size;
        }
        var _proto = LRUCache.prototype;
        _proto.moveToHead = function moveToHead(node) {
          node.next = this.head;
          node.prev = null;
          if (this.head) this.head.prev = node;
          this.head = node;
          if (!this.tail) this.tail = node;
          this.count++;
          this.datas[node.key] = node;
        };
        _proto.put = function put(key, value) {
          var node = pool$1.get();
          node.key = key;
          node.value = value;
          if (this.count >= this.limit) {
            var discard = this.tail;
            delete this.datas[discard.key];
            this.count--;
            this.tail = discard.prev;
            this.tail.next = null;
            discard.prev = null;
            discard.next = null;
            pool$1.put(discard);
          }
          this.moveToHead(node);
        };
        _proto.remove = function remove(node) {
          if (node.prev) {
            node.prev.next = node.next;
          } else {
            this.head = node.next;
          }
          if (node.next) {
            node.next.prev = node.prev;
          } else {
            this.tail = node.prev;
          }
          delete this.datas[node.key];
          this.count--;
        };
        _proto.get = function get(key) {
          var node = this.datas[key];
          if (node) {
            this.remove(node);
            this.moveToHead(node);
            return node.value;
          }
          return null;
        };
        _proto.clear = function clear() {
          this.count = 0;
          this.datas = {};
          this.head = null;
          this.tail = null;
        };
        _proto.has = function has(key) {
          return !!this.datas[key];
        };
        _proto["delete"] = function _delete(key) {
          var node = this.datas[key];
          this.remove(node);
        };
        return LRUCache;
      }());
      var measureCache = new LRUCache(MAX_CACHE_SIZE);
      var WORD_REG = /([a-zA-Z0-9ÄÖÜäöüßéèçàùêâîôûа-яА-ЯЁё]+|\S)/;
      var SYMBOL_REG = /^[!,.:;'}\]%\?>、‘“》？。，！]/;
      var LAST_WORD_REG = /([a-zA-Z0-9ÄÖÜäöüßéèçàùêâîôûаíìÍÌïÁÀáàÉÈÒÓòóŐőÙÚŰúűñÑæÆœŒÃÂãÔõěščřžýáíéóúůťďňĚŠČŘŽÁÍÉÓÚŤżźśóńłęćąŻŹŚÓŃŁĘĆĄ-яА-ЯЁёáàảạãăắằẳẵặâấầẩẫậéèẻẽẹêếềểễệiíìỉĩịóòỏõọôốồổỗộơớờởỡợúùủũụưứừửữựýỳỷỹỵđÁÀẢẠÃĂẮẰẲẴẶÂẤẦẨẪẬÉÈẺẼẸÊẾỀỂỄỆIÍÌỈĨỊÓÒỎÕỌÔỐỒỔỖỘƠỚỜỞỠỢÚÙỦŨỤƯỨỪỬỮỰÝỲỶỸỴĐ]+|\S)$/;
      var LAST_ENGLISH_REG = /[a-zA-Z0-9ÄÖÜäöüßéèçàùêâîôûаíìÍÌïÁÀáàÉÈÒÓòóŐőÙÚŰúűñÑæÆœŒÃÂãÔõěščřžýáíéóúůťďňĚŠČŘŽÁÍÉÓÚŤżźśóńłęćąŻŹŚÓŃŁĘĆĄ-яА-ЯЁёáàảạãăắằẳẵặâấầẩẫậéèẻẽẹêếềểễệiíìỉĩịóòỏõọôốồổỗộơớờởỡợúùủũụưứừửữựýỳỷỹỵđÁÀẢẠÃĂẮẰẲẴẶÂẤẦẨẪẬÉÈẺẼẸÊẾỀỂỄỆIÍÌỈĨỊÓÒỎÕỌÔỐỒỔỖỘƠỚỜỞỠỢÚÙỦŨỤƯỨỪỬỮỰÝỲỶỸỴĐ]+$/;
      var FIRST_ENGLISH_REG = /^[a-zA-Z0-9ÄÖÜäöüßéèçàùêâîôûаíìÍÌïÁÀáàÉÈÒÓòóŐőÙÚŰúűñÑæÆœŒÃÂãÔõěščřžýáíéóúůťďňĚŠČŘŽÁÍÉÓÚŤżźśóńłęćąŻŹŚÓŃŁĘĆĄ-яА-ЯЁёáàảạãăắằẳẵặâấầẩẫậéèẻẽẹêếềểễệiíìỉĩịóòỏõọôốồổỗộơớờởỡợúùủũụưứừửữựýỳỷỹỵđÁÀẢẠÃĂẮẰẲẴẶÂẤẦẨẪẬÉÈẺẼẸÊẾỀỂỄỆIÍÌỈĨỊÓÒỎÕỌÔỐỒỔỖỘƠỚỜỞỠỢÚÙỦŨỤƯỨỪỬỮỰÝỲỶỸỴĐ]/;
      function isUnicodeCJK(ch) {
        var __CHINESE_REG = /^[\u4E00-\u9FFF\u3400-\u4DFF]+$/;
        var __JAPANESE_REG = /[\u3000-\u303F]|[\u3040-\u309F]|[\u30A0-\u30FF]|[\uFF00-\uFFEF]|[\u4E00-\u9FAF]|[\u2605-\u2606]|[\u2190-\u2195]|\u203B/g;
        var __KOREAN_REG = /^[\u1100-\u11FF]|[\u3130-\u318F]|[\uA960-\uA97F]|[\uAC00-\uD7AF]|[\uD7B0-\uD7FF]+$/;
        return __CHINESE_REG.test(ch) || __JAPANESE_REG.test(ch) || __KOREAN_REG.test(ch);
      }
      function isUnicodeSpace(ch) {
        var chCode = ch.charCodeAt(0);
        return chCode >= 9 && chCode <= 13 || chCode === 32 || chCode === 133 || chCode === 160 || chCode === 5760 || chCode >= 8192 && chCode <= 8202 || chCode === 8232 || chCode === 8233 || chCode === 8239 || chCode === 8287 || chCode === 12288;
      }
      function safeMeasureText(ctx, string, desc) {
        var font = desc || ctx.font;
        var key = font + "\uD83C\uDFAE" + string;
        var cache = measureCache.get(key);
        if (cache !== null) {
          return cache;
        }
        var metric = ctx.measureText(string);
        var width = metric && metric.width || 0;
        measureCache.put(key, width);
        return width;
      }
      function _safeSubstring(targetString, startIndex, endIndex) {
        var newStartIndex = startIndex;
        var newEndIndex = endIndex;
        var startChar = targetString[startIndex];
        if (startChar >= "\uDC00" && startChar <= "\uDFFF") {
          newStartIndex--;
        }
        if (endIndex !== undefined) {
          if (endIndex - 1 !== startIndex) {
            var endChar = targetString[endIndex - 1];
            if (endChar >= "\uD800" && endChar <= "\uDBFF") {
              newEndIndex--;
            }
          } else if (startChar >= "\uD800" && startChar <= "\uDBFF") {
            newEndIndex++;
          }
        }
        return targetString.substring(newStartIndex, newEndIndex);
      }
      function isEnglishWordPartAtFirst(stringToken) {
        return FIRST_ENGLISH_REG.test(stringToken);
      }
      function isEnglishWordPartAtLast(stringToken) {
        return LAST_ENGLISH_REG.test(stringToken);
      }
      function getEnglishWordPartAtFirst(stringToken) {
        var result = FIRST_ENGLISH_REG.exec(stringToken);
        return result;
      }
      function getEnglishWordPartAtLast(stringToken) {
        var result = LAST_ENGLISH_REG.exec(stringToken);
        return result;
      }
      function fragmentText(stringToken, allWidth, maxWidth, measureText) {
        var wrappedWords = [];
        if (stringToken.length === 0 || maxWidth < 0) {
          wrappedWords.push('');
          return wrappedWords;
        }
        var text = stringToken;
        while (allWidth > maxWidth && text.length > 1) {
          var fuzzyLen = text.length * (maxWidth / allWidth) | 0;
          var tmpText = _safeSubstring(text, fuzzyLen);
          var width = allWidth - measureText(tmpText);
          var sLine = tmpText;
          var pushNum = 0;
          var checkWhile = 0;
          var checkCount = 100;
          while (width > maxWidth && checkWhile++ < checkCount) {
            fuzzyLen *= maxWidth / width;
            fuzzyLen |= 0;
            tmpText = _safeSubstring(text, fuzzyLen);
            width = allWidth - measureText(tmpText);
          }
          checkWhile = 0;
          while (tmpText && width <= maxWidth && checkWhile++ < checkCount) {
            var exec = WORD_REG.exec(tmpText);
            pushNum = exec ? exec[0].length : 1;
            sLine = tmpText;
            fuzzyLen += pushNum;
            tmpText = _safeSubstring(text, fuzzyLen);
            width = allWidth - measureText(tmpText);
          }
          fuzzyLen -= pushNum;
          if (fuzzyLen === 0) {
            fuzzyLen = 1;
            sLine = _safeSubstring(text, 1);
          } else if (fuzzyLen === 1 && text[0] >= "\uD800" && text[0] <= "\uDBFF") {
            fuzzyLen = 2;
            sLine = _safeSubstring(text, 2);
          }
          var sText = _safeSubstring(text, 0, fuzzyLen);
          var result = void 0;
          {
            if (SYMBOL_REG.test(sLine || tmpText)) {
              result = LAST_WORD_REG.exec(sText);
              fuzzyLen -= result ? result[0].length : 0;
              if (fuzzyLen === 0) {
                fuzzyLen = 1;
              }
              sLine = _safeSubstring(text, fuzzyLen);
              sText = _safeSubstring(text, 0, fuzzyLen);
            }
          }
          if (FIRST_ENGLISH_REG.test(sLine)) {
            result = LAST_ENGLISH_REG.exec(sText);
            if (result && sText !== result[0]) {
              fuzzyLen -= result[0].length;
              sLine = _safeSubstring(text, fuzzyLen);
              sText = _safeSubstring(text, 0, fuzzyLen);
            }
          }
          if (wrappedWords.length === 0) {
            wrappedWords.push(sText);
          } else {
            sText = sText.trim();
            if (sText.length > 0) {
              wrappedWords.push(sText);
            }
          }
          text = sLine || tmpText;
          allWidth = measureText(text);
        }
        if (wrappedWords.length === 0) {
          wrappedWords.push(text);
        } else {
          text = text.trim();
          if (text.length > 0) {
            wrappedWords.push(text);
          }
        }
        return wrappedWords;
      }

      var _canvasPool;
      var CanvasPool = function () {
        function CanvasPool() {
          this.pool = [];
        }
        CanvasPool.getInstance = function getInstance() {
          if (!_canvasPool) {
            _canvasPool = new CanvasPool();
          }
          return _canvasPool;
        };
        var _proto = CanvasPool.prototype;
        _proto.get = function get() {
          var data = this.pool.pop();
          if (!data) {
            var canvas = ccwindow.document.createElement('canvas');
            var context = canvas.getContext('2d');
            data = {
              canvas: canvas,
              context: context
            };
          }
          return data;
        };
        _proto.put = function put(canvas) {
          if (this.pool.length >= macro.MAX_LABEL_CANVAS_POOL_SIZE) {
            return;
          }
          this.pool.push(canvas);
        };
        return CanvasPool;
      }();
      var WHITE$1 = Color$1.WHITE.clone();
      var space = 0;
      var bleed = 2;
      var FontLetterDefinition = function FontLetterDefinition() {
        this.u = 0;
        this.v = 0;
        this.w = 0;
        this.h = 0;
        this.texture = null;
        this.offsetX = 0;
        this.offsetY = 0;
        this.valid = false;
        this.xAdvance = 0;
      };
      var _backgroundStyle = "rgba(255, 255, 255, " + (1 / 255).toFixed(3) + ")";
      var BASELINE_OFFSET = getBaselineOffset();
      var LetterTexture = function () {
        function LetterTexture(_char, labelInfo) {
          this.image = null;
          this.labelInfo = void 0;
          this["char"] = void 0;
          this.data = null;
          this.canvas = null;
          this.context = null;
          this.width = 0;
          this.height = 0;
          this.offsetY = 0;
          this.hash = void 0;
          this["char"] = _char;
          this.labelInfo = labelInfo;
          this.hash = "" + _char.charCodeAt(0) + labelInfo.hash;
        }
        var _proto2 = LetterTexture.prototype;
        _proto2.updateRenderData = function updateRenderData() {
          this._updateProperties();
          this._updateTexture();
        };
        _proto2.destroy = function destroy() {
          this.image = null;
          CanvasPool.getInstance().put(this.data);
        };
        _proto2._updateProperties = function _updateProperties() {
          this.data = CanvasPool.getInstance().get();
          this.canvas = this.data.canvas;
          this.context = this.data.context;
          if (this.context) {
            var fontScale = this.labelInfo.fontScale;
            this.context.font = this.labelInfo.fontDesc;
            var width = safeMeasureText(this.context, this["char"], this.labelInfo.fontDesc);
            var blank = this.labelInfo.margin * 2 + bleed;
            this.width = parseFloat(width.toFixed(2)) * fontScale + blank;
            this.height = (1 + BASELINE_RATIO) * this.labelInfo.fontSize * fontScale + blank;
            this.offsetY = -(this.labelInfo.fontSize * BASELINE_RATIO) * fontScale / 2;
          }
          if (this.canvas.width !== this.width) {
            this.canvas.width = this.width;
          }
          if (this.canvas.height !== this.height) {
            this.canvas.height = this.height;
          }
          if (!this.image) {
            this.image = new ImageAsset();
          }
          this.image.reset(this.canvas);
        };
        _proto2._updateTexture = function _updateTexture() {
          if (!this.context || !this.canvas) {
            return;
          }
          var context = this.context;
          var labelInfo = this.labelInfo;
          var width = this.canvas.width;
          var height = this.canvas.height;
          var fontScale = labelInfo.fontScale;
          context.textAlign = 'center';
          context.textBaseline = 'alphabetic';
          context.clearRect(0, 0, width, height);
          context.fillStyle = _backgroundStyle;
          context.fillRect(0, 0, width, height);
          context.font = labelInfo.fontDesc.replace(/(\d+)(\.\d+)?(px|em|rem|pt)/g, function (w, m, n, u) {
            return (+m * fontScale + (+n || 0) * fontScale).toString() + u;
          });
          var fontSize = labelInfo.fontSize * fontScale;
          var startX = width / 2;
          var startY = height / 2 + fontSize * MIDDLE_RATIO + fontSize * BASELINE_OFFSET;
          var color = labelInfo.color;
          context.lineJoin = 'round';
          context.fillStyle = "rgba(" + color.r + ", " + color.g + ", " + color.b + ", " + 1 + ")";
          if (labelInfo.isOutlined) {
            var strokeColor = labelInfo.out || WHITE$1;
            context.strokeStyle = "rgba(" + strokeColor.r + ", " + strokeColor.g + ", " + strokeColor.b + ", " + strokeColor.a / 255 + ")";
            context.lineWidth = labelInfo.margin * 2 * fontScale;
            context.strokeText(this["char"], startX, startY);
          }
          context.fillText(this["char"], startX, startY);
        };
        return LetterTexture;
      }();
      var LetterRenderTexture = function (_Texture2D) {
        _inheritsLoose(LetterRenderTexture, _Texture2D);
        function LetterRenderTexture() {
          return _Texture2D.apply(this, arguments) || this;
        }
        var _proto3 = LetterRenderTexture.prototype;
        _proto3.initWithSize = function initWithSize(width, height, format) {
          if (format === void 0) {
            format = PixelFormat.RGBA8888;
          }
          this.reset({
            width: width,
            height: height,
            format: format
          });
        };
        _proto3.drawTextureAt = function drawTextureAt(image, x, y) {
          var gfxTexture = this.getGFXTexture();
          if (!image || !gfxTexture) {
            return;
          }
          var gfxDevice = this._getGFXDevice();
          if (!gfxDevice) {
            console.warn('Unable to get device');
            return;
          }
          var region = new BufferTextureCopy();
          region.texOffset.x = x;
          region.texOffset.y = y;
          region.texExtent.width = image.width;
          region.texExtent.height = image.height;
          gfxDevice.copyTexImagesToTexture([image.data], gfxTexture, [region]);
        };
        return LetterRenderTexture;
      }(Texture2D);
      var LetterAtlas = function () {
        function LetterAtlas(width, height) {
          this._x = space;
          this._y = space;
          this._nextY = space;
          this._width = 0;
          this._height = 0;
          this._halfBleed = 0;
          this._dirty = false;
          var texture = new LetterRenderTexture();
          texture.initWithSize(width, height);
          this.fontDefDictionary = new FontAtlas(texture);
          this._halfBleed = bleed / 2;
          this._width = width;
          this._height = height;
          director.on(Director.EVENT_BEFORE_SCENE_LAUNCH, this.beforeSceneLoad, this);
        }
        var _proto4 = LetterAtlas.prototype;
        _proto4.insertLetterTexture = function insertLetterTexture(letterTexture) {
          var texture = letterTexture.image;
          var device = director.root.device;
          if (!texture || !this.fontDefDictionary || !device) {
            return null;
          }
          var width = texture.width;
          var height = texture.height;
          if (this._x + width + space > this._width) {
            this._x = space;
            this._y = this._nextY;
          }
          if (this._y + height > this._nextY) {
            this._nextY = this._y + height + space;
          }
          if (this._nextY > this._height) {
            warnID(12100);
            return null;
          }
          this.fontDefDictionary.texture.drawTextureAt(texture, this._x, this._y);
          this._dirty = true;
          var letterDefinition = new FontLetterDefinition();
          letterDefinition.u = this._x + this._halfBleed;
          letterDefinition.v = this._y + this._halfBleed;
          letterDefinition.texture = this.fontDefDictionary.texture;
          letterDefinition.valid = true;
          letterDefinition.w = letterTexture.width - bleed;
          letterDefinition.h = letterTexture.height - bleed;
          letterDefinition.xAdvance = letterDefinition.w;
          letterDefinition.offsetY = letterTexture.offsetY;
          this._x += width + space;
          this.fontDefDictionary.addLetterDefinitions(letterTexture.hash, letterDefinition);
          return letterDefinition;
        };
        _proto4.update = function update() {
          if (!this._dirty) {
            return;
          }
          this._dirty = false;
        };
        _proto4.reset = function reset() {
          this._x = space;
          this._y = space;
          this._nextY = space;
          this.fontDefDictionary.clear();
        };
        _proto4.destroy = function destroy() {
          this.reset();
          if (this.fontDefDictionary) {
            this.fontDefDictionary.texture.destroy();
            this.fontDefDictionary.texture = null;
          }
        };
        _proto4.getTexture = function getTexture() {
          return this.fontDefDictionary.getTexture();
        };
        _proto4.beforeSceneLoad = function beforeSceneLoad() {
          this.clearAllCache();
        };
        _proto4.clearAllCache = function clearAllCache() {
          this.destroy();
          var texture = new LetterRenderTexture();
          texture.initWithSize(this._width, this._height);
          this.fontDefDictionary.texture = texture;
        };
        _proto4.getLetter = function getLetter(key) {
          return this.fontDefDictionary.letterDefinitions[key];
        };
        _proto4.getLetterDefinitionForChar = function getLetterDefinitionForChar(_char2, labelInfo) {
          var hash = _char2.charCodeAt(0) + labelInfo.hash;
          var letter = this.fontDefDictionary.letterDefinitions[hash];
          if (!letter) {
            var temp = new LetterTexture(_char2, labelInfo);
            temp.updateRenderData();
            letter = this.insertLetterTexture(temp);
            temp.destroy();
          }
          return letter;
        };
        _createClass(LetterAtlas, [{
          key: "width",
          get: function get() {
            return this._width;
          }
        }, {
          key: "height",
          get: function get() {
            return this._height;
          }
        }]);
        return LetterAtlas;
      }();
      var shareLabelInfo = {
        fontAtlas: null,
        fontSize: 0,
        lineHeight: 0,
        hAlign: 0,
        vAlign: 0,
        hash: '',
        fontFamily: '',
        fontDesc: 'Arial',
        color: Color$1.WHITE.clone(),
        isOutlined: false,
        out: Color$1.WHITE.clone(),
        margin: 0,
        fontScale: 1
      };
      function computeHash(labelInfo) {
        var hashData = '';
        var color = labelInfo.color.toHEX();
        var out = '';
        if (labelInfo.isOutlined && labelInfo.margin > 0) {
          out = out + labelInfo.margin + labelInfo.out.toHEX();
        }
        return hashData + labelInfo.fontSize + labelInfo.fontFamily + color + out;
      }

      var vfmt = [new Attribute(AttributeName.ATTR_POSITION, Format.RGB32F)];
      var vfmtPosColor = [new Attribute(AttributeName.ATTR_POSITION, Format.RGB32F), new Attribute(AttributeName.ATTR_COLOR, Format.RGBA32F)];
      var vfmtPosUvColor = [new Attribute(AttributeName.ATTR_POSITION, Format.RGB32F), new Attribute(AttributeName.ATTR_TEX_COORD, Format.RG32F), new Attribute(AttributeName.ATTR_COLOR, Format.RGBA32F)];
      var vfmtPosUvColor4B = [new Attribute(AttributeName.ATTR_POSITION, Format.RGB32F), new Attribute(AttributeName.ATTR_TEX_COORD, Format.RG32F), new Attribute(AttributeName.ATTR_COLOR, Format.RGBA8, true)];
      var vfmtPosUvTwoColor = [new Attribute(AttributeName.ATTR_POSITION, Format.RGB32F), new Attribute(AttributeName.ATTR_TEX_COORD, Format.RG32F), new Attribute(AttributeName.ATTR_COLOR, Format.RGBA32F), new Attribute(AttributeName.ATTR_COLOR2, Format.RGBA32F)];
      var vfmtPosUvTwoColor4B = [new Attribute(AttributeName.ATTR_POSITION, Format.RGB32F), new Attribute(AttributeName.ATTR_TEX_COORD, Format.RG32F), new Attribute(AttributeName.ATTR_COLOR, Format.RGBA8, true), new Attribute(AttributeName.ATTR_COLOR2, Format.RGBA8, true)];
      function getComponentPerVertex(attrs) {
        var count = 0;
        for (var i = 0; i < attrs.length; i++) {
          var attr = attrs[i];
          var info = FormatInfos[attr.format];
          count += info.count;
        }
        return count;
      }
      function getAttributeStride(attrs) {
        var count = 0;
        for (var i = 0; i < attrs.length; i++) {
          var attr = attrs[i];
          var info = FormatInfos[attr.format];
          count += info.size;
        }
        return count;
      }
      legacyCC.internal.vfmtPosUvColor = vfmtPosUvColor;
      legacyCC.internal.vfmtPosUvTwoColor = vfmtPosUvTwoColor;
      legacyCC.internal.vfmtPosUvColor4B = vfmtPosUvColor4B;
      legacyCC.internal.vfmtPosUvTwoColor4B = vfmtPosUvTwoColor4B;

      var MeshBufferSharedBufferView;
      (function (MeshBufferSharedBufferView) {
        MeshBufferSharedBufferView[MeshBufferSharedBufferView["byteOffset"] = 0] = "byteOffset";
        MeshBufferSharedBufferView[MeshBufferSharedBufferView["vertexOffset"] = 1] = "vertexOffset";
        MeshBufferSharedBufferView[MeshBufferSharedBufferView["indexOffset"] = 2] = "indexOffset";
        MeshBufferSharedBufferView[MeshBufferSharedBufferView["dirty"] = 3] = "dirty";
        MeshBufferSharedBufferView[MeshBufferSharedBufferView["count"] = 4] = "count";
      })(MeshBufferSharedBufferView || (MeshBufferSharedBufferView = {}));
      var IA_POOL_USED_SCALE = 1 / 2;
      var MeshBuffer = exports('M', function () {
        var _proto = MeshBuffer.prototype;
        _proto.initSharedBuffer = function initSharedBuffer() {
        };
        _proto.syncSharedBufferToNative = function syncSharedBufferToNative() {
        };
        function MeshBuffer() {
          this._byteOffset = 0;
          this._vertexOffset = 0;
          this._indexOffset = 0;
          this._dirty = false;
          this._floatsPerVertex = 0;
          this._vData = null;
          this._iData = null;
          this._vertexFormatBytes = 0;
          this._initVDataCount = 0;
          this._initIDataCount = 0;
          this._attributes = null;
          this._iaPool = [];
          this._iaInfo = null;
          this._nextFreeIAHandle = 0;
          this.initSharedBuffer();
          this.syncSharedBufferToNative();
        }
        _proto.initialize = function initialize(device, attrs, vFloatCount, iCount) {
          this._initVDataCount = vFloatCount;
          this._initIDataCount = iCount;
          this._attributes = attrs;
          this.floatsPerVertex = getAttributeStride(attrs) >> 2;
          assertIsTrue(this._initVDataCount / this._floatsPerVertex < 65536, getError(9005));
          if (!this.vData || !this.iData) {
            this.vData = new Float32Array(this._initVDataCount);
            this.iData = new Uint16Array(this._initIDataCount);
          }
          this._iaPool.push(this.createNewIA(device));
        };
        _proto.reset = function reset() {
          this._nextFreeIAHandle = 0;
          this.dirty = false;
        };
        _proto.destroy = function destroy() {
          this.reset();
          this._attributes = null;
          this._iaInfo = null;
          this.vData = null;
          this.iData = null;
          for (var i = 0; i < this._iaPool.length; ++i) {
            var iaRef = this._iaPool[i];
            if (iaRef.vertexBuffers[0]) {
              iaRef.vertexBuffers[0].destroy();
            }
            if (iaRef.indexBuffer) {
              iaRef.indexBuffer.destroy();
            }
            iaRef.ia.destroy();
          }
          this._iaPool.length = 0;
        };
        _proto.setDirty = function setDirty() {
          this.dirty = true;
        };
        _proto.request = function request(vertexCount, indexCount) {
          warnID(9002);
          return false;
        };
        _proto.requireFreeIA = function requireFreeIA(device) {
          if (this._iaPool.length <= this._nextFreeIAHandle) {
            this._iaPool.push(this.createNewIA(device));
          }
          var ia = this._iaPool[this._nextFreeIAHandle++].ia;
          return ia;
        };
        _proto.recycleIA = function recycleIA(ia) {
          var pool = this._iaPool;
          for (var i = 0; i < this._nextFreeIAHandle; ++i) {
            if (ia === pool[i].ia) {
              var iaRef = pool[i];
              pool[i] = pool[--this._nextFreeIAHandle];
              pool[this._nextFreeIAHandle] = iaRef;
              return;
            }
          }
        };
        _proto.checkCapacity = function checkCapacity(vertexCount, indexCount) {
          var maxVertex = (this.vertexOffset + vertexCount) * this._floatsPerVertex;
          var maxIndex = this.indexOffset + indexCount;
          if (maxVertex > this._initVDataCount || maxIndex > this._initIDataCount) {
            return false;
          }
          return true;
        };
        _proto.uploadBuffers = function uploadBuffers() {
          if (this.byteOffset === 0 || !this._dirty) {
            return;
          }
          var iOS14 = sys.__isWebIOS14OrIPadOS14Env;
          var submitCount = iOS14 ? this._nextFreeIAHandle : 1;
          if (iOS14 && submitCount / this._iaPool.length < IA_POOL_USED_SCALE) {
            var count = submitCount / IA_POOL_USED_SCALE;
            var length = this._iaPool.length;
            for (var i = length - 1; i >= count; i--) {
              var iaRef = this._iaPool[i];
              if (iaRef.vertexBuffers[0]) {
                iaRef.vertexBuffers[0].destroy();
              }
              if (iaRef.indexBuffer) {
                iaRef.indexBuffer.destroy();
              }
              iaRef.ia.destroy();
            }
            this._iaPool.length = count;
          }
          var byteCount = this.byteOffset;
          var indexCount = this.indexOffset;
          for (var _i = 0; _i < submitCount; ++_i) {
            var _iaRef = this._iaPool[_i];
            var verticesData = new Float32Array(this.vData.buffer, 0, byteCount >> 2);
            var indicesData = new Uint16Array(this.iData.buffer, 0, indexCount);
            var vertexBuffer = _iaRef.vertexBuffers[0];
            if (byteCount > vertexBuffer.size) {
              vertexBuffer.resize(byteCount);
            }
            vertexBuffer.update(verticesData);
            if (indexCount * 2 > _iaRef.indexBuffer.size) {
              _iaRef.indexBuffer.resize(indexCount * 2);
            }
            _iaRef.indexBuffer.update(indicesData);
          }
          this.dirty = false;
        };
        _proto.createNewIA = function createNewIA(device) {
          var ia;
          var vertexBuffers;
          var indexBuffer;
          if (sys.__isWebIOS14OrIPadOS14Env || !this._iaPool[0]) {
            var vbStride = this._vertexFormatBytes = this._floatsPerVertex * Float32Array.BYTES_PER_ELEMENT;
            var ibStride = Uint16Array.BYTES_PER_ELEMENT;
            var vertexBuffer = device.createBuffer(new BufferInfo(BufferUsageBit.VERTEX | BufferUsageBit.TRANSFER_DST, MemoryUsageBit.HOST | MemoryUsageBit.DEVICE, vbStride, vbStride));
            indexBuffer = device.createBuffer(new BufferInfo(BufferUsageBit.INDEX | BufferUsageBit.TRANSFER_DST, MemoryUsageBit.HOST | MemoryUsageBit.DEVICE, ibStride, ibStride));
            vertexBuffers = [vertexBuffer];
            this._iaInfo = new InputAssemblerInfo(this._attributes, vertexBuffers, indexBuffer);
            ia = device.createInputAssembler(this._iaInfo);
          } else {
            ia = device.createInputAssembler(this._iaInfo);
            vertexBuffers = this._iaInfo.vertexBuffers;
            indexBuffer = this._iaInfo.indexBuffer;
          }
          return {
            ia: ia,
            vertexBuffers: vertexBuffers,
            indexBuffer: indexBuffer
          };
        };
        _createClass(MeshBuffer, [{
          key: "attributes",
          get: function get() {
            return this._attributes;
          }
        }, {
          key: "vertexFormatBytes",
          get: function get() {
            return this._vertexFormatBytes;
          }
        }, {
          key: "byteOffset",
          get: function get() {
            return this._byteOffset;
          },
          set: function set(val) {
            this._byteOffset = val;
          }
        }, {
          key: "vertexOffset",
          get: function get() {
            return this._vertexOffset;
          },
          set: function set(val) {
            this._vertexOffset = val;
          }
        }, {
          key: "indexOffset",
          get: function get() {
            return this._indexOffset;
          },
          set: function set(val) {
            this._indexOffset = val;
          }
        }, {
          key: "dirty",
          get: function get() {
            return this._dirty;
          },
          set: function set(val) {
            this._dirty = val;
          }
        }, {
          key: "floatsPerVertex",
          get: function get() {
            return this._floatsPerVertex;
          },
          set: function set(val) {
            this._floatsPerVertex = val;
          }
        }, {
          key: "vData",
          get: function get() {
            return this._vData;
          },
          set: function set(val) {
            this._vData = val;
          }
        }, {
          key: "iData",
          get: function get() {
            return this._iData;
          },
          set: function set(val) {
            this._iData = val;
          }
        }, {
          key: "nativeObj",
          get: function get() {
            return this._nativeObj;
          }
        }, {
          key: "sharedBuffer",
          get: function get() {
            return this._sharedBuffer;
          }
        }]);
        return MeshBuffer;
      }());

      var BufferAccessor = function () {
        function BufferAccessor(device, attributes) {
          this._device = null;
          this._attributes = null;
          this._vertexFormatBytes = void 0;
          this._floatsPerVertex = void 0;
          this._buffers = [];
          this._device = device;
          this._attributes = attributes;
          this._floatsPerVertex = getAttributeStride(attributes) >> 2;
          this._vertexFormatBytes = this._floatsPerVertex * Float32Array.BYTES_PER_ELEMENT;
        }
        var _proto = BufferAccessor.prototype;
        _proto.initialize = function initialize() {};
        _proto.reset = function reset() {};
        _proto.request = function request(vertexCount, indexCount) {
        };
        _proto.appendBuffers = function appendBuffers(vertices, indices) {};
        _proto.uploadBuffers = function uploadBuffers() {};
        _proto.destroy = function destroy() {
          this._attributes.length = 0;
        };
        _createClass(BufferAccessor, [{
          key: "attributes",
          get: function get() {
            return this._attributes;
          }
        }, {
          key: "vertexFormatBytes",
          get: function get() {
            return this._vertexFormatBytes;
          }
        }, {
          key: "floatsPerVertex",
          get: function get() {
            return this._floatsPerVertex;
          }
        }]);
        return BufferAccessor;
      }();

      var _entryPool = new Pool(function () {
        return {
          offset: 0,
          length: 0
        };
      }, 32);
      var StaticVBChunk = function () {
        function StaticVBChunk(vertexAccessor, bufferId, meshBuffer, vertexOffset, vb, indexCount) {
          this._ib = void 0;
          this.vertexAccessor = vertexAccessor;
          this.bufferId = bufferId;
          this.meshBuffer = meshBuffer;
          this.vertexOffset = vertexOffset;
          this.vb = vb;
          this.indexCount = indexCount;
          this._ib = new Uint16Array(indexCount);
          assertIsTrue(meshBuffer === vertexAccessor.getMeshBuffer(bufferId));
        }
        var _proto = StaticVBChunk.prototype;
        _proto.setIndexBuffer = function setIndexBuffer(indices) {
        };
        _createClass(StaticVBChunk, [{
          key: "ib",
          get: function get() {
            return this._ib;
          }
        }]);
        return StaticVBChunk;
      }();
      var StaticVBAccessor = function (_BufferAccessor) {
        _inheritsLoose(StaticVBAccessor, _BufferAccessor);
        function StaticVBAccessor(device, attributes, vCount, iCount) {
          var _this;
          _this = _BufferAccessor.call(this, device, attributes) || this;
          _this._freeLists = [];
          _this._vCount = 0;
          _this._iCount = 0;
          _this._id = 0;
          _this._vCount = vCount || Math.floor(macro.BATCHER2D_MEM_INCREMENT * 1024 / _this._vertexFormatBytes);
          _this._iCount = iCount || _this._vCount * StaticVBAccessor.IB_SCALE;
          _this._id = StaticVBAccessor.generateID();
          _this._allocateBuffer();
          return _this;
        }
        var _proto2 = StaticVBAccessor.prototype;
        _proto2.destroy = function destroy() {
          for (var i = 0; i < this._buffers.length; ++i) {
            this._buffers[i].destroy();
            var freeList = this._freeLists[i];
            for (var j = 0; j < freeList.length; ++j) {
              _entryPool.free(freeList[j]);
            }
          }
          this._buffers.length = 0;
          this._freeLists.length = 0;
          _BufferAccessor.prototype.destroy.call(this);
        };
        _proto2.reset = function reset() {
          for (var i = 0; i < this._buffers.length; ++i) {
            var buffer = this._buffers[i];
            buffer.indexOffset = 0;
            buffer.reset();
          }
        };
        _proto2.getVertexBuffer = function getVertexBuffer(bid) {
          return this._buffers[bid].vData;
        };
        _proto2.getIndexBuffer = function getIndexBuffer(bid) {
          return this._buffers[bid].iData;
        };
        _proto2.getMeshBuffer = function getMeshBuffer(bid) {
          return this._buffers[bid];
        };
        _proto2.uploadBuffers = function uploadBuffers() {
          for (var i = 0; i < this._buffers.length; ++i) {
            var firstEntry = this._freeLists[i][0];
            var buffer = this._buffers[i];
            if (!firstEntry || firstEntry.length < buffer.vData.byteLength) {
              buffer.uploadBuffers();
            }
          }
        };
        _proto2.appendIndices = function appendIndices(bufferId, indices) {
          var buf = this._buffers[bufferId];
          var iCount = indices.length;
          if (iCount) {
            var needLength = buf.indexOffset + indices.length;
            if (buf.iData.length < needLength) {
              var expansionLength = Math.floor(1.25 * needLength);
              var newIData = new Uint16Array(expansionLength);
              newIData.set(buf.iData);
              buf.iData = newIData;
            }
            buf.iData.set(indices, buf.indexOffset);
            buf.indexOffset += indices.length;
          }
        };
        _proto2.allocateChunk = function allocateChunk(vertexCount, indexCount) {
          var byteLength = vertexCount * this.vertexFormatBytes;
          var buf = null;
          var freeList;
          var bid = 0;
          var eid = -1;
          var entry = null;
          for (var i = 0; i < this._buffers.length; ++i) {
            buf = this._buffers[i];
            freeList = this._freeLists[i];
            for (var e = 0; e < freeList.length; ++e) {
              if (freeList[e].length >= byteLength) {
                entry = freeList[e];
                bid = i;
                eid = e;
                break;
              }
            }
            if (entry) break;
          }
          if (!entry) {
            bid = this._allocateBuffer();
            buf = this._buffers[bid];
            if (buf && buf.checkCapacity(vertexCount, indexCount)) {
              eid = 0;
              entry = this._freeLists[bid][eid];
            }
          }
          if (entry) {
            var _vertexOffset = entry.offset / this.vertexFormatBytes;
            assertIsTrue(Number.isInteger(_vertexOffset));
            var _vb = new Float32Array(buf.vData.buffer, entry.offset, byteLength >> 2).fill(0);
            this._allocateChunkFromEntry(bid, eid, entry, byteLength);
            return new StaticVBChunk(this, bid, buf, _vertexOffset, _vb, indexCount);
          } else {
            errorID(9004, byteLength);
            return null;
          }
        };
        _proto2.recycleChunk = function recycleChunk(chunk) {
          var freeList = this._freeLists[chunk.bufferId];
          var buf = this._buffers[chunk.bufferId];
          var offset = chunk.vertexOffset * this.vertexFormatBytes;
          var bytes = chunk.vb.byteLength;
          if (bytes === 0) return;
          var recycled = false;
          var i = 0;
          var prevEntry = null;
          var nextEntry = freeList[i];
          while (nextEntry && nextEntry.offset < offset) {
            prevEntry = nextEntry;
            nextEntry = freeList[++i];
          }
          if (prevEntry) {
            var distance = offset - (prevEntry.offset + prevEntry.length);
            assertIsTrue(distance >= 0);
            if (distance === 0) {
              prevEntry.length += bytes;
              offset = prevEntry.offset;
              bytes = prevEntry.length;
              if (nextEntry && nextEntry.offset - (offset + bytes) === 0) {
                prevEntry.length += nextEntry.length;
                freeList.splice(i, 1);
                _entryPool.free(nextEntry);
                nextEntry = null;
              }
              recycled = true;
            }
          }
          if (!recycled && nextEntry) {
            var _distance = nextEntry.offset - (offset + bytes);
            assertIsTrue(_distance >= 0);
            if (_distance === 0) {
              nextEntry.offset = offset;
              nextEntry.length += bytes;
            } else {
              var newEntry = _entryPool.alloc();
              newEntry.offset = offset;
              newEntry.length = bytes;
              freeList.splice(i, 0, newEntry);
            }
            recycled = true;
          }
          if (recycled) {
            if (offset + bytes === buf.byteOffset) {
              buf.byteOffset = offset;
            }
          } else {
            var _newEntry = _entryPool.alloc();
            _newEntry.offset = offset;
            _newEntry.length = bytes;
            freeList.push(_newEntry);
          }
        };
        _proto2._allocateChunkFromEntry = function _allocateChunkFromEntry(bid, eid, entry, bytes) {
          var remaining = entry.length - bytes;
          var offset = entry.offset + bytes;
          var buf = this._buffers[bid];
          if (buf.byteOffset < offset) {
            buf.byteOffset = offset;
          }
          assertID(remaining >= 0, 9004, bid, entry.offset, entry.length);
          if (remaining === 0) {
            this._freeLists[bid].splice(eid, 1);
            _entryPool.free(entry);
          } else {
            entry.offset += bytes;
            entry.length = remaining;
          }
        };
        _proto2._allocateBuffer = function _allocateBuffer() {
          assertID(this._buffers.length === this._freeLists.length, 9003);
          var buffer = new MeshBuffer();
          var vFloatCount = this._vCount * this._floatsPerVertex;
          buffer.initialize(this._device, this._attributes, vFloatCount, this._iCount);
          this._buffers.push(buffer);
          var entry = _entryPool.alloc();
          entry.offset = 0;
          entry.length = buffer.vData.byteLength;
          var freeList = [entry];
          this._freeLists.push(freeList);
          var batcher = director.root.batcher2D;
          batcher.syncMeshBuffersToNative(this.id, this._buffers);
          return this._buffers.length - 1;
        };
        StaticVBAccessor.generateID = function generateID() {
          return StaticVBAccessor.ID_COUNT++;
        };
        _createClass(StaticVBAccessor, [{
          key: "id",
          get: function get() {
            return this._id;
          }
        }]);
        return StaticVBAccessor;
      }(BufferAccessor);
      StaticVBAccessor.IB_SCALE = 4;
      StaticVBAccessor.ID_COUNT = 0;

      var AttrUInt8ArrayView;
      (function (AttrUInt8ArrayView) {
        AttrUInt8ArrayView[AttrUInt8ArrayView["DrawInfoType"] = 0] = "DrawInfoType";
        AttrUInt8ArrayView[AttrUInt8ArrayView["VertDirty"] = 1] = "VertDirty";
        AttrUInt8ArrayView[AttrUInt8ArrayView["IsMeshBuffer"] = 2] = "IsMeshBuffer";
        AttrUInt8ArrayView[AttrUInt8ArrayView["Stride"] = 3] = "Stride";
        AttrUInt8ArrayView[AttrUInt8ArrayView["Count"] = 4] = "Count";
      })(AttrUInt8ArrayView || (AttrUInt8ArrayView = {}));
      var AttrUInt16ArrayView;
      (function (AttrUInt16ArrayView) {
        AttrUInt16ArrayView[AttrUInt16ArrayView["BufferID"] = 0] = "BufferID";
        AttrUInt16ArrayView[AttrUInt16ArrayView["AccessorID"] = 1] = "AccessorID";
        AttrUInt16ArrayView[AttrUInt16ArrayView["Count"] = 2] = "Count";
      })(AttrUInt16ArrayView || (AttrUInt16ArrayView = {}));
      var AttrUInt32ArrayView;
      (function (AttrUInt32ArrayView) {
        AttrUInt32ArrayView[AttrUInt32ArrayView["VertexOffset"] = 0] = "VertexOffset";
        AttrUInt32ArrayView[AttrUInt32ArrayView["IndexOffset"] = 1] = "IndexOffset";
        AttrUInt32ArrayView[AttrUInt32ArrayView["VBCount"] = 2] = "VBCount";
        AttrUInt32ArrayView[AttrUInt32ArrayView["IBCount"] = 3] = "IBCount";
        AttrUInt32ArrayView[AttrUInt32ArrayView["DataHash"] = 4] = "DataHash";
        AttrUInt32ArrayView[AttrUInt32ArrayView["Count"] = 5] = "Count";
      })(AttrUInt32ArrayView || (AttrUInt32ArrayView = {}));
      var RenderDrawInfoType;
      (function (RenderDrawInfoType) {
        RenderDrawInfoType[RenderDrawInfoType["COMP"] = 0] = "COMP";
        RenderDrawInfoType[RenderDrawInfoType["MODEL"] = 1] = "MODEL";
        RenderDrawInfoType[RenderDrawInfoType["MIDDLEWARE"] = 2] = "MIDDLEWARE";
        RenderDrawInfoType[RenderDrawInfoType["SUB_NODE"] = 3] = "SUB_NODE";
      })(RenderDrawInfoType || (RenderDrawInfoType = {}));
      (function () {
        function RenderDrawInfo(nativeDrawInfo) {
          this._accId = -1;
          this._bufferId = -1;
          this._vertexOffset = 0;
          this._indexOffset = 0;
          this._vb = null;
          this._ib = null;
          this._vData = null;
          this._iData = null;
          this._vertDirty = false;
          this._vbCount = 0;
          this._ibCount = 0;
          this._dataHash = 0;
          this._isMeshBuffer = false;
          this._material = null;
          this._texture = null;
          this._sampler = null;
          this._stride = 0;
          this._useLocal = false;
          this._model = null;
          this._drawInfoType = RenderDrawInfoType.COMP;
          this._subNode = null;
          this._uint8SharedBuffer = void 0;
          this._uint16SharedBuffer = void 0;
          this._uint32SharedBuffer = void 0;
          this.init(nativeDrawInfo);
          var attrSharedBuffer = this._nativeObj.getAttrSharedBufferForJS();
          var offset = 0;
          this._uint8SharedBuffer = new Uint8Array(attrSharedBuffer, offset, AttrUInt8ArrayView.Count);
          offset += AttrUInt8ArrayView.Count * Uint8Array.BYTES_PER_ELEMENT;
          this._uint16SharedBuffer = new Uint16Array(attrSharedBuffer, offset, AttrUInt16ArrayView.Count);
          offset += AttrUInt16ArrayView.Count * Uint16Array.BYTES_PER_ELEMENT;
          this._uint32SharedBuffer = new Uint32Array(attrSharedBuffer, offset, AttrUInt32ArrayView.Count);
        }
        var _proto = RenderDrawInfo.prototype;
        _proto.init = function init(nativeDrawInfo) {
        };
        _proto.clear = function clear() {
          this._bufferId = 0;
          this._vertexOffset = 0;
          this._indexOffset = 0;
          this._vertDirty = false;
        };
        _proto.setAccId = function setAccId(accId) {
          this._accId = accId;
        };
        _proto.setBufferId = function setBufferId(bufferId) {
          this._bufferId = bufferId;
        };
        _proto.setAccAndBuffer = function setAccAndBuffer(accId, bufferId) {
          this._bufferId = bufferId;
          this._accId = accId;
        };
        _proto.setVertexOffset = function setVertexOffset(vertexOffset) {
          this._vertexOffset = vertexOffset;
        };
        _proto.setIndexOffset = function setIndexOffset(indexOffset) {
          this._indexOffset = indexOffset;
        };
        _proto.setVB = function setVB(vbBuffer) {
        };
        _proto.setIB = function setIB(ibBuffer) {
        };
        _proto.setVData = function setVData(vDataBuffer) {
        };
        _proto.setIData = function setIData(iDataBuffer) {
        };
        _proto.setVBCount = function setVBCount(vbCount) {
          this._vbCount = vbCount;
        };
        _proto.setIBCount = function setIBCount(ibCount) {
        };
        _proto.setVertDirty = function setVertDirty(val) {
          this._vertDirty = val;
        };
        _proto.setDataHash = function setDataHash(dataHash) {
          this._dataHash = dataHash;
        };
        _proto.setIsMeshBuffer = function setIsMeshBuffer(isMeshBuffer) {
          this._isMeshBuffer = isMeshBuffer;
        };
        _proto.setMaterial = function setMaterial(material) {
          this._material = material;
        };
        _proto.setTexture = function setTexture(texture) {
          this._texture = texture;
        };
        _proto.setSampler = function setSampler(sampler) {
          this._sampler = sampler;
        };
        _proto.setModel = function setModel(model) {
        };
        _proto.setDrawInfoType = function setDrawInfoType(drawInfoType) {
          this._drawInfoType = drawInfoType;
        };
        _proto.setSubNode = function setSubNode(node) {
          this._subNode = node;
        };
        _proto.setStride = function setStride(stride) {
          this._stride = stride;
        };
        _proto.initRender2dBuffer = function initRender2dBuffer() {
        };
        _proto.fillRender2dBuffer = function fillRender2dBuffer(vertexDataArr) {
        };
        _createClass(RenderDrawInfo, [{
          key: "nativeObj",
          get: function get() {
            return this._nativeObj;
          }
        }, {
          key: "render2dBuffer",
          get: function get() {
            return this._render2dBuffer;
          }
        }]);
        return RenderDrawInfo;
      })();

      var Stage;
      (function (Stage) {
        Stage[Stage["DISABLED"] = 0] = "DISABLED";
        Stage[Stage["CLEAR"] = 1] = "CLEAR";
        Stage[Stage["ENTER_LEVEL"] = 2] = "ENTER_LEVEL";
        Stage[Stage["ENABLED"] = 3] = "ENABLED";
        Stage[Stage["EXIT_LEVEL"] = 4] = "EXIT_LEVEL";
        Stage[Stage["CLEAR_INVERTED"] = 5] = "CLEAR_INVERTED";
        Stage[Stage["ENTER_LEVEL_INVERTED"] = 6] = "ENTER_LEVEL_INVERTED";
      })(Stage || (Stage = {}));
      var StencilSharedBufferView;
      (function (StencilSharedBufferView) {
        StencilSharedBufferView[StencilSharedBufferView["stencilTest"] = 0] = "stencilTest";
        StencilSharedBufferView[StencilSharedBufferView["func"] = 1] = "func";
        StencilSharedBufferView[StencilSharedBufferView["stencilMask"] = 2] = "stencilMask";
        StencilSharedBufferView[StencilSharedBufferView["writeMask"] = 3] = "writeMask";
        StencilSharedBufferView[StencilSharedBufferView["failOp"] = 4] = "failOp";
        StencilSharedBufferView[StencilSharedBufferView["zFailOp"] = 5] = "zFailOp";
        StencilSharedBufferView[StencilSharedBufferView["passOp"] = 6] = "passOp";
        StencilSharedBufferView[StencilSharedBufferView["ref"] = 7] = "ref";
        StencilSharedBufferView[StencilSharedBufferView["count"] = 8] = "count";
      })(StencilSharedBufferView || (StencilSharedBufferView = {}));
      var StencilManager = exports('S', function () {
        function StencilManager() {
          this._maskStack = [];
          this._stencilPattern = {
            stencilTest: true,
            func: ComparisonFunc.ALWAYS,
            stencilMask: 0xffff,
            writeMask: 0xffff,
            failOp: StencilOp.KEEP,
            zFailOp: StencilOp.KEEP,
            passOp: StencilOp.KEEP,
            ref: 1
          };
          this._stage = Stage.DISABLED;
          this.stencilStateMap = new Map();
          this.stencilStateMapWithDepth = new Map();
        }
        var _proto = StencilManager.prototype;
        _proto.pushMask = function pushMask(mask) {
          this._maskStack.push(mask);
        };
        _proto.clear = function clear(comp) {
          var isInverted = comp.stencilStage !== Stage.ENTER_LEVEL;
          return isInverted ? Stage.CLEAR_INVERTED : Stage.CLEAR;
        };
        _proto.enableMask = function enableMask() {
          this.stage = Stage.ENABLED;
        };
        _proto.exitMask = function exitMask() {
          if (this._maskStack.length === 0) {
            return;
          }
          this._maskStack.pop();
          if (this._maskStack.length === 0) {
            this.stage = Stage.DISABLED;
          } else {
            this.stage = Stage.ENABLED;
          }
        };
        _proto.getWriteMask = function getWriteMask() {
          return 1 << this._maskStack.length - 1;
        };
        _proto.getExitWriteMask = function getExitWriteMask() {
          return 1 << this._maskStack.length;
        };
        _proto.getStencilRef = function getStencilRef() {
          var result = 0;
          for (var i = 0; i < this._maskStack.length; ++i) {
            result += 0x00000001 << i;
          }
          return result;
        };
        _proto.getMaskStackSize = function getMaskStackSize() {
          return this._maskStack.length;
        };
        _proto.reset = function reset() {
          this._maskStack.length = 0;
          this.stage = Stage.DISABLED;
        };
        _proto.destroy = function destroy() {
          this.stencilStateMap.forEach(function (value, key) {
            value.destroy();
          });
          this.stencilStateMap.clear();
        };
        _proto.getStencilStage = function getStencilStage(stage, mat) {
          var key = 0;
          var depthTest = false;
          var depthWrite = false;
          var depthFunc = ComparisonFunc.LESS;
          var cacheMap = this.stencilStateMap;
          if (mat && mat.passes[0]) {
            var pass = mat.passes[0];
            var dss = pass.depthStencilState;
            var depthTestValue = 0;
            var depthWriteValue = 0;
            if (dss.depthTest) depthTestValue = 1;
            if (dss.depthWrite) depthWriteValue = 1;
            key = depthTestValue | depthWriteValue << 1 | dss.depthFunc << 2 | stage << 6 | this._maskStack.length << 9;
            depthTest = dss.depthTest;
            depthWrite = dss.depthWrite;
            depthFunc = dss.depthFunc;
            cacheMap = this.stencilStateMapWithDepth;
          } else {
            key = stage << 16 | this._maskStack.length;
          }
          if (cacheMap && cacheMap.has(key)) {
            return cacheMap.get(key);
          }
          this.setStateFromStage(stage);
          var depthStencilState = new DepthStencilState(depthTest, depthWrite, depthFunc, this._stencilPattern.stencilTest, this._stencilPattern.func, this._stencilPattern.stencilMask, this._stencilPattern.writeMask, this._stencilPattern.failOp, this._stencilPattern.zFailOp, this._stencilPattern.passOp, this._stencilPattern.ref, this._stencilPattern.stencilTest, this._stencilPattern.func, this._stencilPattern.stencilMask, this._stencilPattern.writeMask, this._stencilPattern.failOp, this._stencilPattern.zFailOp, this._stencilPattern.passOp, this._stencilPattern.ref);
          cacheMap.set(key, depthStencilState);
          return depthStencilState;
        };
        _proto.getStencilHash = function getStencilHash(stage) {
          return stage << 8 | this._maskStack.length;
        };
        _proto.setStateFromStage = function setStateFromStage(stage) {
          var pattern = this._stencilPattern;
          if (stage === Stage.DISABLED) {
            pattern.stencilTest = false;
            pattern.func = ComparisonFunc.ALWAYS;
            pattern.failOp = StencilOp.KEEP;
            pattern.stencilMask = pattern.writeMask = 0xffff;
            pattern.ref = 1;
          } else {
            pattern.stencilTest = true;
            if (stage === Stage.ENABLED) {
              pattern.func = ComparisonFunc.EQUAL;
              pattern.failOp = StencilOp.KEEP;
              pattern.stencilMask = pattern.ref = this.getStencilRef();
              pattern.writeMask = this.getWriteMask();
            } else if (stage === Stage.CLEAR) {
              pattern.func = ComparisonFunc.NEVER;
              pattern.failOp = StencilOp.ZERO;
              pattern.writeMask = pattern.stencilMask = pattern.ref = this.getWriteMask();
            } else if (stage === Stage.CLEAR_INVERTED) {
              pattern.func = ComparisonFunc.NEVER;
              pattern.failOp = StencilOp.REPLACE;
              pattern.writeMask = pattern.stencilMask = pattern.ref = this.getWriteMask();
            } else if (stage === Stage.ENTER_LEVEL) {
              pattern.func = ComparisonFunc.NEVER;
              pattern.failOp = StencilOp.REPLACE;
              pattern.writeMask = pattern.stencilMask = pattern.ref = this.getWriteMask();
            } else if (stage === Stage.ENTER_LEVEL_INVERTED) {
              pattern.func = ComparisonFunc.NEVER;
              pattern.failOp = StencilOp.ZERO;
              pattern.writeMask = pattern.stencilMask = pattern.ref = this.getWriteMask();
            }
          }
        };
        _createClass(StencilManager, [{
          key: "stage",
          get: function get() {
            return this._stage;
          },
          set: function set(val) {
            this._stage = val;
          }
        }, {
          key: "pattern",
          get: function get() {
            return this._stencilPattern;
          }
        }]);
        return StencilManager;
      }());
      StencilManager.sharedManager = null;
      StencilManager.sharedManager = new StencilManager();

      var RenderEntityType;
      (function (RenderEntityType) {
        RenderEntityType[RenderEntityType["STATIC"] = 0] = "STATIC";
        RenderEntityType[RenderEntityType["DYNAMIC"] = 1] = "DYNAMIC";
        RenderEntityType[RenderEntityType["CROSSED"] = 2] = "CROSSED";
      })(RenderEntityType || (RenderEntityType = {}));
      var RenderEntityFloatSharedBufferView;
      (function (RenderEntityFloatSharedBufferView) {
        RenderEntityFloatSharedBufferView[RenderEntityFloatSharedBufferView["localOpacity"] = 0] = "localOpacity";
        RenderEntityFloatSharedBufferView[RenderEntityFloatSharedBufferView["count"] = 1] = "count";
      })(RenderEntityFloatSharedBufferView || (RenderEntityFloatSharedBufferView = {}));
      var RenderEntityUInt8SharedBufferView;
      (function (RenderEntityUInt8SharedBufferView) {
        RenderEntityUInt8SharedBufferView[RenderEntityUInt8SharedBufferView["colorR"] = 0] = "colorR";
        RenderEntityUInt8SharedBufferView[RenderEntityUInt8SharedBufferView["colorG"] = 1] = "colorG";
        RenderEntityUInt8SharedBufferView[RenderEntityUInt8SharedBufferView["colorB"] = 2] = "colorB";
        RenderEntityUInt8SharedBufferView[RenderEntityUInt8SharedBufferView["colorA"] = 3] = "colorA";
        RenderEntityUInt8SharedBufferView[RenderEntityUInt8SharedBufferView["maskMode"] = 4] = "maskMode";
        RenderEntityUInt8SharedBufferView[RenderEntityUInt8SharedBufferView["count"] = 5] = "count";
      })(RenderEntityUInt8SharedBufferView || (RenderEntityUInt8SharedBufferView = {}));
      var RenderEntityBoolSharedBufferView;
      (function (RenderEntityBoolSharedBufferView) {
        RenderEntityBoolSharedBufferView[RenderEntityBoolSharedBufferView["colorDirty"] = 0] = "colorDirty";
        RenderEntityBoolSharedBufferView[RenderEntityBoolSharedBufferView["enabled"] = 1] = "enabled";
        RenderEntityBoolSharedBufferView[RenderEntityBoolSharedBufferView["useLocal"] = 2] = "useLocal";
        RenderEntityBoolSharedBufferView[RenderEntityBoolSharedBufferView["count"] = 3] = "count";
      })(RenderEntityBoolSharedBufferView || (RenderEntityBoolSharedBufferView = {}));
      var MaskMode;
      (function (MaskMode) {
        MaskMode[MaskMode["NONE"] = 0] = "NONE";
        MaskMode[MaskMode["MASK"] = 1] = "MASK";
        MaskMode[MaskMode["MASK_INVERTED"] = 2] = "MASK_INVERTED";
        MaskMode[MaskMode["MASK_NODE"] = 3] = "MASK_NODE";
        MaskMode[MaskMode["MASK_NODE_INVERTED"] = 4] = "MASK_NODE_INVERTED";
      })(MaskMode || (MaskMode = {}));
      var RenderEntity = function () {
        function RenderEntity(entityType) {
          this._renderEntityType = RenderEntityType.STATIC;
          this._dynamicDrawInfoArr = [];
          this._node = null;
          this._renderTransform = null;
          this._stencilStage = Stage.DISABLED;
          this._useLocal = false;
          this._maskMode = MaskMode.NONE;
          this._color = Color$1.WHITE;
          this._localOpacity = 255;
          this._colorDirty = true;
          this._enabled = false;
        }
        var _proto = RenderEntity.prototype;
        _proto.addDynamicRenderDrawInfo = function addDynamicRenderDrawInfo(renderDrawInfo) {
        };
        _proto.removeDynamicRenderDrawInfo = function removeDynamicRenderDrawInfo() {
        };
        _proto.clearDynamicRenderDrawInfos = function clearDynamicRenderDrawInfos() {
        };
        _proto.clearStaticRenderDrawInfos = function clearStaticRenderDrawInfos() {
        };
        _proto.setDynamicRenderDrawInfo = function setDynamicRenderDrawInfo(renderDrawInfo, index) {
        };
        _proto.setMaskMode = function setMaskMode(mode) {
          this._maskMode = mode;
        };
        _proto.getStaticRenderDrawInfo = function getStaticRenderDrawInfo() {
          return null;
        };
        _proto.setNode = function setNode(node) {
          this._node = node;
        };
        _proto.setRenderTransform = function setRenderTransform(renderTransform) {
          this._renderTransform = renderTransform;
        };
        _proto.setStencilStage = function setStencilStage(stage) {
          this._stencilStage = stage;
        };
        _proto.setUseLocal = function setUseLocal(useLocal) {
          this._useLocal = useLocal;
        };
        _proto.initSharedBuffer = function initSharedBuffer() {
        };
        _createClass(RenderEntity, [{
          key: "nativeObj",
          get: function get() {
            return this._nativeObj;
          }
        }, {
          key: "renderDrawInfoArr",
          get: function get() {
            return this._dynamicDrawInfoArr;
          }
        }, {
          key: "renderEntityType",
          get: function get() {
            return this._renderEntityType;
          }
        }, {
          key: "color",
          get: function get() {
            return this._color;
          },
          set: function set(val) {
            this._color = val;
          }
        }, {
          key: "localOpacity",
          get: function get() {
            return this._localOpacity;
          },
          set: function set(val) {
            this._localOpacity = val;
          }
        }, {
          key: "colorDirty",
          get: function get() {
            return this._colorDirty;
          },
          set: function set(val) {
            this._colorDirty = val;
          }
        }, {
          key: "enabled",
          get: function get() {
            return this._enabled;
          },
          set: function set(val) {
            this._enabled = val;
          }
        }]);
        return RenderEntity;
      }();

      var DEFAULT_STRIDE = getAttributeStride(vfmtPosUvColor) >> 2;
      var BaseRenderData = exports('t', function () {
        function BaseRenderData(vertexFormat) {
          if (vertexFormat === void 0) {
            vertexFormat = vfmtPosUvColor;
          }
          this.chunk = null;
          this._renderDrawInfo = null;
          this._material = null;
          this._dataHash = 0;
          this._isMeshBuffer = false;
          this._vc = 0;
          this._ic = 0;
          this._floatStride = 0;
          this._vertexFormat = vfmtPosUvColor;
          this._drawInfoType = RenderDrawInfoType.COMP;
          this._multiOwner = false;
          this._batcher = null;
          this._floatStride = vertexFormat === vfmtPosUvColor ? DEFAULT_STRIDE : getAttributeStride(vertexFormat) >> 2;
          this._vertexFormat = vertexFormat;
        }
        var _proto = BaseRenderData.prototype;
        _proto.isValid = function isValid() {
          return this._ic > 0 && this.chunk.vertexAccessor;
        };
        _proto.initRenderDrawInfo = function initRenderDrawInfo(comp, drawInfoType) {
          if (drawInfoType === void 0) {
            drawInfoType = RenderDrawInfoType.COMP;
          }
        };
        _proto.removeRenderDrawInfo = function removeRenderDrawInfo(comp) {
        };
        _proto.setRenderDrawInfoAttributes = function setRenderDrawInfoAttributes() {
        };
        _createClass(BaseRenderData, [{
          key: "vertexCount",
          get: function get() {
            return this._vc;
          }
        }, {
          key: "indexCount",
          get: function get() {
            return this._ic;
          }
        }, {
          key: "stride",
          get: function get() {
            return this._floatStride << 2;
          }
        }, {
          key: "floatStride",
          get: function get() {
            return this._floatStride;
          }
        }, {
          key: "vertexFormat",
          get: function get() {
            return this._vertexFormat;
          }
        }, {
          key: "drawInfoType",
          get: function get() {
            return this._drawInfoType;
          },
          set: function set(type) {
            this._drawInfoType = type;
            if (this._renderDrawInfo) {
              this._renderDrawInfo.setDrawInfoType(type);
            }
          }
        }, {
          key: "renderDrawInfo",
          get: function get() {
            return this._renderDrawInfo;
          }
        }, {
          key: "material",
          get: function get() {
            return this._material;
          },
          set: function set(val) {
            this._material = val;
            if (this._renderDrawInfo) {
              this._renderDrawInfo.setMaterial(val);
            }
          }
        }, {
          key: "dataHash",
          get: function get() {
            return this._dataHash;
          },
          set: function set(val) {
            this._dataHash = val;
            if (this._renderDrawInfo) {
              this._renderDrawInfo.setDataHash(val);
            }
          }
        }, {
          key: "multiOwner",
          get: function get() {
            return this._multiOwner;
          },
          set: function set(val) {
            this._multiOwner = val;
          }
        }, {
          key: "batcher",
          get: function get() {
            if (!this._batcher) {
              this._batcher = director.root.batcher2D;
            }
            return this._batcher;
          }
        }]);
        return BaseRenderData;
      }());
      var RenderData = exports('u', function (_BaseRenderData) {
        _inheritsLoose(RenderData, _BaseRenderData);
        RenderData.add = function add(vertexFormat, accessor) {
          if (vertexFormat === void 0) {
            vertexFormat = vfmtPosUvColor;
          }
          var rd = new RenderData(vertexFormat, accessor);
          if (!accessor) {
            var batcher = director.root.batcher2D;
            accessor = batcher.switchBufferAccessor(rd._vertexFormat);
          }
          rd._accessor = accessor;
          return rd;
        };
        RenderData.remove = function remove(data) {
          data.clear();
          data._accessor = null;
        };
        function RenderData(vertexFormat, accessor) {
          var _this;
          if (vertexFormat === void 0) {
            vertexFormat = vfmtPosUvColor;
          }
          _this = _BaseRenderData.call(this, vertexFormat) || this;
          _this._vertDirty = true;
          _this._textureHash = 0;
          _this.indices = null;
          _this.layer = 0;
          _this.nodeDirty = true;
          _this.passDirty = true;
          _this.textureDirty = true;
          _this.hashDirty = true;
          _this._data = [];
          _this._frame = null;
          _this._accessor = null;
          _this.vertexRow = 1;
          _this.vertexCol = 1;
          if (!accessor) {
            accessor = _this.batcher.switchBufferAccessor(_this._vertexFormat);
          }
          _this._accessor = accessor;
          return _this;
        }
        var _proto2 = RenderData.prototype;
        _proto2.resize = function resize(vertexCount, indexCount) {
          if (vertexCount === this._vc && indexCount === this._ic && this.chunk) return;
          this._vc = vertexCount;
          this._ic = indexCount;
          if (this.chunk) {
            this._accessor.recycleChunk(this.chunk);
            this.chunk = null;
          }
          this.chunk = this._accessor.allocateChunk(vertexCount, indexCount);
          this.updateHash();
        };
        _proto2.setRenderDrawInfoAttributes = function setRenderDrawInfoAttributes() {
        };
        _proto2.fillDrawInfoAttributes = function fillDrawInfoAttributes(drawInfo) {
        };
        _proto2.syncRender2dBuffer = function syncRender2dBuffer() {
        };
        _proto2.resizeAndCopy = function resizeAndCopy(vertexCount, indexCount) {
          if (vertexCount === this._vc && indexCount === this._ic && this.chunk) return;
          this._vc = vertexCount;
          this._ic = indexCount;
          var oldChunk = this.chunk;
          this.chunk = this._accessor.allocateChunk(vertexCount, indexCount);
          if (oldChunk) {
            this.chunk.vb.set(oldChunk.vb);
            this._accessor.recycleChunk(oldChunk);
          }
          this.updateHash();
        };
        _proto2.getMeshBuffer = function getMeshBuffer() {
          if (this.chunk && this._accessor) {
            return this._accessor.getMeshBuffer(this.chunk.bufferId);
          } else {
            return null;
          }
        };
        _proto2.updateNode = function updateNode(comp) {
          this.layer = comp.node.layer;
          this.nodeDirty = false;
          this.hashDirty = true;
        };
        _proto2.updatePass = function updatePass(comp) {
          this.material = comp.getRenderMaterial(0);
          this.passDirty = false;
          this.hashDirty = true;
        };
        _proto2.updateTexture = function updateTexture(frame) {
          this.frame = frame;
          this.textureHash = frame.getHash();
          this.textureDirty = false;
          this.hashDirty = true;
        };
        _proto2.updateHash = function updateHash() {
          var bid = this.chunk ? this.chunk.bufferId : -1;
          var hashString = "" + bid + this.layer + " " + this.textureHash;
          this.dataHash = murmurhash2_32_gc(hashString, 666);
          this.hashDirty = false;
        };
        _proto2.updateRenderData = function updateRenderData(comp, frame) {
          if (this.passDirty) {
            this.material = comp.getRenderMaterial(0);
            this.passDirty = false;
            this.hashDirty = true;
            if (this._renderDrawInfo) {
              this._renderDrawInfo.setMaterial(this.material);
            }
          }
          if (this.nodeDirty) {
            var renderScene = comp.node.scene ? comp._getRenderScene() : null;
            this.layer = comp.node.layer;
            if (renderScene !== null) {
              this.nodeDirty = false;
            }
            this.hashDirty = true;
          }
          if (this.textureDirty) {
            this.frame = frame;
            this.textureHash = frame.getHash();
            this.textureDirty = false;
            this.hashDirty = true;
            if (this._renderDrawInfo) {
              this._renderDrawInfo.setTexture(this.frame ? this.frame.getGFXTexture() : null);
              this._renderDrawInfo.setSampler(this.frame ? this.frame.getGFXSampler() : null);
            }
          }
          if (this.hashDirty) {
            this.updateHash();
            if (this._renderDrawInfo) {
              this._renderDrawInfo.setDataHash(this.dataHash);
            }
          }
        };
        _proto2.clear = function clear() {
          this.resize(0, 0);
          this._data.length = 0;
          this.indices = null;
          this.vertDirty = true;
          this.material = null;
          this.nodeDirty = true;
          this.passDirty = true;
          this.textureDirty = true;
          this.hashDirty = true;
          this.layer = 0;
          this.frame = null;
          this.textureHash = 0;
          this.dataHash = 0;
        };
        RenderData.createStaticVBAccessor = function createStaticVBAccessor(attributes, vCount, iCount) {
          var device = director.root.device;
          var accessor = new StaticVBAccessor(device, attributes, vCount, iCount);
          return accessor;
        };
        _createClass(RenderData, [{
          key: "dataLength",
          get: function get() {
            return this._data.length;
          },
          set: function set(length) {
            var data = this._data;
            if (data.length !== length) {
              for (var i = data.length; i < length; i++) {
                data.push({
                  x: 0,
                  y: 0,
                  z: 0,
                  u: 0,
                  v: 0,
                  color: Color$1.WHITE.clone()
                });
              }
              data.length = length;
            }
            this.syncRender2dBuffer();
          }
        }, {
          key: "data",
          get: function get() {
            return this._data;
          }
        }, {
          key: "vertDirty",
          get: function get() {
            return this._vertDirty;
          },
          set: function set(val) {
            this._vertDirty = val;
            if (this._renderDrawInfo && val) {
              this._renderDrawInfo.setVertDirty(val);
            }
          }
        }, {
          key: "textureHash",
          get: function get() {
            return this._textureHash;
          },
          set: function set(val) {
            this._textureHash = val;
          }
        }, {
          key: "frame",
          get: function get() {
            return this._frame;
          },
          set: function set(val) {
            this._frame = val;
            if (this._renderDrawInfo) {
              if (this._frame) {
                this._renderDrawInfo.setTexture(this._frame.getGFXTexture());
                this._renderDrawInfo.setSampler(this._frame.getGFXSampler());
              } else {
                this._renderDrawInfo.setTexture(null);
                this._renderDrawInfo.setSampler(null);
              }
            }
          }
        }, {
          key: "accessor",
          get: function get() {
            return this._accessor;
          }
        }]);
        return RenderData;
      }(BaseRenderData));
      var MeshRenderData = exports('v', function (_BaseRenderData2) {
        _inheritsLoose(MeshRenderData, _BaseRenderData2);
        MeshRenderData.add = function add(vertexFormat) {
          if (vertexFormat === void 0) {
            vertexFormat = vfmtPosUvColor;
          }
          var rd = new MeshRenderData();
          rd._floatStride = vertexFormat === vfmtPosUvColor ? DEFAULT_STRIDE : getAttributeStride(vertexFormat) >> 2;
          rd._vertexFormat = vertexFormat;
          return rd;
        };
        MeshRenderData.remove = function remove(data) {
          data.clear();
        };
        function MeshRenderData(vertexFormat) {
          var _this2;
          if (vertexFormat === void 0) {
            vertexFormat = vfmtPosUvColor;
          }
          _this2 = _BaseRenderData2.call(this, vertexFormat) || this;
          _this2._isMeshBuffer = true;
          _this2.vData = void 0;
          _this2.iData = void 0;
          _this2.vertexStart = 0;
          _this2.vertexRange = 0;
          _this2.indexStart = 0;
          _this2.indexRange = 0;
          _this2.lastFilledIndex = 0;
          _this2.lastFilledVertex = 0;
          _this2.frame = void 0;
          _this2._byteLength = 0;
          _this2._vertexBuffers = [];
          _this2._indexBuffer = null;
          _this2._iaPool = null;
          _this2._iaInfo = null;
          _this2.vData = new Float32Array(256 * _this2.stride);
          _this2.iData = new Uint16Array(256 * 6);
          return _this2;
        }
        var _proto3 = MeshRenderData.prototype;
        _proto3.request = function request(vertexCount, indexCount) {
          var byteOffset = this._byteLength + vertexCount * this.stride;
          var succeed = this.reserve(vertexCount, indexCount);
          if (!succeed) return false;
          this._vc += vertexCount;
          this._ic += indexCount;
          this._byteLength = byteOffset;
          this.vertexRange = this._vc;
          this.indexRange = this._ic;
          return true;
        };
        _proto3.reserve = function reserve(vertexCount, indexCount) {
          var newVBytes = this._byteLength + vertexCount * this.stride;
          var newICount = this.indexCount + indexCount;
          if (vertexCount + this.vertexCount > 65535) {
            return false;
          }
          var byteLength = this.vData.byteLength;
          var indicesLength = this.iData.length;
          var vCount = this.vData.length;
          var iCount = this.iData.length;
          if (newVBytes > byteLength || newICount > indicesLength) {
            while (byteLength < newVBytes || indicesLength < newICount) {
              vCount *= 2;
              iCount *= 2;
              byteLength = vCount * 4;
              indicesLength = iCount;
            }
            this._reallocBuffer(vCount, iCount);
          }
          return true;
        };
        _proto3.resize = function resize(vertexCount, indexCount) {
          var byteLength = vertexCount * this.stride;
          assertIsTrue(vertexCount >= 0 && indexCount >= 0 && byteLength <= this.vData.byteLength && indexCount <= this.iData.length);
          this._vc = vertexCount;
          this._ic = indexCount;
          this._byteLength = byteLength;
          this.updateRange(0, vertexCount, 0, indexCount);
        };
        _proto3.updateRange = function updateRange(vertOffset, vertexCount, indexOffset, indexCount) {
          assertIsTrue(vertexCount >= 0 && indexCount >= 0 && vertexCount <= this._vc && indexCount <= this._ic);
          this.vertexStart = vertOffset;
          this.indexStart = indexOffset;
          this.vertexRange = vertexCount;
          this.indexRange = indexCount;
        };
        _proto3.requestIA = function requestIA(device) {
          this._initIAInfo(device);
          var ia = this._iaPool.add();
          ia.firstIndex = this.indexStart;
          ia.indexCount = this.indexRange;
          return ia;
        };
        _proto3.uploadBuffers = function uploadBuffers() {
          if (this._byteLength === 0 || !this._vertexBuffers[0] || !this._indexBuffer) {
            return;
          }
          var indexCount = this._ic;
          var verticesData = new Float32Array(this.vData.buffer, 0, this._byteLength >> 2);
          var indicesData = new Uint16Array(this.iData.buffer, 0, indexCount);
          var vertexBuffer = this._vertexBuffers[0];
          if (this._byteLength > vertexBuffer.size) {
            vertexBuffer.resize(this._byteLength);
          }
          vertexBuffer.update(verticesData);
          var indexBytes = indexCount << 1;
          if (indexBytes > this._indexBuffer.size) {
            this._indexBuffer.resize(indexBytes);
          }
          this._indexBuffer.update(indicesData);
        };
        _proto3.freeIAPool = function freeIAPool() {
          if (this._iaPool) {
            this._iaPool.reset();
          }
        };
        _proto3.reset = function reset() {
          this._vc = 0;
          this._ic = 0;
          this._byteLength = 0;
          this.vertexStart = 0;
          this.vertexRange = 0;
          this.indexStart = 0;
          this.indexRange = 0;
          this.lastFilledIndex = 0;
          this.lastFilledVertex = 0;
          this.material = null;
          this.freeIAPool();
        };
        _proto3.clear = function clear() {
          this.reset();
          if (this._iaPool) {
            this._iaPool.destroy();
          }
          if (this._vertexBuffers[0]) {
            this._vertexBuffers[0].destroy();
            this._vertexBuffers = [];
          }
          this._iaInfo = null;
          this.vData = new Float32Array(256 * this.stride);
          this.iData = new Uint16Array(256 * 6);
        };
        _proto3._initIAInfo = function _initIAInfo(device) {
          var _this3 = this;
          if (!this._iaInfo) {
            var vbStride = this.stride;
            var vbs = this._vertexBuffers;
            if (!vbs.length) {
              vbs.push(device.createBuffer(new BufferInfo(BufferUsageBit.VERTEX | BufferUsageBit.TRANSFER_DST, MemoryUsageBit.DEVICE, vbStride, vbStride)));
            }
            var ibStride = Uint16Array.BYTES_PER_ELEMENT;
            if (!this._indexBuffer) {
              this._indexBuffer = device.createBuffer(new BufferInfo(BufferUsageBit.INDEX | BufferUsageBit.TRANSFER_DST, MemoryUsageBit.DEVICE, ibStride, ibStride));
            }
            this._iaInfo = new InputAssemblerInfo(this._vertexFormat, vbs, this._indexBuffer);
            this._iaPool = new RecyclePool(function () {
              return device.createInputAssembler(_this3._iaInfo);
            }, 1, function (ia) {
              ia.destroy();
            });
          }
        };
        _proto3._reallocBuffer = function _reallocBuffer(vCount, iCount) {
          var oldVData = this.vData;
          this.vData = new Float32Array(vCount);
          if (oldVData) {
            this.vData.set(oldVData, 0);
          }
          var oldIData = this.iData;
          this.iData = new Uint16Array(iCount);
          if (oldIData) {
            this.iData.set(oldIData, 0);
          }
        };
        _proto3.setRenderDrawInfoAttributes = function setRenderDrawInfoAttributes() {
        };
        _proto3.particleInitRenderDrawInfo = function particleInitRenderDrawInfo(entity) {
        };
        _createClass(MeshRenderData, [{
          key: "formatByte",
          get: function get() {
            return this.stride;
          },
          set: function set(value) {}
        }, {
          key: "floatStride",
          get: function get() {
            return this._floatStride;
          }
        }, {
          key: "vDataOffset",
          get: function get() {
            return this._byteLength >>> 2;
          }
        }]);
        return MeshRenderData;
      }(BaseRenderData));

      var _dec$2k, _dec2$1Q, _class$2j, _class2$24, _initializer$1W, _initializer2$1y, _class3$A;
      var _vec2a = new Vec2();
      var _vec2b = new Vec2();
      var _vec3a = new Vec3();
      var _mat4_temp$1 = new Mat4();
      var _matrix$1 = new Mat4();
      var _worldMatrix$1 = new Mat4();
      var _zeroMatrix = new Mat4(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
      var _rect = new Rect$1();
      var UITransform = exports('e', (_dec$2k = ccclass$n('cc.UITransform'), _dec2$1Q = executionOrder$1(110), _dec$2k(_class$2j = _dec2$1Q(_class$2j = disallowMultiple$1(_class$2j = (_class2$24 = (_class3$A = function (_Component) {
        _inheritsLoose(UITransform, _Component);
        function UITransform() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Component.call.apply(_Component, [this].concat(args)) || this;
          _this._priority = 0;
          _this._contentSize = _initializer$1W && _initializer$1W();
          _this._anchorPoint = _initializer2$1y && _initializer2$1y();
          return _this;
        }
        var _proto = UITransform.prototype;
        _proto.__preload = function __preload() {
          this.node._uiProps.uiTransformComp = this;
        };
        _proto.onLoad = function onLoad() {
          if (this.node.parent) {
            UITransform.insertChangeMap(this.node.parent);
          }
        };
        _proto.onEnable = function onEnable() {
          this.node.on(NodeEventType.PARENT_CHANGED, this._parentChanged, this);
          this._markRenderDataDirty();
        };
        _proto.onDisable = function onDisable() {
          this.node.off(NodeEventType.PARENT_CHANGED, this._parentChanged, this);
        };
        _proto.onDestroy = function onDestroy() {
          this.node._uiProps.uiTransformComp = null;
        };
        _proto.setContentSize = function setContentSize(size, height) {
          var locContentSize = this._contentSize;
          var locWidth;
          var locHeight;
          if (height === undefined) {
            size = size;
            if (approx(size.width, locContentSize.width, EPSILON$3) && approx(size.height, locContentSize.height, EPSILON$3)) {
              return;
            }
            locWidth = size.width;
            locHeight = size.height;
          } else {
            size = size;
            if (approx(size, locContentSize.width, EPSILON$3) && approx(height, locContentSize.height, EPSILON$3)) {
              return;
            }
            locWidth = size;
            locHeight = height;
          }
          {
            locContentSize.width = locWidth;
            locContentSize.height = locHeight;
            this.node.emit(NodeEventType.SIZE_CHANGED);
          }
          this._markRenderDataDirty();
        };
        _proto.setAnchorPoint = function setAnchorPoint(point, y) {
          var locAnchorPoint = this._anchorPoint;
          if (y === undefined) {
            point = point;
            if (point.x === locAnchorPoint.x && point.y === locAnchorPoint.y) {
              return;
            }
            locAnchorPoint.x = point.x;
            locAnchorPoint.y = point.y;
          } else {
            if (point === locAnchorPoint.x && y === locAnchorPoint.y) {
              return;
            }
            locAnchorPoint.x = point;
            locAnchorPoint.y = y;
          }
          this.node.emit(NodeEventType.ANCHOR_CHANGED, this._anchorPoint);
          this._markRenderDataDirty();
        };
        _proto.isHit = function isHit(uiPoint) {
          var w = this._contentSize.width;
          var h = this._contentSize.height;
          var v2WorldPt = _vec2a;
          var testPt = _vec2b;
          var cameras = this._getRenderScene().cameras;
          for (var i = 0; i < cameras.length; i++) {
            var camera = cameras[i];
            if (!(camera.visibility & this.node.layer)) continue;
            camera.node.getWorldRT(_mat4_temp$1);
            var m12 = _mat4_temp$1.m12;
            var m13 = _mat4_temp$1.m13;
            var center = visibleRect.center;
            _mat4_temp$1.m12 = center.x - (_mat4_temp$1.m00 * m12 + _mat4_temp$1.m04 * m13);
            _mat4_temp$1.m13 = center.y - (_mat4_temp$1.m01 * m12 + _mat4_temp$1.m05 * m13);
            Mat4.invert(_mat4_temp$1, _mat4_temp$1);
            Vec2.transformMat4(v2WorldPt, uiPoint, _mat4_temp$1);
            this.node.getWorldMatrix(_worldMatrix$1);
            Mat4.invert(_mat4_temp$1, _worldMatrix$1);
            if (Mat4.strictEquals(_mat4_temp$1, _zeroMatrix)) {
              continue;
            }
            Vec2.transformMat4(testPt, v2WorldPt, _mat4_temp$1);
            testPt.x += this._anchorPoint.x * w;
            testPt.y += this._anchorPoint.y * h;
            var hit = false;
            if (testPt.x >= 0 && testPt.y >= 0 && testPt.x <= w && testPt.y <= h) {
              hit = this._maskTest(v2WorldPt);
            }
            if (hit) {
              return true;
            }
          }
          return false;
        };
        _proto.hitTest = function hitTest(screenPoint, windowId) {
          if (windowId === void 0) {
            windowId = 0;
          }
          var w = this._contentSize.width;
          var h = this._contentSize.height;
          var v3WorldPt = _vec3a;
          var v2WorldPt = _vec2a;
          var testPt = _vec2b;
          var cameras = this._getRenderScene().cameras;
          for (var i = 0; i < cameras.length; i++) {
            var camera = cameras[i];
            if (!(camera.visibility & this.node.layer) || camera.window && !camera.window.swapchain) {
              continue;
            }
            if (camera.systemWindowId !== windowId) {
              continue;
            }
            Vec3.set(v3WorldPt, screenPoint.x, screenPoint.y, 0);
            camera.screenToWorld(v3WorldPt, v3WorldPt);
            Vec2.set(v2WorldPt, v3WorldPt.x, v3WorldPt.y);
            this.node.getWorldMatrix(_worldMatrix$1);
            Mat4.invert(_mat4_temp$1, _worldMatrix$1);
            if (Mat4.strictEquals(_mat4_temp$1, _zeroMatrix)) {
              continue;
            }
            Vec2.transformMat4(testPt, v2WorldPt, _mat4_temp$1);
            testPt.x += this._anchorPoint.x * w;
            testPt.y += this._anchorPoint.y * h;
            var hit = false;
            if (testPt.x >= 0 && testPt.y >= 0 && testPt.x <= w && testPt.y <= h) {
              hit = this._maskTest(v2WorldPt);
            }
            if (hit) {
              return true;
            }
          }
          return false;
        };
        _proto._maskTest = function _maskTest(pointInWorldSpace) {
          var _this$node, _this$node$eventProce;
          var maskList = (_this$node = this.node) === null || _this$node === void 0 ? void 0 : (_this$node$eventProce = _this$node.eventProcessor) === null || _this$node$eventProce === void 0 ? void 0 : _this$node$eventProce.maskList;
          if (maskList) {
            var parent = this.node;
            var length = maskList.length;
            for (var i = 0, j = 0; parent && j < length; ++i, parent = parent.parent) {
              var temp = maskList[j];
              if (i === temp.index) {
                if (parent === temp.comp.node) {
                  var comp = temp.comp;
                  if (comp && comp._enabled && !comp.isHit(pointInWorldSpace)) {
                    return false;
                  }
                  j++;
                } else {
                  maskList.length = j;
                  break;
                }
              } else if (i > temp.index) {
                maskList.length = j;
                break;
              }
            }
          }
          return true;
        };
        _proto.convertToNodeSpaceAR = function convertToNodeSpaceAR(worldPoint, out) {
          this.node.getWorldMatrix(_worldMatrix$1);
          Mat4.invert(_mat4_temp$1, _worldMatrix$1);
          if (!out) {
            out = new Vec3();
          }
          return Vec3.transformMat4(out, worldPoint, _mat4_temp$1);
        };
        _proto.convertToWorldSpaceAR = function convertToWorldSpaceAR(nodePoint, out) {
          this.node.getWorldMatrix(_worldMatrix$1);
          if (!out) {
            out = new Vec3();
          }
          return Vec3.transformMat4(out, nodePoint, _worldMatrix$1);
        };
        _proto.getBoundingBox = function getBoundingBox() {
          var rect = new Rect$1();
          this._selfBoundingBox(rect);
          Mat4.fromSRT(_matrix$1, this.node.rotation, this.node.position, this.node.scale);
          rect.transformMat4(_matrix$1);
          return rect;
        };
        _proto.getBoundingBoxToWorld = function getBoundingBoxToWorld() {
          var rect = new Rect$1();
          var locChildren = this.node.children;
          for (var i = 0; i < locChildren.length; ++i) {
            var child = locChildren[i];
            if (child && child.active) {
              var uiTransform = child.getComponent(UITransform);
              if (uiTransform && uiTransform.contentSize.width && uiTransform.contentSize.height) {
                uiTransform._selfBoundingBox(_rect);
                _rect.transformMat4(child.worldMatrix);
                if (rect.width === 0) {
                  rect.set(_rect);
                } else {
                  Rect$1.union(rect, rect, _rect);
                }
              }
            }
          }
          if (this._contentSize.width && this._contentSize.height) {
            this._selfBoundingBox(_rect);
            _rect.transformMat4(this.node.worldMatrix);
            if (rect.width === 0) {
              rect.set(_rect);
            } else {
              Rect$1.union(rect, rect, _rect);
            }
          }
          return rect;
        };
        _proto.getBoundingBoxTo = function getBoundingBoxTo(targetMat) {
          var rect = new Rect$1();
          var locChildren = this.node.children;
          Mat4.invert(_mat4_temp$1, targetMat);
          for (var i = 0; i < locChildren.length; ++i) {
            var child = locChildren[i];
            if (child && child.active) {
              var uiTransform = child.getComponent(UITransform);
              if (uiTransform && uiTransform.contentSize.width && uiTransform.contentSize.height) {
                uiTransform._selfBoundingBox(_rect);
                Mat4.multiply(_matrix$1, child.worldMatrix, _mat4_temp$1);
                _rect.transformMat4(_matrix$1);
                if (rect.width === 0) {
                  rect.set(_rect);
                } else {
                  Rect$1.union(rect, rect, _rect);
                }
              }
            }
          }
          if (this._contentSize.width && this._contentSize.height) {
            this._selfBoundingBox(_rect);
            Mat4.multiply(_matrix$1, this.node.worldMatrix, _mat4_temp$1);
            _rect.transformMat4(_matrix$1);
            if (rect.width === 0) {
              rect.set(_rect);
            } else {
              Rect$1.union(rect, rect, _rect);
            }
          }
          return rect;
        };
        _proto.getComputeAABB = function getComputeAABB(out) {
          var width = this._contentSize.width;
          var height = this._contentSize.height;
          _rect.set(-this._anchorPoint.x * width, -this._anchorPoint.y * height, width, height);
          _rect.transformMat4(this.node.worldMatrix);
          var px = _rect.x + _rect.width * 0.5;
          var py = _rect.y + _rect.height * 0.5;
          var pz = this.node.worldPosition.z;
          var w = _rect.width / 2;
          var h = _rect.height / 2;
          var l = 0.001;
          if (out != null) {
            AABB.set(out, px, py, pz, w, h, l);
            return out;
          } else {
            return new AABB(px, py, pz, w, h, l);
          }
        };
        _proto._selfBoundingBox = function _selfBoundingBox(out) {
          var width = this._contentSize.width;
          var height = this._contentSize.height;
          out.set(-this._anchorPoint.x * width, -this._anchorPoint.y * height, width, height);
          return out;
        };
        _proto._parentChanged = function _parentChanged(node) {
          if (this.node.getComponent('cc.RenderRoot2D')) {
            return;
          }
          if (this.node.parent) {
            UITransform.insertChangeMap(this.node.parent);
          }
        };
        _proto._markRenderDataDirty = function _markRenderDataDirty() {
          var uiComp = this.node._uiProps.uiComp;
          if (uiComp) {
            uiComp.markForUpdateRenderData();
          }
        };
        UITransform.insertChangeMap = function insertChangeMap(node) {
          var key = node.uuid;
          if (!UITransform.priorityChangeNodeMap.has(key)) {
            UITransform.priorityChangeNodeMap.set(key, node);
          }
        };
        UITransform._sortChildrenSibling = function _sortChildrenSibling(node) {
          var siblings = node.children;
          if (siblings) {
            siblings.sort(function (a, b) {
              var aComp = a._uiProps.uiTransformComp;
              var bComp = b._uiProps.uiTransformComp;
              var ca = aComp ? aComp._priority : 0;
              var cb = bComp ? bComp._priority : 0;
              var diff = ca - cb;
              if (diff === 0) return a.getSiblingIndex() - b.getSiblingIndex();
              return diff;
            });
          }
        };
        UITransform._sortSiblings = function _sortSiblings() {
          UITransform.priorityChangeNodeMap.forEach(function (node, ID) {
            UITransform._sortChildrenSibling(node);
            node._updateSiblingIndex();
            node.emit('childrenSiblingOrderChanged');
          });
          UITransform.priorityChangeNodeMap.clear();
        };
        UITransform._cleanChangeMap = function _cleanChangeMap() {
          UITransform.priorityChangeNodeMap.clear();
        };
        _createClass(UITransform, [{
          key: "contentSize",
          get: function get() {
            return this._contentSize;
          },
          set: function set(value) {
            if (this._contentSize.equals(value)) {
              return;
            }
            {
              this._contentSize.set(value);
              this.node.emit(NodeEventType.SIZE_CHANGED);
            }
            this._markRenderDataDirty();
          }
        }, {
          key: "width",
          get: function get() {
            return this._contentSize.width;
          },
          set: function set(value) {
            if (this._contentSize.width === value) {
              return;
            }
            {
              this._contentSize.width = value;
              this.node.emit(NodeEventType.SIZE_CHANGED);
            }
            this._markRenderDataDirty();
          }
        }, {
          key: "height",
          get: function get() {
            return this._contentSize.height;
          },
          set: function set(value) {
            if (this.contentSize.height === value) {
              return;
            }
            {
              this._contentSize.height = value;
              this.node.emit(NodeEventType.SIZE_CHANGED);
            }
            this._markRenderDataDirty();
          }
        }, {
          key: "anchorPoint",
          get: function get() {
            return this._anchorPoint;
          },
          set: function set(value) {
            if (this._anchorPoint.equals(value)) {
              return;
            }
            this._anchorPoint.set(value);
            this.node.emit(NodeEventType.ANCHOR_CHANGED, this._anchorPoint);
            this._markRenderDataDirty();
          }
        }, {
          key: "anchorX",
          get: function get() {
            return this._anchorPoint.x;
          },
          set: function set(value) {
            if (this._anchorPoint.x === value) {
              return;
            }
            this._anchorPoint.x = value;
            this.node.emit(NodeEventType.ANCHOR_CHANGED, this._anchorPoint);
            this._markRenderDataDirty();
          }
        }, {
          key: "anchorY",
          get: function get() {
            return this._anchorPoint.y;
          },
          set: function set(value) {
            if (this._anchorPoint.y === value) {
              return;
            }
            this._anchorPoint.y = value;
            this.node.emit(NodeEventType.ANCHOR_CHANGED, this._anchorPoint);
            this._markRenderDataDirty();
          }
        }, {
          key: "priority",
          get: function get() {
            return this._priority;
          },
          set: function set(value) {
            if (this._priority === value) {
              return;
            }
            if (this.node.getComponent('cc.RenderRoot2D')) {
              warnID(6706);
              return;
            }
            this._priority = value;
            if (this.node.parent) {
              UITransform.insertChangeMap(this.node.parent);
            }
          }
        }, {
          key: "visibility",
          get: function get() {
            var camera = director.root.batcher2D.getFirstRenderCamera(this.node);
            return camera ? camera.visibility : 0;
          }
        }, {
          key: "cameraPriority",
          get: function get() {
            var camera = director.root.batcher2D.getFirstRenderCamera(this.node);
            return camera ? camera.priority : 0;
          }
        }]);
        return UITransform;
      }(Component), _class3$A.EventType = NodeEventType, _class3$A.priorityChangeNodeMap = new Map(), _class3$A), (_initializer$1W = applyDecoratedInitializer(_class2$24.prototype, "_contentSize", [serializable$j], function () {
        return new Size$1(100, 100);
      }), _initializer2$1y = applyDecoratedInitializer(_class2$24.prototype, "_anchorPoint", [serializable$j], function () {
        return new Vec2(0.5, 0.5);
      })), _class2$24)) || _class$2j) || _class$2j) || _class$2j));
      director.on(Director.EVENT_AFTER_UPDATE, UITransform._sortSiblings);
      director.on(Director.EVENT_BEFORE_SCENE_LAUNCH, UITransform._cleanChangeMap);

      var _dec$2j, _dec2$1P, _dec3$1j, _class$2i, _class2$23, _initializer$1V;
      var _matInsInfo = {
        parent: null,
        owner: null,
        subModelIdx: 0
      };
      var ccclass$l = ccclass$n,
        disallowMultiple = disallowMultiple$1,
        type$6 = type$7;
      var Renderer = exports('dU', (_dec$2j = ccclass$l('cc.Renderer'), _dec2$1P = type$6(Material), _dec3$1j = type$6([Material]), _dec$2j(_class$2i = disallowMultiple(_class$2i = (_class2$23 = function (_Component) {
        _inheritsLoose(Renderer, _Component);
        function Renderer() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Component.call.apply(_Component, [this].concat(args)) || this;
          _this._materials = _initializer$1V && _initializer$1V();
          _this._materialInstances = [];
          return _this;
        }
        var _proto = Renderer.prototype;
        _proto.getMaterial = function getMaterial(idx) {
          return this.getSharedMaterial(idx);
        };
        _proto.setMaterial = function setMaterial(material, index) {
          this.setSharedMaterial(material, index);
        };
        _proto.getSharedMaterial = function getSharedMaterial(idx) {
          if (idx < 0 || idx >= this._materials.length) {
            return null;
          }
          return this._materials[idx];
        };
        _proto.setSharedMaterial = function setSharedMaterial(material, index) {
          if (material && material instanceof MaterialInstance) {
            errorID(12012);
          }
          this._materials[index] = material;
          var inst = this._materialInstances[index];
          if (inst) {
            inst.destroy();
            this._materialInstances[index] = null;
          }
          this._onMaterialModified(index, this._materials[index]);
        };
        _proto.getMaterialInstance = function getMaterialInstance(idx) {
          var mat = this._materials[idx];
          if (!mat) {
            return null;
          }
          if (!this._materialInstances[idx]) {
            _matInsInfo.parent = this._materials[idx];
            _matInsInfo.owner = this;
            _matInsInfo.subModelIdx = idx;
            var instantiated = new MaterialInstance(_matInsInfo);
            _matInsInfo.parent = null;
            _matInsInfo.owner = null;
            _matInsInfo.subModelIdx = 0;
            this.setMaterialInstance(instantiated, idx);
          }
          return this._materialInstances[idx];
        };
        _proto.setMaterialInstance = function setMaterialInstance(matInst, index) {
          if (typeof matInst === 'number') {
            warnID(12007);
            var temp = matInst;
            matInst = index;
            index = temp;
          }
          var curInst = this._materialInstances[index];
          if (matInst && matInst.parent) {
            if (matInst !== curInst) {
              this._materialInstances[index] = matInst;
              this._onMaterialModified(index, matInst);
            }
            return;
          }
          if (matInst !== this._materials[index] || curInst) {
            this.setSharedMaterial(matInst, index);
          }
        };
        _proto.getRenderMaterial = function getRenderMaterial(index) {
          return this._materialInstances[index] || this._materials[index];
        };
        _proto._onMaterialModified = function _onMaterialModified(index, material) {};
        _proto._onRebuildPSO = function _onRebuildPSO(index, material) {};
        _proto._clearMaterials = function _clearMaterials() {};
        _createClass(Renderer, [{
          key: "sharedMaterial",
          get: function get() {
            return this.getSharedMaterial(0);
          }
        }, {
          key: "sharedMaterials",
          get: function get() {
            return this._materials;
          },
          set: function set(val) {
            for (var i = 0; i < val.length; i++) {
              if (val[i] !== this._materials[i]) {
                this.setSharedMaterial(val[i], i);
              }
            }
            if (val.length < this._materials.length) {
              for (var _i = val.length; _i < this._materials.length; _i++) {
                this.setSharedMaterial(null, _i);
              }
              this._materials.splice(val.length);
            }
          }
        }, {
          key: "material",
          get: function get() {
            return this.getMaterialInstance(0);
          },
          set: function set(val) {
            if (this._materials.length === 1 && !this._materialInstances[0] && this._materials[0] === val) {
              return;
            }
            this.setMaterialInstance(val, 0);
          }
        }, {
          key: "materials",
          get: function get() {
            for (var i = 0; i < this._materials.length; i++) {
              this._materialInstances[i] = this.getMaterialInstance(i);
            }
            return this._materialInstances;
          },
          set: function set(val) {
            var newLength = val.length;
            var oldLength = this._materials.length;
            for (var i = newLength; i < oldLength; i++) {
              this.setMaterialInstance(null, i);
            }
            this._materials.length = newLength;
            this._materialInstances.length = newLength;
            for (var _i2 = 0; _i2 < newLength; _i2++) {
              if (this._materialInstances[_i2] != val[_i2]) {
                this.setMaterialInstance(val[_i2], _i2);
              }
            }
          }
        }]);
        return Renderer;
      }(Component), (_applyDecoratedDescriptor(_class2$23.prototype, "sharedMaterials", [_dec2$1P], Object.getOwnPropertyDescriptor(_class2$23.prototype, "sharedMaterials"), _class2$23.prototype), _initializer$1V = applyDecoratedInitializer(_class2$23.prototype, "_materials", [_dec3$1j], function () {
        return [];
      })), _class2$23)) || _class$2i) || _class$2i));

      var _dec$2i, _dec2$1O, _dec3$1i, _dec4$X, _class$2h, _class2$22, _initializer$1U, _initializer2$1x, _initializer3$11, _initializer4$P, _initializer5$C, _class3$z;
      ccenum(BlendFactor);
      ccenum(BlendOp);
      ccenum(ColorMask);
      var InstanceMaterialType; exports('I', InstanceMaterialType);
      (function (InstanceMaterialType) {
        InstanceMaterialType[InstanceMaterialType["ADD_COLOR"] = 0] = "ADD_COLOR";
        InstanceMaterialType[InstanceMaterialType["ADD_COLOR_AND_TEXTURE"] = 1] = "ADD_COLOR_AND_TEXTURE";
        InstanceMaterialType[InstanceMaterialType["GRAYSCALE"] = 2] = "GRAYSCALE";
        InstanceMaterialType[InstanceMaterialType["USE_ALPHA_SEPARATED"] = 3] = "USE_ALPHA_SEPARATED";
        InstanceMaterialType[InstanceMaterialType["USE_ALPHA_SEPARATED_AND_GRAY"] = 4] = "USE_ALPHA_SEPARATED_AND_GRAY";
      })(InstanceMaterialType || (exports('I', InstanceMaterialType = {})));
      var UIRenderer = exports('d', (_dec$2i = ccclass$n('cc.UIRenderer'), _dec2$1O = requireComponent(UITransform), _dec3$1i = type$7(Material), _dec4$X = type$7(Material), _dec$2i(_class$2h = _dec2$1O(_class$2h = (_class2$22 = (_class3$z = function (_Renderer) {
        _inheritsLoose(UIRenderer, _Renderer);
        function UIRenderer() {
          var _this;
          _this = _Renderer.call(this) || this;
          _this._renderData = null;
          _this._materials = _initializer$1U && _initializer$1U();
          _this._customMaterial = _initializer2$1x && _initializer2$1x();
          _this._srcBlendFactor = _initializer3$11 && _initializer3$11();
          _this._dstBlendFactor = _initializer4$P && _initializer4$P();
          _this._color = _initializer5$C && _initializer5$C();
          _this._stencilStage = Stage.DISABLED;
          _this._assembler = null;
          _this._postAssembler = null;
          _this._renderDataFlag = true;
          _this._renderFlag = true;
          _this._renderEntity = void 0;
          _this._instanceMaterialType = -1;
          _this._srcBlendFactorCache = BlendFactor.SRC_ALPHA;
          _this._dstBlendFactorCache = BlendFactor.ONE_MINUS_SRC_ALPHA;
          _this._dirtyVersion = -1;
          _this._internalId = -1;
          _this._flagChangedVersion = -1;
          _this._useVertexOpacity = false;
          _this._lastParent = null;
          _this._renderEntity = _this.createRenderEntity();
          return _this;
        }
        var _proto = UIRenderer.prototype;
        _proto.setRenderData = function setRenderData(renderData) {
          this._renderData = renderData;
        };
        _proto.onLoad = function onLoad() {
          this._renderEntity.setNode(this.node);
        };
        _proto.__preload = function __preload() {
          this.node._uiProps.uiComp = this;
          if (this._flushAssembler) {
            this._flushAssembler();
          }
        };
        _proto.onEnable = function onEnable() {
          this.node.on(NodeEventType.ANCHOR_CHANGED, this._nodeStateChange, this);
          this.node.on(NodeEventType.SIZE_CHANGED, this._nodeStateChange, this);
          this.node.on(NodeEventType.PARENT_CHANGED, this._colorDirty, this);
          this.updateMaterial();
          this._colorDirty();
          uiRendererManager.addRenderer(this);
          this.markForUpdateRenderData();
        };
        _proto.onRestore = function onRestore() {
          this.updateMaterial();
          this.markForUpdateRenderData();
        };
        _proto.onDisable = function onDisable() {
          this.node.off(NodeEventType.ANCHOR_CHANGED, this._nodeStateChange, this);
          this.node.off(NodeEventType.SIZE_CHANGED, this._nodeStateChange, this);
          this.node.off(NodeEventType.PARENT_CHANGED, this._colorDirty, this);
          uiRendererManager.removeRenderer(this);
          this._renderFlag = false;
          this._renderEntity.enabled = false;
        };
        _proto.onDestroy = function onDestroy() {
          this._renderEntity.setNode(null);
          if (this.node._uiProps.uiComp === this) {
            this.node._uiProps.uiComp = null;
          }
          this.destroyRenderData();
          if (this._materialInstances) {
            for (var i = 0; i < this._materialInstances.length; i++) {
              var instance = this._materialInstances[i];
              if (instance) {
                instance.destroy();
              }
            }
          }
        };
        _proto.markForUpdateRenderData = function markForUpdateRenderData(enable) {
          if (enable === void 0) {
            enable = true;
          }
          if (enable) {
            var renderData = this._renderData;
            if (renderData) {
              renderData.vertDirty = true;
            }
            uiRendererManager.markDirtyRenderer(this);
          }
        };
        _proto.requestRenderData = function requestRenderData(drawInfoType) {
          if (drawInfoType === void 0) {
            drawInfoType = RenderDrawInfoType.COMP;
          }
          var data = RenderData.add();
          data.initRenderDrawInfo(this, drawInfoType);
          this._renderData = data;
          return data;
        };
        _proto.destroyRenderData = function destroyRenderData() {
          if (!this._renderData) {
            return;
          }
          this._renderData.removeRenderDrawInfo(this);
          RenderData.remove(this._renderData);
          this._renderData = null;
        };
        _proto.updateRenderer = function updateRenderer() {
          if (this._assembler) {
            this._assembler.updateRenderData(this);
          }
          this._renderFlag = this._canRender();
          this._renderEntity.enabled = this._renderFlag;
        };
        _proto.fillBuffers = function fillBuffers(render) {
          if (this._renderFlag) {
            this._render(render);
          }
        };
        _proto.postUpdateAssembler = function postUpdateAssembler(render) {
          if (this._postAssembler && this._renderFlag) {
            this._postRender(render);
          }
        };
        _proto._render = function _render(render) {};
        _proto._postRender = function _postRender(render) {};
        _proto._canRender = function _canRender() {
          {
            assert(this.isValid, 'this component should not be invalid!');
          }
          return this.getSharedMaterial(0) !== null && this._enabled && this._color.a > 0;
        };
        _proto._postCanRender = function _postCanRender() {};
        _proto.updateMaterial = function updateMaterial() {
          if (this._customMaterial) {
            if (this.getSharedMaterial(0) !== this._customMaterial) {
              this.setSharedMaterial(this._customMaterial, 0);
            }
            return;
          }
          var mat = this._updateBuiltinMaterial();
          this.setSharedMaterial(mat, 0);
          if (this.stencilStage === Stage.ENTER_LEVEL || this.stencilStage === Stage.ENTER_LEVEL_INVERTED) {
            this.getMaterialInstance(0).recompileShaders({
              USE_ALPHA_TEST: true
            });
          }
          this._updateBlendFunc();
        };
        _proto._updateColor = function _updateColor() {
          this.node._uiProps.colorDirty = true;
          this.setEntityColorDirty(true);
          this.setEntityColor(this._color);
          this.setEntityOpacity(this.node._uiProps.localOpacity);
          if (this._assembler) {
            this._assembler.updateColor(this);
            var renderFlag = this._renderFlag;
            this._renderFlag = this._canRender();
            this.setEntityEnabled(this._renderFlag);
            if (renderFlag !== this._renderFlag) {
              var renderData = this.renderData;
              if (renderData) {
                renderData.vertDirty = true;
              }
            }
          }
        };
        UIRenderer.setEntityColorDirtyRecursively = function setEntityColorDirtyRecursively(node, dirty) {
          var render = node._uiProps.uiComp;
          if (render && render.color) {
            render._renderEntity.colorDirty = dirty;
          }
          for (var i = 0; i < node.children.length; i++) {
            UIRenderer.setEntityColorDirtyRecursively(node.children[i], dirty);
          }
        };
        _proto.setEntityColorDirty = function setEntityColorDirty(dirty) {
        };
        _proto.setEntityColor = function setEntityColor(color) {
        };
        _proto.setEntityOpacity = function setEntityOpacity(opacity) {
        };
        _proto.setEntityEnabled = function setEntityEnabled(enabled) {
        };
        _proto._updateBlendFunc = function _updateBlendFunc() {
          var target = this.getRenderMaterial(0).passes[0].blendState.targets[0];
          this._dstBlendFactorCache = target.blendDst;
          this._srcBlendFactorCache = target.blendSrc;
          if (this._dstBlendFactorCache !== this._dstBlendFactor || this._srcBlendFactorCache !== this._srcBlendFactor) {
            target = this.getMaterialInstance(0).passes[0].blendState.targets[0];
            target.blend = true;
            target.blendDstAlpha = BlendFactor.ONE_MINUS_SRC_ALPHA;
            target.blendDst = this._dstBlendFactor;
            target.blendSrc = this._srcBlendFactor;
            var targetPass = this.getMaterialInstance(0).passes[0];
            targetPass.blendState.setTarget(0, target);
            targetPass._updatePassHash();
            this._dstBlendFactorCache = this._dstBlendFactor;
            this._srcBlendFactorCache = this._srcBlendFactor;
          }
        };
        _proto._nodeStateChange = function _nodeStateChange(transformType) {
          if (this._renderData) {
            this.markForUpdateRenderData();
          }
          for (var i = 0; i < this.node.children.length; ++i) {
            var child = this.node.children[i];
            var renderComp = child.getComponent(UIRenderer);
            if (renderComp) {
              renderComp.markForUpdateRenderData();
            }
          }
        };
        _proto._colorDirty = function _colorDirty() {
          this.node._uiProps.colorDirty = true;
          this.setEntityColorDirty(true);
        };
        _proto._onMaterialModified = function _onMaterialModified(idx, material) {
          if (this._renderData) {
            this.markForUpdateRenderData();
            this._renderData.passDirty = true;
          }
          _Renderer.prototype._onMaterialModified.call(this, idx, material);
        };
        _proto._updateBuiltinMaterial = function _updateBuiltinMaterial() {
          var mat;
          switch (this._instanceMaterialType) {
            case InstanceMaterialType.ADD_COLOR:
              mat = builtinResMgr.get("ui-base-material");
              break;
            case InstanceMaterialType.GRAYSCALE:
              mat = builtinResMgr.get("ui-sprite-gray-material");
              break;
            case InstanceMaterialType.USE_ALPHA_SEPARATED:
              mat = builtinResMgr.get("ui-sprite-alpha-sep-material");
              break;
            case InstanceMaterialType.USE_ALPHA_SEPARATED_AND_GRAY:
              mat = builtinResMgr.get("ui-sprite-gray-alpha-sep-material");
              break;
            default:
              mat = builtinResMgr.get("ui-sprite-material");
              break;
          }
          return mat;
        };
        _proto.setNodeDirty = function setNodeDirty() {
          if (this._renderData) {
            this._renderData.nodeDirty = true;
          }
        };
        _proto.setTextureDirty = function setTextureDirty() {
          if (this._renderData) {
            this._renderData.textureDirty = true;
          }
        };
        _proto.createRenderEntity = function createRenderEntity() {
          return new RenderEntity(RenderEntityType.STATIC);
        };
        _createClass(UIRenderer, [{
          key: "sharedMaterials",
          get: function get() {
            return this._materials;
          },
          set: function set(val) {
            for (var i = 0; i < val.length; i++) {
              if (val[i] !== this._materials[i]) {
                this.setSharedMaterial(val[i], i);
              }
            }
            if (val.length < this._materials.length) {
              for (var _i = val.length; _i < this._materials.length; _i++) {
                this.setSharedMaterial(null, _i);
              }
              this._materials.splice(val.length);
            }
          }
        }, {
          key: "customMaterial",
          get: function get() {
            return this._customMaterial;
          },
          set: function set(val) {
            this._customMaterial = val;
            this.updateMaterial();
          }
        }, {
          key: "color",
          get: function get() {
            return this._color;
          },
          set: function set(value) {
            if (this._color.equals(value)) {
              return;
            }
            this._color.set(value);
            this._updateColor();
          }
        }, {
          key: "renderData",
          get: function get() {
            return this._renderData;
          }
        }, {
          key: "useVertexOpacity",
          get: function get() {
            return this._useVertexOpacity;
          }
        }, {
          key: "stencilStage",
          get: function get() {
            return this._stencilStage;
          },
          set: function set(val) {
            this._stencilStage = val;
            this._renderEntity.setStencilStage(val);
          }
        }, {
          key: "srcBlendFactor",
          get: function get() {
            return this._srcBlendFactor;
          },
          set: function set(srcBlendFactor) {
            this._srcBlendFactor = srcBlendFactor;
          }
        }, {
          key: "batcher",
          get: function get() {
            return director.root.batcher2D;
          }
        }, {
          key: "renderEntity",
          get: function get() {
            {
              assert(Boolean(this._renderEntity), 'this._renderEntity should not be invalid');
            }
            return this._renderEntity;
          }
        }]);
        return UIRenderer;
      }(Renderer), _class3$z.BlendState = BlendFactor, _class3$z.Assembler = null, _class3$z.PostAssembler = null, _class3$z), (_applyDecoratedDescriptor(_class2$22.prototype, "sharedMaterials", [override], Object.getOwnPropertyDescriptor(_class2$22.prototype, "sharedMaterials"), _class2$22.prototype), _applyDecoratedDescriptor(_class2$22.prototype, "customMaterial", [_dec3$1i], Object.getOwnPropertyDescriptor(_class2$22.prototype, "customMaterial"), _class2$22.prototype), _initializer$1U = applyDecoratedInitializer(_class2$22.prototype, "_materials", [override], function () {
        return [];
      }), _initializer2$1x = applyDecoratedInitializer(_class2$22.prototype, "_customMaterial", [_dec4$X], function () {
        return null;
      }), _initializer3$11 = applyDecoratedInitializer(_class2$22.prototype, "_srcBlendFactor", [serializable$j], function () {
        return BlendFactor.SRC_ALPHA;
      }), _initializer4$P = applyDecoratedInitializer(_class2$22.prototype, "_dstBlendFactor", [serializable$j], function () {
        return BlendFactor.ONE_MINUS_SRC_ALPHA;
      }), _initializer5$C = applyDecoratedInitializer(_class2$22.prototype, "_color", [serializable$j], function () {
        return Color$1.WHITE.clone();
      })), _class2$22)) || _class$2h) || _class$2h));
      legacyCC.internal.UIRenderer = UIRenderer;

      var TextStyle = function () {
        function TextStyle() {
          this.isBold = false;
          this.isItalic = false;
          this.isUnderline = false;
          this.underlineHeight = 1;
          this.isOutlined = false;
          this.outlineColor = Color$1.WHITE.clone();
          this.outlineWidth = 1;
          this.hasShadow = false;
          this.shadowColor = Color$1.BLACK.clone();
          this.shadowBlur = 2;
          this.shadowOffsetX = 0;
          this.shadowOffsetY = 0;
          this.color = Color$1.WHITE.clone();
          this.fontSize = 40;
          this.actualFontSize = 0;
          this.isSystemFontUsed = false;
          this.originFontSize = 0;
          this.bmfontScale = 1.0;
          this.fontFamily = 'Arial';
          this.fontDesc = '';
          this.fntConfig = null;
          this.spriteFrame = null;
          this.fontScale = 1;
        }
        var _proto = TextStyle.prototype;
        _proto.reset = function reset() {
          this.isBold = false;
          this.isItalic = false;
          this.isUnderline = false;
          this.underlineHeight = 1;
          this.isOutlined = false;
          this.outlineColor.set();
          this.outlineWidth = 1;
          this.hasShadow = false;
          this.shadowColor.set();
          this.shadowBlur = 2;
          this.shadowOffsetX = 0;
          this.shadowOffsetY = 0;
        };
        return TextStyle;
      }();

      var TextLayout = function () {
        function TextLayout() {
          this.horizontalAlign = 0;
          this.verticalAlign = 0;
          this.wrapping = true;
          this.overFlow = 0;
          this.lineHeight = 10;
          this.maxLineWidth = 0;
          this.spacingX = 0;
          this.textWidthTemp = 0;
          this.textHeightTemp = 0;
          this.textDimensions = new Size$1();
          this.horizontalKerning = [];
          this.numberOfLines = 1;
          this.linesOffsetX = [];
          this.letterOffsetY = 0;
          this.tailoredTopY = 0;
          this.tailoredBottomY = 0;
          this.textDesiredHeight = 0;
          this.linesWidth = [];
        }
        var _proto = TextLayout.prototype;
        _proto.reset = function reset() {
          this.horizontalAlign = 0;
          this.verticalAlign = 0;
          this.wrapping = true;
          this.overFlow = 0;
          this.lineHeight = 10;
          this.maxLineWidth = 0;
          this.spacingX = 0;
          this.textWidthTemp = 0;
          this.textHeightTemp = 0;
          this.textDimensions.set();
          this.horizontalKerning.length = 0;
          this.numberOfLines = 1;
          this.linesOffsetX.length = 0;
          this.letterOffsetY = 0;
          this.tailoredTopY = 0;
          this.tailoredBottomY = 0;
          this.textDesiredHeight = 0;
          this.linesWidth.length = 0;
        };
        return TextLayout;
      }();

      var TextOutputLayoutData = function () {
        function TextOutputLayoutData() {
          this.parsedString = [];
          this.nodeContentSize = Size$1.ZERO.clone();
          this.canvasSize = new Size$1();
          this.canvasPadding = new Rect$1();
          this.contentSizeExtend = Size$1.ZERO.clone();
          this.startPosition = Vec2.ZERO.clone();
        }
        var _proto = TextOutputLayoutData.prototype;
        _proto.reset = function reset() {
          this.parsedString.length = 0;
          this.nodeContentSize.set(0, 0);
          this.canvasSize.set();
          this.canvasPadding.set();
          this.contentSizeExtend.set();
          this.startPosition.set();
        };
        return TextOutputLayoutData;
      }();
      var TextOutputRenderData = function () {
        function TextOutputRenderData() {
          this.quadCount = 0;
          this.vertexBuffer = [];
          this.texture = null;
          this.uiTransAnchorX = 0.5;
          this.uiTransAnchorY = 0.5;
        }
        var _proto2 = TextOutputRenderData.prototype;
        _proto2.reset = function reset() {
          this.quadCount = 0;
          this.vertexBuffer.length = 0;
          this.texture = null;
          this.uiTransAnchorX = 0.5;
          this.uiTransAnchorY = 0.5;
        };
        return TextOutputRenderData;
      }();

      var _dec$2h, _dec2$1N, _dec3$1h, _dec4$W, _dec5$M, _dec6$w, _dec7$p, _class$2g, _class2$21, _initializer$1T, _initializer2$1w, _initializer3$10, _initializer4$O, _initializer5$B, _initializer6$t, _initializer7$n, _initializer8$m, _initializer9$k, _initializer10$i, _initializer11$f, _initializer12$d, _initializer13$c, _initializer14$a, _initializer15$7, _initializer16$7, _initializer17$6, _class3$y;
      Color$1.WHITE.clone();
      var HorizontalTextAlignment; exports('H', HorizontalTextAlignment);
      (function (HorizontalTextAlignment) {
        HorizontalTextAlignment[HorizontalTextAlignment["LEFT"] = 0] = "LEFT";
        HorizontalTextAlignment[HorizontalTextAlignment["CENTER"] = 1] = "CENTER";
        HorizontalTextAlignment[HorizontalTextAlignment["RIGHT"] = 2] = "RIGHT";
      })(HorizontalTextAlignment || (exports('H', HorizontalTextAlignment = {})));
      ccenum(HorizontalTextAlignment);
      var VerticalTextAlignment; exports('V', VerticalTextAlignment);
      (function (VerticalTextAlignment) {
        VerticalTextAlignment[VerticalTextAlignment["TOP"] = 0] = "TOP";
        VerticalTextAlignment[VerticalTextAlignment["CENTER"] = 1] = "CENTER";
        VerticalTextAlignment[VerticalTextAlignment["BOTTOM"] = 2] = "BOTTOM";
      })(VerticalTextAlignment || (exports('V', VerticalTextAlignment = {})));
      ccenum(VerticalTextAlignment);
      var Overflow$1; exports('O', Overflow$1);
      (function (Overflow) {
        Overflow[Overflow["NONE"] = 0] = "NONE";
        Overflow[Overflow["CLAMP"] = 1] = "CLAMP";
        Overflow[Overflow["SHRINK"] = 2] = "SHRINK";
        Overflow[Overflow["RESIZE_HEIGHT"] = 3] = "RESIZE_HEIGHT";
      })(Overflow$1 || (exports('O', Overflow$1 = {})));
      ccenum(Overflow$1);
      var CacheMode; exports('q', CacheMode);
      (function (CacheMode) {
        CacheMode[CacheMode["NONE"] = 0] = "NONE";
        CacheMode[CacheMode["BITMAP"] = 1] = "BITMAP";
        CacheMode[CacheMode["CHAR"] = 2] = "CHAR";
      })(CacheMode || (exports('q', CacheMode = {})));
      ccenum(CacheMode);
      var Label = exports('r', (_dec$2h = ccclass$n('cc.Label'), _dec2$1N = executionOrder$1(110), _dec3$1h = type$7(HorizontalTextAlignment), _dec4$W = type$7(VerticalTextAlignment), _dec5$M = type$7(Overflow$1), _dec6$w = type$7(Font), _dec7$p = type$7(CacheMode), _dec$2h(_class$2g = _dec2$1N(_class$2g = (_class2$21 = (_class3$y = function (_UIRenderer) {
        _inheritsLoose(Label, _UIRenderer);
        function Label() {
          var _this;
          _this = _UIRenderer.call(this) || this;
          _this._string = _initializer$1T && _initializer$1T();
          _this._horizontalAlign = _initializer2$1w && _initializer2$1w();
          _this._verticalAlign = _initializer3$10 && _initializer3$10();
          _this._actualFontSize = _initializer4$O && _initializer4$O();
          _this._fontSize = _initializer5$B && _initializer5$B();
          _this._fontFamily = _initializer6$t && _initializer6$t();
          _this._lineHeight = _initializer7$n && _initializer7$n();
          _this._overflow = _initializer8$m && _initializer8$m();
          _this._enableWrapText = _initializer9$k && _initializer9$k();
          _this._font = _initializer10$i && _initializer10$i();
          _this._isSystemFontUsed = _initializer11$f && _initializer11$f();
          _this._spacingX = _initializer12$d && _initializer12$d();
          _this._isItalic = _initializer13$c && _initializer13$c();
          _this._isBold = _initializer14$a && _initializer14$a();
          _this._isUnderline = _initializer15$7 && _initializer15$7();
          _this._underlineHeight = _initializer16$7 && _initializer16$7();
          _this._cacheMode = _initializer17$6 && _initializer17$6();
          _this._N$file = null;
          _this._texture = null;
          _this._ttfSpriteFrame = null;
          _this._userDefinedFont = null;
          _this._assemblerData = null;
          _this._fontAtlas = null;
          _this._letterTexture = null;
          _this._contentWidth = 0;
          _this._textStyle = null;
          _this._textLayout = null;
          _this._textRenderData = null;
          _this._textLayoutData = null;
          _this._ttfSpriteFrame = null;
          _this._textStyle = new TextStyle();
          _this._textLayout = new TextLayout();
          _this._textLayoutData = new TextOutputLayoutData();
          _this._textRenderData = new TextOutputRenderData();
          return _this;
        }
        var _proto = Label.prototype;
        _proto.onEnable = function onEnable() {
          _UIRenderer.prototype.onEnable.call(this);
          if (!this._font && !this._isSystemFontUsed) {
            this.useSystemFont = true;
          }
          if (this._isSystemFontUsed && !this._fontFamily) {
            this.fontFamily = 'Arial';
          }
          this._applyFontTexture();
        };
        _proto.onDestroy = function onDestroy() {
          if (this._assembler && this._assembler.resetAssemblerData) {
            this._assembler.resetAssemblerData(this._assemblerData);
          }
          this._assemblerData = null;
          if (this._ttfSpriteFrame) {
            this._ttfSpriteFrame._resetDynamicAtlasFrame();
            var tex = this._ttfSpriteFrame.texture;
            this._ttfSpriteFrame.destroy();
            if (tex) {
              var tex2d = tex;
              if (tex2d.image) {
                tex2d.image.destroy();
              }
              tex.destroy();
            }
            this._ttfSpriteFrame = null;
          }
          this._letterTexture = null;
          _UIRenderer.prototype.onDestroy.call(this);
        };
        _proto.updateRenderData = function updateRenderData(force) {
          if (force === void 0) {
            force = false;
          }
          if (force) {
            this._flushAssembler();
            if (this.renderData) this.renderData.vertDirty = true;
            this._applyFontTexture();
          }
          if (this._assembler) {
            this._assembler.updateRenderData(this);
          }
        };
        _proto._render = function _render(render) {
          render.commitComp(this, this.renderData, this._texture, this._assembler, null);
        };
        _proto._updateColor = function _updateColor() {
          _UIRenderer.prototype._updateColor.call(this);
          this.markForUpdateRenderData();
        };
        _proto.setEntityColor = function setEntityColor(color) {
        };
        _proto._canRender = function _canRender() {
          if (!_UIRenderer.prototype._canRender.call(this) || !this._string) {
            return false;
          }
          var font = this._font;
          if (font && font instanceof BitmapFont) {
            var spriteFrame = font.spriteFrame;
            if (!spriteFrame || !spriteFrame.texture) {
              return false;
            }
          }
          return true;
        };
        _proto._flushAssembler = function _flushAssembler() {
          var assembler = Label.Assembler.getAssembler(this);
          if (this._assembler !== assembler) {
            this.destroyRenderData();
            this._assembler = assembler;
            this.textStyle.reset();
            this.textLayout.reset();
            this.textLayoutData.reset();
            this.textRenderData.reset();
          }
          if (!this.renderData) {
            if (this._assembler && this._assembler.createData) {
              this._renderData = this._assembler.createData(this);
              this.renderData.material = this.material;
              this._updateColor();
            }
          }
        };
        _proto._applyFontTexture = function _applyFontTexture() {
          this.markForUpdateRenderData();
          var font = this._font;
          if (font instanceof BitmapFont) {
            var spriteFrame = font.spriteFrame;
            if (spriteFrame && spriteFrame.texture) {
              this._texture = spriteFrame;
              if (this.renderData) {
                this.renderData.textureDirty = true;
              }
              this.changeMaterialForDefine();
              if (this._assembler) {
                this._assembler.updateRenderData(this);
              }
            }
          } else {
            if (this.cacheMode === CacheMode.CHAR) {
              this._letterTexture = this._assembler.getAssemblerData();
              this._texture = this._letterTexture;
            } else if (!this._ttfSpriteFrame) {
              this._ttfSpriteFrame = new SpriteFrame();
              this._assemblerData = this._assembler.getAssemblerData();
              var image = new ImageAsset(this._assemblerData.canvas);
              var texture = new Texture2D();
              texture.image = image;
              this._ttfSpriteFrame.texture = texture;
            }
            if (this.cacheMode !== CacheMode.CHAR) {
              this._texture = this._ttfSpriteFrame;
            }
            this.changeMaterialForDefine();
          }
        };
        _proto.changeMaterialForDefine = function changeMaterialForDefine() {
          if (!this._texture) {
            return;
          }
          var value = false;
          if (this.cacheMode !== CacheMode.CHAR) {
            var spriteFrame = this._texture;
            var texture = spriteFrame.texture;
            if (texture instanceof TextureBase) {
              var format = texture.getPixelFormat();
              value = format === PixelFormat.RGBA_ETC1 || format === PixelFormat.RGB_A_PVRTC_4BPPV1 || format === PixelFormat.RGB_A_PVRTC_2BPPV1;
            }
          }
          if (value) {
            this._instanceMaterialType = InstanceMaterialType.USE_ALPHA_SEPARATED;
          } else {
            this._instanceMaterialType = InstanceMaterialType.ADD_COLOR_AND_TEXTURE;
          }
          this.updateMaterial();
        };
        _proto._updateBlendFunc = function _updateBlendFunc() {
          _UIRenderer.prototype._updateBlendFunc.call(this);
        };
        _createClass(Label, [{
          key: "string",
          get: function get() {
            return this._string;
          },
          set: function set(value) {
            if (value === null || value === undefined) {
              value = '';
            } else {
              value = value.toString();
            }
            if (this._string === value) {
              return;
            }
            this._string = value;
            this.markForUpdateRenderData();
          }
        }, {
          key: "horizontalAlign",
          get: function get() {
            return this._horizontalAlign;
          },
          set: function set(value) {
            if (this._horizontalAlign === value) {
              return;
            }
            this._horizontalAlign = value;
            this.markForUpdateRenderData();
          }
        }, {
          key: "verticalAlign",
          get: function get() {
            return this._verticalAlign;
          },
          set: function set(value) {
            if (this._verticalAlign === value) {
              return;
            }
            this._verticalAlign = value;
            this.markForUpdateRenderData();
          }
        }, {
          key: "actualFontSize",
          get: function get() {
            return this._actualFontSize;
          },
          set: function set(value) {
            this._actualFontSize = value;
          }
        }, {
          key: "fontSize",
          get: function get() {
            return this._fontSize;
          },
          set: function set(value) {
            if (this._fontSize === value) {
              return;
            }
            this._fontSize = value;
            this.markForUpdateRenderData();
          }
        }, {
          key: "lineHeight",
          get: function get() {
            return this._lineHeight;
          },
          set: function set(value) {
            if (this._lineHeight === value) {
              return;
            }
            this._lineHeight = value;
            this.markForUpdateRenderData();
          }
        }, {
          key: "spacingX",
          get: function get() {
            return this._spacingX;
          },
          set: function set(value) {
            if (this._spacingX === value) {
              return;
            }
            this._spacingX = value;
            this.markForUpdateRenderData();
          }
        }, {
          key: "overflow",
          get: function get() {
            return this._overflow;
          },
          set: function set(value) {
            if (this._overflow === value) {
              return;
            }
            this._overflow = value;
            this.markForUpdateRenderData();
          }
        }, {
          key: "enableWrapText",
          get: function get() {
            return this._enableWrapText;
          },
          set: function set(value) {
            if (this._enableWrapText === value) {
              return;
            }
            this._enableWrapText = value;
            this.markForUpdateRenderData();
          }
        }, {
          key: "useSystemFont",
          get: function get() {
            return this._isSystemFontUsed;
          },
          set: function set(value) {
            if (this._isSystemFontUsed === value) {
              return;
            }
            this.destroyRenderData();
            this._isSystemFontUsed = !!value;
            if (value) {
              this.font = null;
            }
            this._flushAssembler();
            this.markForUpdateRenderData();
          }
        }, {
          key: "fontFamily",
          get: function get() {
            return this._fontFamily;
          },
          set: function set(value) {
            if (this._fontFamily === value) {
              return;
            }
            this._fontFamily = value;
            this.markForUpdateRenderData();
          }
        }, {
          key: "font",
          get: function get() {
            return this._font;
          },
          set: function set(value) {
            if (this._font === value) {
              return;
            }
            this._isSystemFontUsed = !value;
            this._font = value;
            this.destroyRenderData();
            this._fontAtlas = null;
            this.updateRenderData(true);
          }
        }, {
          key: "cacheMode",
          get: function get() {
            return this._cacheMode;
          },
          set: function set(value) {
            if (this._cacheMode === value) {
              return;
            }
            if (this._cacheMode === CacheMode.BITMAP && !(this._font instanceof BitmapFont) && this._ttfSpriteFrame) {
              this._ttfSpriteFrame._resetDynamicAtlasFrame();
            }
            if (this._cacheMode === CacheMode.CHAR) {
              this._ttfSpriteFrame = null;
            }
            this._cacheMode = value;
            this.updateRenderData(true);
          }
        }, {
          key: "isBold",
          get: function get() {
            return this._isBold;
          },
          set: function set(value) {
            if (this._isBold === value) {
              return;
            }
            this._isBold = value;
            this.markForUpdateRenderData();
          }
        }, {
          key: "isItalic",
          get: function get() {
            return this._isItalic;
          },
          set: function set(value) {
            if (this._isItalic === value) {
              return;
            }
            this._isItalic = value;
            this.markForUpdateRenderData();
          }
        }, {
          key: "isUnderline",
          get: function get() {
            return this._isUnderline;
          },
          set: function set(value) {
            if (this._isUnderline === value) {
              return;
            }
            this._isUnderline = value;
            this.markForUpdateRenderData();
          }
        }, {
          key: "underlineHeight",
          get: function get() {
            return this._underlineHeight;
          },
          set: function set(value) {
            if (this._underlineHeight === value) return;
            this._underlineHeight = value;
            this.markForUpdateRenderData();
          }
        }, {
          key: "spriteFrame",
          get: function get() {
            return this._texture;
          }
        }, {
          key: "ttfSpriteFrame",
          get: function get() {
            return this._ttfSpriteFrame;
          }
        }, {
          key: "assemblerData",
          get: function get() {
            return this._assemblerData;
          }
        }, {
          key: "fontAtlas",
          get: function get() {
            return this._fontAtlas;
          },
          set: function set(value) {
            this._fontAtlas = value;
          }
        }, {
          key: "_bmFontOriginalSize",
          get: function get() {
            if (this._font instanceof BitmapFont) {
              return this._font.fontSize;
            } else {
              return -1;
            }
          }
        }, {
          key: "textStyle",
          get: function get() {
            return this._textStyle;
          }
        }, {
          key: "textLayout",
          get: function get() {
            return this._textLayout;
          }
        }, {
          key: "textRenderData",
          get: function get() {
            return this._textRenderData;
          }
        }, {
          key: "textLayoutData",
          get: function get() {
            return this._textLayoutData;
          }
        }, {
          key: "contentWidth",
          get: function get() {
            return this._contentWidth;
          },
          set: function set(val) {
            this._contentWidth = val;
          }
        }]);
        return Label;
      }(UIRenderer), _class3$y.HorizontalAlign = HorizontalTextAlignment, _class3$y.VerticalAlign = VerticalTextAlignment, _class3$y.Overflow = Overflow$1, _class3$y.CacheMode = CacheMode, _class3$y._canvasPool = CanvasPool.getInstance(), _class3$y), (_applyDecoratedDescriptor(_class2$21.prototype, "horizontalAlign", [_dec3$1h], Object.getOwnPropertyDescriptor(_class2$21.prototype, "horizontalAlign"), _class2$21.prototype), _applyDecoratedDescriptor(_class2$21.prototype, "verticalAlign", [_dec4$W], Object.getOwnPropertyDescriptor(_class2$21.prototype, "verticalAlign"), _class2$21.prototype), _applyDecoratedDescriptor(_class2$21.prototype, "overflow", [_dec5$M], Object.getOwnPropertyDescriptor(_class2$21.prototype, "overflow"), _class2$21.prototype), _applyDecoratedDescriptor(_class2$21.prototype, "font", [_dec6$w], Object.getOwnPropertyDescriptor(_class2$21.prototype, "font"), _class2$21.prototype), _applyDecoratedDescriptor(_class2$21.prototype, "cacheMode", [_dec7$p], Object.getOwnPropertyDescriptor(_class2$21.prototype, "cacheMode"), _class2$21.prototype), _initializer$1T = applyDecoratedInitializer(_class2$21.prototype, "_string", [serializable$j], function () {
        return 'label';
      }), _initializer2$1w = applyDecoratedInitializer(_class2$21.prototype, "_horizontalAlign", [serializable$j], function () {
        return HorizontalTextAlignment.CENTER;
      }), _initializer3$10 = applyDecoratedInitializer(_class2$21.prototype, "_verticalAlign", [serializable$j], function () {
        return VerticalTextAlignment.CENTER;
      }), _initializer4$O = applyDecoratedInitializer(_class2$21.prototype, "_actualFontSize", [serializable$j], function () {
        return 0;
      }), _initializer5$B = applyDecoratedInitializer(_class2$21.prototype, "_fontSize", [serializable$j], function () {
        return 40;
      }), _initializer6$t = applyDecoratedInitializer(_class2$21.prototype, "_fontFamily", [serializable$j], function () {
        return 'Arial';
      }), _initializer7$n = applyDecoratedInitializer(_class2$21.prototype, "_lineHeight", [serializable$j], function () {
        return 40;
      }), _initializer8$m = applyDecoratedInitializer(_class2$21.prototype, "_overflow", [serializable$j], function () {
        return Overflow$1.NONE;
      }), _initializer9$k = applyDecoratedInitializer(_class2$21.prototype, "_enableWrapText", [serializable$j], function () {
        return true;
      }), _initializer10$i = applyDecoratedInitializer(_class2$21.prototype, "_font", [serializable$j], function () {
        return null;
      }), _initializer11$f = applyDecoratedInitializer(_class2$21.prototype, "_isSystemFontUsed", [serializable$j], function () {
        return true;
      }), _initializer12$d = applyDecoratedInitializer(_class2$21.prototype, "_spacingX", [serializable$j], function () {
        return 0;
      }), _initializer13$c = applyDecoratedInitializer(_class2$21.prototype, "_isItalic", [serializable$j], function () {
        return false;
      }), _initializer14$a = applyDecoratedInitializer(_class2$21.prototype, "_isBold", [serializable$j], function () {
        return false;
      }), _initializer15$7 = applyDecoratedInitializer(_class2$21.prototype, "_isUnderline", [serializable$j], function () {
        return false;
      }), _initializer16$7 = applyDecoratedInitializer(_class2$21.prototype, "_underlineHeight", [serializable$j], function () {
        return 2;
      }), _initializer17$6 = applyDecoratedInitializer(_class2$21.prototype, "_cacheMode", [serializable$j], function () {
        return CacheMode.NONE;
      })), _class2$21)) || _class$2g) || _class$2g));
      legacyCC.Label = Label;

      var _stageOffset = 0;
      var _name2stageID = {};
      var config = {
        addStage: function addStage(name) {
          if (_name2stageID[name] !== undefined) {
            return;
          }
          var stageID = 1 << _stageOffset;
          _name2stageID[name] = stageID;
          _stageOffset += 1;
        },
        stageID: function stageID(name) {
          var id = _name2stageID[name];
          if (id === undefined) {
            return -1;
          }
          return id;
        },
        stageIDs: function stageIDs(nameList) {
          var key = 0;
          for (var _iterator = _createForOfIteratorHelperLoose(nameList), _step; !(_step = _iterator()).done;) {
            var name = _step.value;
            var id = _name2stageID[name];
            if (id !== undefined) {
              key |= id;
            }
          }
          return key;
        }
      };

      function createIA(device, data) {
        if (!data.positions) {
          console.error('The data must have positions field');
          return null;
        }
        var verts = [];
        var vcount = data.positions.length / 3;
        for (var i = 0; i < vcount; ++i) {
          verts.push(data.positions[3 * i], data.positions[3 * i + 1], data.positions[3 * i + 2]);
          if (data.normals) {
            verts.push(data.normals[3 * i], data.normals[3 * i + 1], data.normals[3 * i + 2]);
          }
          if (data.uvs) {
            verts.push(data.uvs[2 * i], data.uvs[2 * i + 1]);
          }
          if (data.colors) {
            verts.push(data.colors[3 * i], data.colors[3 * i + 1], data.colors[3 * i + 2]);
          }
        }
        var vfmt = [];
        vfmt.push(new Attribute(AttributeName.ATTR_POSITION, Format.RGB32F));
        if (data.normals) {
          vfmt.push(new Attribute(AttributeName.ATTR_NORMAL, Format.RGB32F));
        }
        if (data.uvs) {
          vfmt.push(new Attribute(AttributeName.ATTR_TEX_COORD, Format.RG32F));
        }
        if (data.colors) {
          vfmt.push(new Attribute(AttributeName.ATTR_COLOR, Format.RGB32F));
        }
        var vb = device.createBuffer(new BufferInfo(BufferUsageBit.VERTEX | BufferUsageBit.TRANSFER_DST, MemoryUsageBit.DEVICE, verts.length * 4, verts.length * 4 / vcount));
        vb.update(new Float32Array(verts));
        var ib = null;
        if (data.indices) {
          ib = device.createBuffer(new BufferInfo(BufferUsageBit.INDEX | BufferUsageBit.TRANSFER_DST, MemoryUsageBit.DEVICE, data.indices.length * 2, 2));
          ib.update(new Uint16Array(data.indices));
        }
        return device.createInputAssembler(new InputAssemblerInfo(vfmt, [vb], ib));
      }

      var RenderQueue;
      (function (RenderQueue) {
        RenderQueue[RenderQueue["OPAQUE"] = 0] = "OPAQUE";
        RenderQueue[RenderQueue["TRANSPARENT"] = 1] = "TRANSPARENT";
        RenderQueue[RenderQueue["OVERLAY"] = 2] = "OVERLAY";
      })(RenderQueue || (RenderQueue = {}));
      var PassStage;
      (function (PassStage) {
        PassStage[PassStage["DEFAULT"] = 1] = "DEFAULT";
        PassStage[PassStage["FORWARD"] = 2] = "FORWARD";
        PassStage[PassStage["SHADOWCAST"] = 4] = "SHADOWCAST";
      })(PassStage || (PassStage = {}));

      function nearestPOT(num) {
        --num;
        num |= num >> 16;
        num |= num >> 8;
        num |= num >> 4;
        num |= num >> 2;
        num |= num >> 1;
        ++num;
        return num;
      }
      function roundUp(n, alignment) {
        return Math.ceil(n / alignment) * alignment;
      }
      var TextureBufferPool = function () {
        function TextureBufferPool(device) {
          this._device = void 0;
          this._format = Format.UNKNOWN;
          this._formatSize = 0;
          this._chunks = [];
          this._chunkCount = 0;
          this._handles = [];
          this._region0 = new BufferTextureCopy();
          this._region1 = new BufferTextureCopy();
          this._region2 = new BufferTextureCopy();
          this._roundUpFn = null;
          this._bufferViewCtor = Uint8Array;
          this._channels = 4;
          this._alignment = 1;
          this._device = device;
        }
        var _proto = TextureBufferPool.prototype;
        _proto.initialize = function initialize(info) {
          var formatInfo = FormatInfos[info.format];
          this._format = info.format;
          this._formatSize = formatInfo.size;
          this._channels = formatInfo.count;
          this._bufferViewCtor = getTypedArrayConstructor(formatInfo);
          this._roundUpFn = info.roundUpFn || null;
          this._alignment = info.alignment || 1;
          if (info.inOrderFree) {
            this.alloc = this._McDonaldAlloc;
          }
        };
        _proto.destroy = function destroy() {
          for (var i = 0; i < this._chunkCount; ++i) {
            var chunk = this._chunks[i];
            chunk.texture.destroy();
          }
          this._chunks.length = 0;
          this._handles.length = 0;
        };
        _proto.alloc = function alloc(size, chunkIdx) {
          size = roundUp(size, this._alignment);
          var index = -1;
          var start = -1;
          if (chunkIdx !== undefined) {
            index = chunkIdx;
            start = this._findAvailableSpace(size, index);
          }
          if (start < 0) {
            for (var i = 0; i < this._chunkCount; ++i) {
              index = i;
              start = this._findAvailableSpace(size, index);
              if (start >= 0) {
                break;
              }
            }
          }
          if (start >= 0) {
            var chunk = this._chunks[index];
            chunk.start += size;
            var handle = {
              chunkIdx: index,
              start: start,
              end: start + size,
              texture: chunk.texture
            };
            this._handles.push(handle);
            return handle;
          }
          var targetSize = Math.sqrt(size / this._formatSize);
          var texLength = this._roundUpFn && this._roundUpFn(targetSize, this._formatSize) || Math.max(1024, nearestPOT(targetSize));
          var newChunk = this._chunks[this.createChunk(texLength)];
          newChunk.start += size;
          var texHandle = {
            chunkIdx: this._chunkCount - 1,
            start: 0,
            end: size,
            texture: newChunk.texture
          };
          this._handles.push(texHandle);
          return texHandle;
        };
        _proto.free = function free(handle) {
          for (var i = 0; i < this._handles.length; ++i) {
            if (this._handles[i] === handle) {
              this._chunks[handle.chunkIdx].end = handle.end;
              this._handles.splice(i, 1);
              return;
            }
          }
        };
        _proto.createChunk = function createChunk(length) {
          var texSize = length * length * this._formatSize;
          debug("TextureBufferPool: Allocate chunk " + this._chunkCount + ", size: " + texSize + ", format: " + this._format);
          var texture = this._device.createTexture(new TextureInfo(TextureType.TEX2D, TextureUsageBit.SAMPLED | TextureUsageBit.TRANSFER_DST, this._format, length, length));
          var chunk = {
            texture: texture,
            size: texSize,
            start: 0,
            end: texSize
          };
          this._chunks[this._chunkCount] = chunk;
          return this._chunkCount++;
        };
        _proto.update = function update(handle, buffer) {
          var buffers = [];
          var regions = [];
          var start = handle.start / this._formatSize;
          var remainSize = buffer.byteLength / this._formatSize;
          var offsetX = start % handle.texture.width;
          var offsetY = Math.floor(start / handle.texture.width);
          var copySize = Math.min(handle.texture.width - offsetX, remainSize);
          var begin = 0;
          if (offsetX > 0) {
            this._region0.texOffset.x = offsetX;
            this._region0.texOffset.y = offsetY;
            this._region0.texExtent.width = copySize;
            this._region0.texExtent.height = 1;
            buffers.push(new this._bufferViewCtor(buffer, begin * this._formatSize, copySize * this._channels));
            regions.push(this._region0);
            offsetX = 0;
            offsetY += 1;
            remainSize -= copySize;
            begin += copySize;
          }
          if (remainSize > 0) {
            this._region1.texOffset.x = offsetX;
            this._region1.texOffset.y = offsetY;
            if (remainSize > handle.texture.width) {
              this._region1.texExtent.width = handle.texture.width;
              this._region1.texExtent.height = Math.floor(remainSize / handle.texture.width);
              copySize = this._region1.texExtent.width * this._region1.texExtent.height;
            } else {
              copySize = remainSize;
              this._region1.texExtent.width = copySize;
              this._region1.texExtent.height = 1;
            }
            buffers.push(new this._bufferViewCtor(buffer, begin * this._formatSize, copySize * this._channels));
            regions.push(this._region1);
            offsetX = 0;
            offsetY += this._region1.texExtent.height;
            remainSize -= copySize;
            begin += copySize;
          }
          if (remainSize > 0) {
            this._region2.texOffset.x = offsetX;
            this._region2.texOffset.y = offsetY;
            this._region2.texExtent.width = remainSize;
            this._region2.texExtent.height = 1;
            buffers.push(new this._bufferViewCtor(buffer, begin * this._formatSize, remainSize * this._channels));
            regions.push(this._region2);
          }
          this._device.copyBuffersToTexture(buffers, handle.texture, regions);
        };
        _proto._findAvailableSpace = function _findAvailableSpace(size, chunkIdx) {
          var chunk = this._chunks[chunkIdx];
          var isFound = false;
          var start = chunk.start;
          if (start + size <= chunk.size) {
            isFound = true;
          } else {
            start = 0;
            var handles = this._handles.filter(function (h) {
              return h.chunkIdx === chunkIdx;
            }).sort(function (a, b) {
              return a.start - b.start;
            });
            for (var i = 0; i < handles.length; i++) {
              var handle = handles[i];
              if (start + size <= handle.start) {
                isFound = true;
                break;
              }
              start = handle.end;
            }
            if (!isFound && start + size <= chunk.size) {
              isFound = true;
            }
          }
          return isFound ? start : -1;
        };
        _proto._McDonaldAlloc = function _McDonaldAlloc(size) {
          size = roundUp(size, this._alignment);
          for (var i = 0; i < this._chunkCount; ++i) {
            var chunk = this._chunks[i];
            var isFound = false;
            var start = chunk.start;
            if (start + size <= chunk.end) {
              isFound = true;
            } else if (start > chunk.end) {
              if (start + size <= chunk.size) {
                isFound = true;
              } else if (size <= chunk.end) {
                chunk.start = start = 0;
                isFound = true;
              }
            } else if (start === chunk.end) {
              chunk.start = start = 0;
              chunk.end = chunk.size;
              if (size <= chunk.end) {
                isFound = true;
              }
            }
            if (isFound) {
              chunk.start += size;
              var handle = {
                chunkIdx: i,
                start: start,
                end: start + size,
                texture: chunk.texture
              };
              this._handles.push(handle);
              return handle;
            }
          }
          var targetSize = Math.sqrt(size / this._formatSize);
          var texLength = this._roundUpFn && this._roundUpFn(targetSize, this._formatSize) || Math.max(1024, nearestPOT(targetSize));
          var newChunk = this._chunks[this.createChunk(texLength)];
          newChunk.start += size;
          var texHandle = {
            chunkIdx: this._chunkCount,
            start: 0,
            end: size,
            texture: newChunk.texture
          };
          this._handles.push(texHandle);
          return texHandle;
        };
        return TextureBufferPool;
      }();

      var NativeBufferPool = function () {
        function NativeBufferPool(dataType, entryBits, stride) {
          this._arrayBuffers = [];
          this._chunkSize = void 0;
          this._chunkSize = stride * (1 << entryBits);
        }
        var _proto = NativeBufferPool.prototype;
        _proto.allocateNewChunk = function allocateNewChunk() {
          return new ArrayBuffer(this._chunkSize);
        };
        return NativeBufferPool;
      }();

      var _Render2dViewDataType, _Render2dViewDataMemb, _NodeViewDataType, _NodeViewDataMembers, _PassViewDataType, _PassViewDataMembers, _AABBViewDataType, _AABBViewDataMembers;
      var contains = function contains(a, t) {
        for (var i = 0; i < a.length; ++i) {
          if (a[i] === t) return true;
        }
        return false;
      };
      var BufferDataType;
      (function (BufferDataType) {
        BufferDataType[BufferDataType["UINT32"] = 0] = "UINT32";
        BufferDataType[BufferDataType["FLOAT32"] = 1] = "FLOAT32";
        BufferDataType[BufferDataType["NEVER"] = 2] = "NEVER";
      })(BufferDataType || (BufferDataType = {}));
      var BufferPool = function () {
        function BufferPool(poolType, dataType, dataMembers, enumType, entryBits) {
          if (entryBits === void 0) {
            entryBits = 8;
          }
          this._dataType = void 0;
          this._dataMembers = void 0;
          this._elementCount = void 0;
          this._entryBits = void 0;
          this._stride = void 0;
          this._entriesPerChunk = void 0;
          this._entryMask = void 0;
          this._chunkMask = void 0;
          this._poolFlag = void 0;
          this._arrayBuffers = [];
          this._freeLists = [];
          this._uint32BufferViews = [];
          this._float32BufferViews = [];
          this._hasUint32 = false;
          this._hasFloat32 = false;
          this._nativePool = void 0;
          this._elementCount = enumType.COUNT;
          this._entryBits = entryBits;
          this._dataType = dataType;
          this._dataMembers = dataMembers;
          var bytesPerElement = 4;
          this._stride = bytesPerElement * this._elementCount;
          this._entriesPerChunk = 1 << entryBits;
          this._entryMask = this._entriesPerChunk - 1;
          this._poolFlag = 1 << 30;
          this._chunkMask = ~(this._entryMask | this._poolFlag);
          this._nativePool = new NativeBufferPool(poolType, entryBits, this._stride);
          var type = BufferDataType.NEVER;
          var hasFloat32 = false;
          var hasUint32 = false;
          for (var e in dataType) {
            hasFloat32 = this._hasFloat32;
            hasUint32 = this._hasUint32;
            if (hasUint32 && hasFloat32) {
              break;
            }
            type = dataType[e];
            if (!hasFloat32 && type === BufferDataType.FLOAT32) {
              this._hasFloat32 = true;
            } else if (!hasUint32 && type === BufferDataType.UINT32) {
              this._hasUint32 = true;
            }
          }
        }
        var _proto = BufferPool.prototype;
        _proto.alloc = function alloc() {
          var i = 0;
          for (; i < this._freeLists.length; i++) {
            var list = this._freeLists[i];
            if (list.length) {
              var j = list[list.length - 1];
              list.length--;
              return (i << this._entryBits) + j + this._poolFlag;
            }
          }
          var buffer = this._nativePool.allocateNewChunk();
          var float32BufferViews = [];
          var uint32BufferViews = [];
          var freeList = [];
          var hasFloat32 = this._hasFloat32;
          var hasUint32 = this._hasUint32;
          for (var _j = 0; _j < this._entriesPerChunk; _j++) {
            if (hasFloat32) {
              float32BufferViews.push(new Float32Array(buffer, this._stride * _j, this._elementCount));
            }
            if (hasUint32) {
              uint32BufferViews.push(new Uint32Array(buffer, this._stride * _j, this._elementCount));
            }
            if (_j) {
              freeList.push(_j);
            }
          }
          if (hasUint32) {
            this._uint32BufferViews.push(uint32BufferViews);
          }
          if (hasFloat32) {
            this._float32BufferViews.push(float32BufferViews);
          }
          this._freeLists.push(freeList);
          this._arrayBuffers.push(buffer);
          var handle = (i << this._entryBits) + this._poolFlag;
          return handle;
        };
        _proto.getBuffer = function getBuffer(handle) {
          var chunk = (this._chunkMask & handle) >> this._entryBits;
          var entry = this._entryMask & handle;
          var bufferViews = this._hasFloat32 ? this._float32BufferViews : this._uint32BufferViews;
          if ((!handle || chunk < 0 || chunk >= bufferViews.length || entry < 0 || entry >= this._entriesPerChunk || contains(this._freeLists[chunk], entry))) {
            console.warn('invalid buffer pool handle');
            return [];
          }
          return bufferViews[chunk][entry];
        };
        _proto.getTypedArray = function getTypedArray(handle, element) {
          var chunk = (this._chunkMask & handle) >> this._entryBits;
          var entry = this._entryMask & handle;
          var bufferViews = this._dataType[element] === BufferDataType.UINT32 ? this._uint32BufferViews : this._float32BufferViews;
          if ((!handle || chunk < 0 || chunk >= bufferViews.length || entry < 0 || entry >= this._entriesPerChunk || contains(this._freeLists[chunk], entry))) {
            console.warn('invalid buffer pool handle');
            return [];
          }
          var index = element;
          var view = bufferViews[chunk][entry];
          var count = this._dataMembers[element];
          return view.subarray(index, index + count);
        };
        _proto.free = function free(handle) {
          var chunk = (this._chunkMask & handle) >> this._entryBits;
          var entry = this._entryMask & handle;
          if ((!handle || chunk < 0 || chunk >= this._freeLists.length || entry < 0 || entry >= this._entriesPerChunk || contains(this._freeLists[chunk], entry))) {
            console.warn('invalid buffer pool handle');
            return;
          }
          var bufferViews = this._hasUint32 ? this._uint32BufferViews : this._float32BufferViews;
          bufferViews[chunk][entry].fill(0);
          this._freeLists[chunk].push(entry);
        };
        return BufferPool;
      }();
      var PoolType;
      (function (PoolType) {
        PoolType[PoolType["NODE"] = 0] = "NODE";
        PoolType[PoolType["PASS"] = 1] = "PASS";
        PoolType[PoolType["AABB"] = 2] = "AABB";
        PoolType[PoolType["RENDER2D"] = 3] = "RENDER2D";
      })(PoolType || (PoolType = {}));
      var NULL_HANDLE = 0;
      var Render2dView;
      (function (Render2dView) {
        Render2dView[Render2dView["POSITION"] = 0] = "POSITION";
        Render2dView[Render2dView["UV"] = 3] = "UV";
        Render2dView[Render2dView["COLOR"] = 5] = "COLOR";
        Render2dView[Render2dView["COUNT"] = 9] = "COUNT";
      })(Render2dView || (Render2dView = {}));
      var Render2dViewDataType = (_Render2dViewDataType = {}, _Render2dViewDataType[Render2dView.POSITION] = BufferDataType.FLOAT32, _Render2dViewDataType[Render2dView.UV] = BufferDataType.FLOAT32, _Render2dViewDataType[Render2dView.COLOR] = BufferDataType.UINT32, _Render2dViewDataType[Render2dView.COUNT] = BufferDataType.NEVER, _Render2dViewDataType);
      var Render2dViewDataMembers = (_Render2dViewDataMemb = {}, _Render2dViewDataMemb[Render2dView.POSITION] = Render2dView.UV - Render2dView.POSITION, _Render2dViewDataMemb[Render2dView.UV] = Render2dView.COLOR - Render2dView.UV, _Render2dViewDataMemb[Render2dView.COLOR] = Render2dView.COUNT - Render2dView.COLOR, _Render2dViewDataMemb[Render2dView.COUNT] = 1, _Render2dViewDataMemb);
      var Render2dPool = new BufferPool(PoolType.RENDER2D, Render2dViewDataType, Render2dViewDataMembers, Render2dView);
      var NodeView;
      (function (NodeView) {
        NodeView[NodeView["DIRTY_FLAG"] = 0] = "DIRTY_FLAG";
        NodeView[NodeView["LAYER"] = 1] = "LAYER";
        NodeView[NodeView["WORLD_SCALE"] = 2] = "WORLD_SCALE";
        NodeView[NodeView["WORLD_POSITION"] = 5] = "WORLD_POSITION";
        NodeView[NodeView["WORLD_ROTATION"] = 8] = "WORLD_ROTATION";
        NodeView[NodeView["WORLD_MATRIX"] = 12] = "WORLD_MATRIX";
        NodeView[NodeView["LOCAL_SCALE"] = 28] = "LOCAL_SCALE";
        NodeView[NodeView["LOCAL_POSITION"] = 31] = "LOCAL_POSITION";
        NodeView[NodeView["LOCAL_ROTATION"] = 34] = "LOCAL_ROTATION";
        NodeView[NodeView["COUNT"] = 38] = "COUNT";
      })(NodeView || (NodeView = {}));
      var NodeViewDataType = (_NodeViewDataType = {}, _NodeViewDataType[NodeView.DIRTY_FLAG] = BufferDataType.UINT32, _NodeViewDataType[NodeView.LAYER] = BufferDataType.UINT32, _NodeViewDataType[NodeView.WORLD_SCALE] = BufferDataType.FLOAT32, _NodeViewDataType[NodeView.WORLD_POSITION] = BufferDataType.FLOAT32, _NodeViewDataType[NodeView.WORLD_ROTATION] = BufferDataType.FLOAT32, _NodeViewDataType[NodeView.WORLD_MATRIX] = BufferDataType.FLOAT32, _NodeViewDataType[NodeView.LOCAL_SCALE] = BufferDataType.FLOAT32, _NodeViewDataType[NodeView.LOCAL_POSITION] = BufferDataType.FLOAT32, _NodeViewDataType[NodeView.LOCAL_ROTATION] = BufferDataType.FLOAT32, _NodeViewDataType[NodeView.COUNT] = BufferDataType.NEVER, _NodeViewDataType);
      var NodeViewDataMembers = (_NodeViewDataMembers = {}, _NodeViewDataMembers[NodeView.DIRTY_FLAG] = NodeView.LAYER - NodeView.DIRTY_FLAG, _NodeViewDataMembers[NodeView.LAYER] = NodeView.WORLD_SCALE - NodeView.LAYER, _NodeViewDataMembers[NodeView.WORLD_SCALE] = NodeView.WORLD_POSITION - NodeView.WORLD_SCALE, _NodeViewDataMembers[NodeView.WORLD_POSITION] = NodeView.WORLD_ROTATION - NodeView.WORLD_POSITION, _NodeViewDataMembers[NodeView.WORLD_ROTATION] = NodeView.WORLD_MATRIX - NodeView.WORLD_ROTATION, _NodeViewDataMembers[NodeView.WORLD_MATRIX] = NodeView.LOCAL_SCALE - NodeView.WORLD_MATRIX, _NodeViewDataMembers[NodeView.LOCAL_SCALE] = NodeView.LOCAL_POSITION - NodeView.LOCAL_SCALE, _NodeViewDataMembers[NodeView.LOCAL_POSITION] = NodeView.LOCAL_ROTATION - NodeView.LOCAL_POSITION, _NodeViewDataMembers[NodeView.LOCAL_ROTATION] = NodeView.COUNT - NodeView.LOCAL_ROTATION, _NodeViewDataMembers[NodeView.COUNT] = 1, _NodeViewDataMembers);
      var NodePool$1 = new BufferPool(PoolType.NODE, NodeViewDataType, NodeViewDataMembers, NodeView);
      var PassView;
      (function (PassView) {
        PassView[PassView["PRIORITY"] = 0] = "PRIORITY";
        PassView[PassView["STAGE"] = 1] = "STAGE";
        PassView[PassView["PHASE"] = 2] = "PHASE";
        PassView[PassView["PRIMITIVE"] = 3] = "PRIMITIVE";
        PassView[PassView["BATCHING_SCHEME"] = 4] = "BATCHING_SCHEME";
        PassView[PassView["DYNAMIC_STATE"] = 5] = "DYNAMIC_STATE";
        PassView[PassView["HASH"] = 6] = "HASH";
        PassView[PassView["COUNT"] = 7] = "COUNT";
      })(PassView || (PassView = {}));
      var PassViewDataType = (_PassViewDataType = {}, _PassViewDataType[PassView.PRIORITY] = BufferDataType.UINT32, _PassViewDataType[PassView.STAGE] = BufferDataType.UINT32, _PassViewDataType[PassView.PHASE] = BufferDataType.UINT32, _PassViewDataType[PassView.PRIMITIVE] = BufferDataType.UINT32, _PassViewDataType[PassView.BATCHING_SCHEME] = BufferDataType.UINT32, _PassViewDataType[PassView.DYNAMIC_STATE] = BufferDataType.UINT32, _PassViewDataType[PassView.HASH] = BufferDataType.UINT32, _PassViewDataType[PassView.COUNT] = BufferDataType.NEVER, _PassViewDataType);
      var PassViewDataMembers = (_PassViewDataMembers = {}, _PassViewDataMembers[PassView.PRIORITY] = PassView.STAGE - PassView.PRIORITY, _PassViewDataMembers[PassView.STAGE] = PassView.PHASE - PassView.STAGE, _PassViewDataMembers[PassView.PHASE] = PassView.PRIMITIVE - PassView.PHASE, _PassViewDataMembers[PassView.PRIMITIVE] = PassView.BATCHING_SCHEME - PassView.PRIMITIVE, _PassViewDataMembers[PassView.BATCHING_SCHEME] = PassView.DYNAMIC_STATE - PassView.BATCHING_SCHEME, _PassViewDataMembers[PassView.DYNAMIC_STATE] = PassView.HASH - PassView.DYNAMIC_STATE, _PassViewDataMembers[PassView.HASH] = PassView.COUNT - PassView.HASH, _PassViewDataMembers[PassView.COUNT] = 1, _PassViewDataMembers);
      var PassPool = new BufferPool(PoolType.PASS, PassViewDataType, PassViewDataMembers, PassView);
      var AABBView;
      (function (AABBView) {
        AABBView[AABBView["CENTER"] = 0] = "CENTER";
        AABBView[AABBView["HALFEXTENTS"] = 3] = "HALFEXTENTS";
        AABBView[AABBView["COUNT"] = 6] = "COUNT";
      })(AABBView || (AABBView = {}));
      var AABBViewDataType = (_AABBViewDataType = {}, _AABBViewDataType[AABBView.CENTER] = BufferDataType.FLOAT32, _AABBViewDataType[AABBView.HALFEXTENTS] = BufferDataType.FLOAT32, _AABBViewDataType[AABBView.COUNT] = BufferDataType.NEVER, _AABBViewDataType);
      var AABBViewDataMembers = (_AABBViewDataMembers = {}, _AABBViewDataMembers[AABBView.CENTER] = AABBView.HALFEXTENTS - AABBView.CENTER, _AABBViewDataMembers[AABBView.HALFEXTENTS] = AABBView.COUNT - AABBView.HALFEXTENTS, _AABBViewDataMembers[AABBView.COUNT] = 1, _AABBViewDataMembers);
      var AABBPool = new BufferPool(PoolType.AABB, AABBViewDataType, AABBViewDataMembers, AABBView);

      var addStage = config.addStage;

      var renderer = /*#__PURE__*/Object.freeze({
        __proto__: null,
        addStage: addStage,
        scene: index,
        createIA: createIA,
        programLib: programLib,
        getDeviceShaderVersion: getDeviceShaderVersion,
        get RenderQueue () { return RenderQueue; },
        get PassStage () { return PassStage; },
        genHandle: genHandle,
        getTypeFromHandle: getTypeFromHandle,
        getBindingFromHandle: getBindingFromHandle,
        getCountFromHandle: getCountFromHandle,
        getOffsetFromHandle: getOffsetFromHandle,
        customizeType: customizeType,
        type2reader: type2reader,
        type2writer: type2writer,
        type2validator: type2validator,
        getDefaultFromType: getDefaultFromType,
        getStringFromType: getStringFromType,
        overrideMacros: overrideMacros,
        get BatchingSchemes () { return BatchingSchemes; },
        Pass: Pass,
        nearestPOT: nearestPOT,
        TextureBufferPool: TextureBufferPool,
        MaterialInstance: MaterialInstance,
        PassInstance: PassInstance,
        get PoolType () { return PoolType; },
        NULL_HANDLE: NULL_HANDLE,
        get Render2dView () { return Render2dView; },
        Render2dPool: Render2dPool,
        get NodeView () { return NodeView; },
        NodePool: NodePool$1,
        get PassView () { return PassView; },
        PassPool: PassPool,
        get AABBView () { return AABBView; },
        AABBPool: AABBPool,
        RenderScene: RenderScene
      });
      exports('ay', renderer);

      var LineCap;
      (function (LineCap) {
        LineCap[LineCap["BUTT"] = 0] = "BUTT";
        LineCap[LineCap["ROUND"] = 1] = "ROUND";
        LineCap[LineCap["SQUARE"] = 2] = "SQUARE";
      })(LineCap || (LineCap = {}));
      ccenum(LineCap);
      var LineJoin;
      (function (LineJoin) {
        LineJoin[LineJoin["BEVEL"] = 0] = "BEVEL";
        LineJoin[LineJoin["ROUND"] = 1] = "ROUND";
        LineJoin[LineJoin["MITER"] = 2] = "MITER";
      })(LineJoin || (LineJoin = {}));
      ccenum(LineJoin);
      var PointFlags;
      (function (PointFlags) {
        PointFlags[PointFlags["PT_CORNER"] = 1] = "PT_CORNER";
        PointFlags[PointFlags["PT_LEFT"] = 2] = "PT_LEFT";
        PointFlags[PointFlags["PT_BEVEL"] = 4] = "PT_BEVEL";
        PointFlags[PointFlags["PT_INNERBEVEL"] = 8] = "PT_INNERBEVEL";
      })(PointFlags || (PointFlags = {}));
      ccenum(PointFlags);

      var PI$1 = Math.PI;
      var min$1 = Math.min;
      var max$1 = Math.max;
      var cos$1 = Math.cos;
      var sin$1 = Math.sin;
      var abs = Math.abs;
      var sign = Math.sign;
      var KAPPA90 = 0.5522847493;
      function arc(ctx, cx, cy, r, startAngle, endAngle, counterclockwise) {
        counterclockwise = counterclockwise || false;
        var a = 0;
        var da = 0;
        var hda = 0;
        var kappa = 0;
        var dx = 0;
        var dy = 0;
        var x = 0;
        var y = 0;
        var tanx = 0;
        var tany = 0;
        var px = 0;
        var py = 0;
        var ptanx = 0;
        var ptany = 0;
        var i = 0;
        var ndivs = 0;
        da = endAngle - startAngle;
        if (counterclockwise) {
          if (abs(da) >= PI$1 * 2) {
            da = PI$1 * 2;
          } else {
            while (da < 0) {
              da += PI$1 * 2;
            }
          }
        } else if (abs(da) >= PI$1 * 2) {
          da = -PI$1 * 2;
        } else {
          while (da > 0) {
            da -= PI$1 * 2;
          }
        }
        ndivs = max$1(1, min$1(abs(da) / (PI$1 * 0.5) + 0.5, 5)) | 0;
        hda = da / ndivs / 2.0;
        kappa = abs(4.0 / 3.0 * (1 - cos$1(hda)) / sin$1(hda));
        if (!counterclockwise) {
          kappa = -kappa;
        }
        for (i = 0; i <= ndivs; i++) {
          a = startAngle + da * (i / ndivs);
          dx = cos$1(a);
          dy = sin$1(a);
          x = cx + dx * r;
          y = cy + dy * r;
          tanx = -dy * r * kappa;
          tany = dx * r * kappa;
          if (i === 0) {
            ctx.moveTo(x, y);
          } else {
            ctx.bezierCurveTo(px + ptanx, py + ptany, x - tanx, y - tany, x, y);
          }
          px = x;
          py = y;
          ptanx = tanx;
          ptany = tany;
        }
      }
      function ellipse(ctx, cx, cy, rx, ry) {
        ctx.moveTo(cx - rx, cy);
        ctx.bezierCurveTo(cx - rx, cy + ry * KAPPA90, cx - rx * KAPPA90, cy + ry, cx, cy + ry);
        ctx.bezierCurveTo(cx + rx * KAPPA90, cy + ry, cx + rx, cy + ry * KAPPA90, cx + rx, cy);
        ctx.bezierCurveTo(cx + rx, cy - ry * KAPPA90, cx + rx * KAPPA90, cy - ry, cx, cy - ry);
        ctx.bezierCurveTo(cx - rx * KAPPA90, cy - ry, cx - rx, cy - ry * KAPPA90, cx - rx, cy);
        ctx.close();
      }
      function roundRect(ctx, x, y, w, h, r) {
        if (r < 0.1) {
          ctx.rect(x, y, w, h);
        } else {
          var rx = min$1(r, abs(w) * 0.5) * sign(w);
          var ry = min$1(r, abs(h) * 0.5) * sign(h);
          ctx.moveTo(x, y + ry);
          ctx.lineTo(x, y + h - ry);
          ctx.bezierCurveTo(x, y + h - ry * (1 - KAPPA90), x + rx * (1 - KAPPA90), y + h, x + rx, y + h);
          ctx.lineTo(x + w - rx, y + h);
          ctx.bezierCurveTo(x + w - rx * (1 - KAPPA90), y + h, x + w, y + h - ry * (1 - KAPPA90), x + w, y + h - ry);
          ctx.lineTo(x + w, y + ry);
          ctx.bezierCurveTo(x + w, y + ry * (1 - KAPPA90), x + w - rx * (1 - KAPPA90), y, x + w - rx, y);
          ctx.lineTo(x + rx, y);
          ctx.bezierCurveTo(x + rx * (1 - KAPPA90), y, x, y + ry * (1 - KAPPA90), x, y + ry);
          ctx.close();
        }
      }
      function tesselateBezier(ctx, x1, y1, x2, y2, x3, y3, x4, y4, level, type) {
        var x12 = 0;
        var y12 = 0;
        var x23 = 0;
        var y23 = 0;
        var x34 = 0;
        var y34 = 0;
        var x123 = 0;
        var y123 = 0;
        var x234 = 0;
        var y234 = 0;
        var x1234 = 0;
        var y1234 = 0;
        var dx = 0;
        var dy = 0;
        var d2 = 0;
        var d3 = 0;
        if (level > 10) {
          return;
        }
        x12 = (x1 + x2) * 0.5;
        y12 = (y1 + y2) * 0.5;
        x23 = (x2 + x3) * 0.5;
        y23 = (y2 + y3) * 0.5;
        x34 = (x3 + x4) * 0.5;
        y34 = (y3 + y4) * 0.5;
        x123 = (x12 + x23) * 0.5;
        y123 = (y12 + y23) * 0.5;
        dx = x4 - x1;
        dy = y4 - y1;
        d2 = abs((x2 - x4) * dy - (y2 - y4) * dx);
        d3 = abs((x3 - x4) * dy - (y3 - y4) * dx);
        if ((d2 + d3) * (d2 + d3) < ctx.tessTol * (dx * dx + dy * dy)) {
          ctx.addPoint(x4, y4, type === 0 ? type | PointFlags.PT_BEVEL : type);
          return;
        }
        x234 = (x23 + x34) * 0.5;
        y234 = (y23 + y34) * 0.5;
        x1234 = (x123 + x234) * 0.5;
        y1234 = (y123 + y234) * 0.5;
        tesselateBezier(ctx, x1, y1, x12, y12, x123, y123, x1234, y1234, level + 1, 0);
        tesselateBezier(ctx, x1234, y1234, x234, y234, x34, y34, x4, y4, level + 1, type);
      }

      var Point = function (_Vec) {
        _inheritsLoose(Point, _Vec);
        function Point() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Vec.call.apply(_Vec, [this].concat(args)) || this;
          _this.dx = 0;
          _this.dy = 0;
          _this.dmx = 0;
          _this.dmy = 0;
          _this.flags = 0;
          _this.len = 0;
          return _this;
        }
        var _proto = Point.prototype;
        _proto.reset = function reset() {
          this.dx = 0;
          this.dy = 0;
          this.dmx = 0;
          this.dmy = 0;
          this.flags = 0;
          this.len = 0;
        };
        return Point;
      }(Vec2);
      var Path = function () {
        function Path() {
          this.closed = false;
          this.bevel = 0;
          this.complex = true;
          this.points = [];
        }
        var _proto2 = Path.prototype;
        _proto2.reset = function reset() {
          this.closed = false;
          this.bevel = 0;
          this.complex = true;
          this.points.length = 0;
        };
        return Path;
      }();
      var Impl = function () {
        function Impl(comp) {
          this.dataOffset = 0;
          this.updatePathOffset = false;
          this.pathLength = 0;
          this.pathOffset = 0;
          this.paths = [];
          this.tessTol = 0.25;
          this.distTol = 0.01;
          this.fillColor = Color$1.WHITE.clone();
          this.lineCap = LineCap.BUTT;
          this.strokeColor = Color$1.BLACK.clone();
          this.lineJoin = LineJoin.MITER;
          this.lineWidth = 0;
          this.pointsOffset = 0;
          this._commandX = 0;
          this._commandY = 0;
          this._points = [];
          this._renderDataList = [];
          this._curPath = null;
          this._comp = void 0;
          this._comp = comp;
        }
        var _proto3 = Impl.prototype;
        _proto3.moveTo = function moveTo(x, y) {
          if (this.updatePathOffset) {
            this.pathOffset = this.pathLength;
            this.updatePathOffset = false;
          }
          this._addPath();
          this.addPoint(x, y, PointFlags.PT_CORNER);
          this._commandX = x;
          this._commandY = y;
        };
        _proto3.lineTo = function lineTo(x, y) {
          this.addPoint(x, y, PointFlags.PT_CORNER);
          this._commandX = x;
          this._commandY = y;
        };
        _proto3.bezierCurveTo = function bezierCurveTo(c1x, c1y, c2x, c2y, x, y) {
          var path = this._curPath;
          var last = path.points[path.points.length - 1];
          if (!last) {
            return;
          }
          if (last.x === c1x && last.y === c1y && c2x === x && c2y === y) {
            this.lineTo(x, y);
            return;
          }
          tesselateBezier(this, last.x, last.y, c1x, c1y, c2x, c2y, x, y, 0, PointFlags.PT_CORNER);
          this._commandX = x;
          this._commandY = y;
        };
        _proto3.quadraticCurveTo = function quadraticCurveTo(cx, cy, x, y) {
          var x0 = this._commandX;
          var y0 = this._commandY;
          this.bezierCurveTo(x0 + 2.0 / 3.0 * (cx - x0), y0 + 2.0 / 3.0 * (cy - y0), x + 2.0 / 3.0 * (cx - x), y + 2.0 / 3.0 * (cy - y), x, y);
        };
        _proto3.arc = function arc$1(cx, cy, r, startAngle, endAngle, counterclockwise) {
          arc(this, cx, cy, r, startAngle, endAngle, counterclockwise);
        };
        _proto3.ellipse = function ellipse$1(cx, cy, rx, ry) {
          ellipse(this, cx, cy, rx, ry);
          this._curPath.complex = false;
        };
        _proto3.circle = function circle(cx, cy, r) {
          ellipse(this, cx, cy, r, r);
          this._curPath.complex = false;
        };
        _proto3.rect = function rect(x, y, w, h) {
          this.moveTo(x, y);
          this.lineTo(x + w, y);
          this.lineTo(x + w, y + h);
          this.lineTo(x, y + h);
          this.close();
          this._curPath.complex = false;
        };
        _proto3.roundRect = function roundRect$1(x, y, w, h, r) {
          roundRect(this, x, y, w, h, r);
          this._curPath.complex = false;
        };
        _proto3.clear = function clear() {
          this.pathLength = 0;
          this.pathOffset = 0;
          this.pointsOffset = 0;
          this.dataOffset = 0;
          this._curPath = null;
          this.paths.length = 0;
          this._points.length = 0;
          var dataList = this._renderDataList;
          for (var i = 0, l = dataList.length; i < l; i++) {
            var data = dataList[i];
            if (!data) {
              continue;
            }
            MeshRenderData.remove(data);
            data.removeRenderDrawInfo(this._comp);
          }
          this._renderDataList.length = 0;
        };
        _proto3.close = function close() {
          this._curPath.closed = true;
        };
        _proto3.requestRenderData = function requestRenderData() {
          var renderData = MeshRenderData.add();
          this._renderDataList.push(renderData);
          return renderData;
        };
        _proto3.getRenderDataList = function getRenderDataList() {
          if (this._renderDataList.length === 0) {
            this.requestRenderData();
          }
          return this._renderDataList;
        };
        _proto3.addPoint = function addPoint(x, y, flags) {
          var path = this._curPath;
          if (!path) {
            return;
          }
          var points = this._points;
          var pathPoints = path.points;
          var offset = this.pointsOffset++;
          var pt = points[offset];
          if (!pt) {
            pt = new Point(x, y);
            points.push(pt);
          } else {
            pt.x = x;
            pt.y = y;
          }
          pt.flags = flags;
          pathPoints.push(pt);
        };
        _proto3._addPath = function _addPath() {
          var offset = this.pathLength;
          var path = this.paths[offset];
          if (!path) {
            path = new Path();
            this.paths.push(path);
          } else {
            path.reset();
          }
          this.pathLength++;
          this._curPath = path;
          return path;
        };
        return Impl;
      }();

      var _dec$2g, _dec2$1M, _dec3$1g, _dec4$V, _class$2f, _class2$20, _initializer$1S, _initializer2$1v, _initializer3$$, _initializer4$N, _initializer5$A, _initializer6$s, _class3$x;
      var attributes = vfmtPosColor.concat([new Attribute('a_dist', Format.R32F)]);
      var componentPerVertex = getComponentPerVertex(attributes);
      var stride = getAttributeStride(attributes);
      var Graphics = exports('G', (_dec$2g = ccclass$n('cc.Graphics'), _dec2$1M = executionOrder$1(110), _dec3$1g = type$7(LineJoin), _dec4$V = type$7(LineCap), _dec$2g(_class$2f = _dec2$1M(_class$2f = (_class2$20 = (_class3$x = function (_UIRenderer) {
        _inheritsLoose(Graphics, _UIRenderer);
        function Graphics() {
          var _this;
          _this = _UIRenderer.call(this) || this;
          _this.impl = null;
          _this.model = null;
          _this._lineWidth = _initializer$1S && _initializer$1S();
          _this._strokeColor = _initializer2$1v && _initializer2$1v();
          _this._lineJoin = _initializer3$$ && _initializer3$$();
          _this._lineCap = _initializer4$N && _initializer4$N();
          _this._fillColor = _initializer5$A && _initializer5$A();
          _this._miterLimit = _initializer6$s && _initializer6$s();
          _this._isDrawing = false;
          _this._isNeedUploadData = true;
          _this._graphicsUseSubMeshes = [];
          _this._instanceMaterialType = InstanceMaterialType.ADD_COLOR;
          _this.impl = new Impl(_assertThisInitialized(_this));
          return _this;
        }
        var _proto = Graphics.prototype;
        _proto.onRestore = function onRestore() {
          if (!this.impl) {
            this._flushAssembler();
          }
        };
        _proto.onLoad = function onLoad() {
          _UIRenderer.prototype.onLoad.call(this);
          {
            this.model = director.root.createModel(Model);
            this.model.node = this.model.transform = this.node;
          }
          this._flushAssembler();
        };
        _proto.onEnable = function onEnable() {
          _UIRenderer.prototype.onEnable.call(this);
          this._updateMtlForGraphics();
        };
        _proto.onDestroy = function onDestroy() {
          this._sceneGetter = null;
          {
            if (this.model) {
              director.root.destroyModel(this.model);
              this.model = null;
            }
            var subMeshLength = this._graphicsUseSubMeshes.length;
            if (subMeshLength > 0) {
              for (var i = 0; i < subMeshLength; ++i) {
                this._graphicsUseSubMeshes[i].destroy();
              }
              this._graphicsUseSubMeshes.length = 0;
            }
          }
          if (this.impl) {
            this._isDrawing = false;
            this.impl.clear();
            this.impl = null;
          }
          _UIRenderer.prototype.onDestroy.call(this);
        };
        _proto.moveTo = function moveTo(x, y) {
          if (!this.impl) {
            return;
          }
          this.impl.moveTo(x, y);
        };
        _proto.lineTo = function lineTo(x, y) {
          if (!this.impl) {
            return;
          }
          this.impl.lineTo(x, y);
        };
        _proto.bezierCurveTo = function bezierCurveTo(c1x, c1y, c2x, c2y, x, y) {
          if (!this.impl) {
            return;
          }
          this.impl.bezierCurveTo(c1x, c1y, c2x, c2y, x, y);
        };
        _proto.quadraticCurveTo = function quadraticCurveTo(cx, cy, x, y) {
          if (!this.impl) {
            return;
          }
          this.impl.quadraticCurveTo(cx, cy, x, y);
        };
        _proto.arc = function arc(cx, cy, r, startAngle, endAngle, counterclockwise) {
          if (!this.impl) {
            return;
          }
          this.impl.arc(cx, cy, r, startAngle, endAngle, counterclockwise);
        };
        _proto.ellipse = function ellipse(cx, cy, rx, ry) {
          if (!this.impl) {
            return;
          }
          this.impl.ellipse(cx, cy, rx, ry);
        };
        _proto.circle = function circle(cx, cy, r) {
          if (!this.impl) {
            return;
          }
          this.impl.circle(cx, cy, r);
        };
        _proto.rect = function rect(x, y, w, h) {
          if (!this.impl) {
            return;
          }
          this.impl.rect(x, y, w, h);
        };
        _proto.roundRect = function roundRect(x, y, w, h, r) {
          if (!this.impl) {
            return;
          }
          this.impl.roundRect(x, y, w, h, r);
        };
        _proto.fillRect = function fillRect(x, y, w, h) {
          this.rect(x, y, w, h);
          this.fill();
        };
        _proto.clear = function clear() {
          if (!this.impl) {
            return;
          }
          this.impl.clear();
          this._isDrawing = false;
          if (this.model) {
            for (var i = 0; i < this.model.subModels.length; i++) {
              var subModel = this.model.subModels[i];
              subModel.inputAssembler.indexCount = 0;
            }
          }
          this.markForUpdateRenderData();
        };
        _proto.close = function close() {
          if (!this.impl) {
            return;
          }
          this.impl.close();
        };
        _proto.stroke = function stroke() {
          if (!this._assembler) {
            this._flushAssembler();
          }
          this._isDrawing = true;
          this._isNeedUploadData = true;
          this._assembler.stroke(this);
        };
        _proto.fill = function fill() {
          if (!this._assembler) {
            this._flushAssembler();
          }
          this._isDrawing = true;
          this._isNeedUploadData = true;
          this._assembler.fill(this);
        };
        _proto._updateMtlForGraphics = function _updateMtlForGraphics() {
          var mat;
          if (this._customMaterial) {
            mat = this.getMaterialInstance(0);
          } else {
            mat = builtinResMgr.get('ui-graphics-material');
            this.setSharedMaterial(mat, 0);
            mat = this.getMaterialInstance(0);
            mat.recompileShaders({
              USE_LOCAL: true
            });
          }
        };
        _proto.activeSubModel = function activeSubModel(idx) {
          if (!this.model) {
            warnID(4500, this.node.name);
            return;
          }
          if (this.model.subModels.length <= idx) {
            var gfxDevice = deviceManager.gfxDevice;
            var vertexBuffer = gfxDevice.createBuffer(new BufferInfo(BufferUsageBit.VERTEX | BufferUsageBit.TRANSFER_DST, MemoryUsageBit.DEVICE, 65535 * stride, stride));
            var indexBuffer = gfxDevice.createBuffer(new BufferInfo(BufferUsageBit.INDEX | BufferUsageBit.TRANSFER_DST, MemoryUsageBit.DEVICE, 65535 * Uint16Array.BYTES_PER_ELEMENT * 2, Uint16Array.BYTES_PER_ELEMENT));
            var renderMesh = new RenderingSubMesh([vertexBuffer], attributes, PrimitiveMode.TRIANGLE_LIST, indexBuffer);
            renderMesh.subMeshIdx = 0;
            this.model.initSubModel(idx, renderMesh, this.getMaterialInstance(0));
            this._graphicsUseSubMeshes.push(renderMesh);
          }
        };
        _proto._uploadData = function _uploadData() {
          var impl = this.impl;
          if (!impl) {
            return;
          }
          var renderDataList = impl && impl.getRenderDataList();
          if (renderDataList.length <= 0 || !this.model) {
            return;
          }
          var subModelList = this.model.subModels;
          for (var i = 0; i < renderDataList.length; i++) {
            var renderData = renderDataList[i];
            var ia = subModelList[i].inputAssembler;
            if (renderData.lastFilledVertex === renderData.vertexStart) {
              continue;
            }
            var vb = new Float32Array(renderData.vData.buffer, 0, renderData.vertexStart * componentPerVertex);
            ia.vertexBuffers[0].update(vb);
            ia.vertexCount = renderData.vertexStart;
            var ib = new Uint16Array(renderData.iData.buffer, 0, renderData.indexStart);
            ia.indexBuffer.update(ib);
            ia.indexCount = renderData.indexStart;
            renderData.lastFilledVertex = renderData.vertexStart;
            renderData.lastFilledIndex = renderData.indexStart;
          }
          this._isNeedUploadData = false;
        };
        _proto._render = function _render(render) {
          if (this._isNeedUploadData) {
            if (this.impl) {
              var renderDataList = this.impl.getRenderDataList();
              var len = this.model.subModels.length;
              if (renderDataList.length > len) {
                for (var i = len; i < renderDataList.length; i++) {
                  this.activeSubModel(i);
                }
              }
            }
            this._uploadData();
          }
          render.commitModel(this, this.model, this.getMaterialInstance(0));
        };
        _proto._flushAssembler = function _flushAssembler() {
          var assembler = Graphics.Assembler.getAssembler(this);
          if (this._assembler !== assembler) {
            this._assembler = assembler;
          }
        };
        _proto._canRender = function _canRender() {
          if (!_UIRenderer.prototype._canRender.call(this)) {
            return false;
          }
          {
            return !!this.model && this._isDrawing;
          }
        };
        _proto.updateRenderer = function updateRenderer() {
          _UIRenderer.prototype.updateRenderer.call(this);
        };
        _proto.createRenderEntity = function createRenderEntity() {
          return new RenderEntity(RenderEntityType.DYNAMIC);
        };
        _createClass(Graphics, [{
          key: "lineWidth",
          get: function get() {
            return this._lineWidth;
          },
          set: function set(value) {
            this._lineWidth = value;
            if (!this.impl) {
              return;
            }
            this.impl.lineWidth = value;
          }
        }, {
          key: "lineJoin",
          get: function get() {
            return this._lineJoin;
          },
          set: function set(value) {
            this._lineJoin = value;
            if (!this.impl) {
              return;
            }
            this.impl.lineJoin = value;
          }
        }, {
          key: "lineCap",
          get: function get() {
            return this._lineCap;
          },
          set: function set(value) {
            this._lineCap = value;
            if (!this.impl) {
              return;
            }
            this.impl.lineCap = value;
          }
        }, {
          key: "strokeColor",
          get: function get() {
            return this._strokeColor;
          },
          set: function set(value) {
            if (!this.impl) {
              return;
            }
            this._strokeColor.set(value);
            this.impl.strokeColor = this._strokeColor;
          }
        }, {
          key: "fillColor",
          get: function get() {
            return this._fillColor;
          },
          set: function set(value) {
            if (!this.impl) {
              return;
            }
            this._fillColor.set(value);
            this.impl.fillColor = this._fillColor;
          }
        }, {
          key: "miterLimit",
          get: function get() {
            return this._miterLimit;
          },
          set: function set(value) {
            this._miterLimit = value;
          }
        }, {
          key: "color",
          get: function get() {
            return this._color;
          },
          set: function set(value) {
            if (this._color === value) {
              return;
            }
            this._color.set(value);
          }
        }, {
          key: "graphicsNativeProxy",
          get: function get() {
            return this._graphicsNativeProxy;
          }
        }]);
        return Graphics;
      }(UIRenderer), _class3$x.LineJoin = LineJoin, _class3$x.LineCap = LineCap, _class3$x), (_applyDecoratedDescriptor(_class2$20.prototype, "lineJoin", [_dec3$1g], Object.getOwnPropertyDescriptor(_class2$20.prototype, "lineJoin"), _class2$20.prototype), _applyDecoratedDescriptor(_class2$20.prototype, "lineCap", [_dec4$V], Object.getOwnPropertyDescriptor(_class2$20.prototype, "lineCap"), _class2$20.prototype), _applyDecoratedDescriptor(_class2$20.prototype, "color", [override], Object.getOwnPropertyDescriptor(_class2$20.prototype, "color"), _class2$20.prototype), _initializer$1S = applyDecoratedInitializer(_class2$20.prototype, "_lineWidth", [serializable$j], function () {
        return 1;
      }), _initializer2$1v = applyDecoratedInitializer(_class2$20.prototype, "_strokeColor", [serializable$j], function () {
        return Color$1.BLACK.clone();
      }), _initializer3$$ = applyDecoratedInitializer(_class2$20.prototype, "_lineJoin", [serializable$j], function () {
        return LineJoin.MITER;
      }), _initializer4$N = applyDecoratedInitializer(_class2$20.prototype, "_lineCap", [serializable$j], function () {
        return LineCap.BUTT;
      }), _initializer5$A = applyDecoratedInitializer(_class2$20.prototype, "_fillColor", [serializable$j], function () {
        return Color$1.WHITE.clone();
      }), _initializer6$s = applyDecoratedInitializer(_class2$20.prototype, "_miterLimit", [serializable$j], function () {
        return 10;
      })), _class2$20)) || _class$2f) || _class$2f));
      legacyCC.Graphics = Graphics;

      var _dec$2f, _dec2$1L, _dec3$1f, _dec4$U, _dec5$L, _dec6$v, _dec7$o, _class$2e, _class2$1$, _initializer$1R, _initializer2$1u, _initializer3$_, _initializer4$M, _initializer5$z, _initializer6$r, _initializer7$m, _initializer8$l, _initializer9$j, _initializer10$h, _class3$w;
      var SpriteType$1;
      (function (SpriteType) {
        SpriteType[SpriteType["SIMPLE"] = 0] = "SIMPLE";
        SpriteType[SpriteType["SLICED"] = 1] = "SLICED";
        SpriteType[SpriteType["TILED"] = 2] = "TILED";
        SpriteType[SpriteType["FILLED"] = 3] = "FILLED";
      })(SpriteType$1 || (SpriteType$1 = {}));
      ccenum(SpriteType$1);
      var FillType$2;
      (function (FillType) {
        FillType[FillType["HORIZONTAL"] = 0] = "HORIZONTAL";
        FillType[FillType["VERTICAL"] = 1] = "VERTICAL";
        FillType[FillType["RADIAL"] = 2] = "RADIAL";
      })(FillType$2 || (FillType$2 = {}));
      ccenum(FillType$2);
      var SizeMode$1;
      (function (SizeMode) {
        SizeMode[SizeMode["CUSTOM"] = 0] = "CUSTOM";
        SizeMode[SizeMode["TRIMMED"] = 1] = "TRIMMED";
        SizeMode[SizeMode["RAW"] = 2] = "RAW";
      })(SizeMode$1 || (SizeMode$1 = {}));
      ccenum(SizeMode$1);
      var EventType$6;
      (function (EventType) {
        EventType["SPRITE_FRAME_CHANGED"] = "spriteframe-changed";
      })(EventType$6 || (EventType$6 = {}));
      var Sprite = exports('j', (_dec$2f = ccclass$n('cc.Sprite'), _dec2$1L = executionOrder$1(110), _dec3$1f = type$7(SpriteAtlas), _dec4$U = type$7(SpriteFrame), _dec5$L = type$7(SpriteType$1), _dec6$v = type$7(FillType$2), _dec7$o = type$7(SizeMode$1), _dec$2f(_class$2e = _dec2$1L(_class$2e = (_class2$1$ = (_class3$w = function (_UIRenderer) {
        _inheritsLoose(Sprite, _UIRenderer);
        function Sprite() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _UIRenderer.call.apply(_UIRenderer, [this].concat(args)) || this;
          _this._spriteFrame = _initializer$1R && _initializer$1R();
          _this._type = _initializer2$1u && _initializer2$1u();
          _this._fillType = _initializer3$_ && _initializer3$_();
          _this._sizeMode = _initializer4$M && _initializer4$M();
          _this._fillCenter = _initializer5$z && _initializer5$z();
          _this._fillStart = _initializer6$r && _initializer6$r();
          _this._fillRange = _initializer7$m && _initializer7$m();
          _this._isTrimmedMode = _initializer8$l && _initializer8$l();
          _this._useGrayscale = _initializer9$j && _initializer9$j();
          _this._atlas = _initializer10$h && _initializer10$h();
          return _this;
        }
        var _proto = Sprite.prototype;
        _proto.__preload = function __preload() {
          this.changeMaterialForDefine();
          _UIRenderer.prototype.__preload.call(this);
        };
        _proto.onEnable = function onEnable() {
          _UIRenderer.prototype.onEnable.call(this);
          this._activateMaterial();
          var spriteFrame = this._spriteFrame;
          if (spriteFrame) {
            this._updateUVs();
            if (this._type === SpriteType$1.SLICED) {
              spriteFrame.on(SpriteFrame.EVENT_UV_UPDATED, this._updateUVs, this);
            }
          }
        };
        _proto.onDisable = function onDisable() {
          _UIRenderer.prototype.onDisable.call(this);
          if (this._spriteFrame && this._type === SpriteType$1.SLICED) {
            this._spriteFrame.off(SpriteFrame.EVENT_UV_UPDATED, this._updateUVs, this);
          }
        };
        _proto.onDestroy = function onDestroy() {
          _UIRenderer.prototype.onDestroy.call(this);
        };
        _proto.changeSpriteFrameFromAtlas = function changeSpriteFrameFromAtlas(name) {
          if (!this._atlas) {
            console.warn('SpriteAtlas is null.');
            return;
          }
          var sprite = this._atlas.getSpriteFrame(name);
          this.spriteFrame = sprite;
        };
        _proto.changeMaterialForDefine = function changeMaterialForDefine() {
          var texture;
          var lastInstanceMaterialType = this._instanceMaterialType;
          if (this._spriteFrame) {
            texture = this._spriteFrame.texture;
          }
          var value = false;
          if (texture instanceof TextureBase) {
            var format = texture.getPixelFormat();
            value = format === PixelFormat.RGBA_ETC1 || format === PixelFormat.RGB_A_PVRTC_4BPPV1 || format === PixelFormat.RGB_A_PVRTC_2BPPV1;
          }
          if (value && this.grayscale) {
            this._instanceMaterialType = InstanceMaterialType.USE_ALPHA_SEPARATED_AND_GRAY;
          } else if (value) {
            this._instanceMaterialType = InstanceMaterialType.USE_ALPHA_SEPARATED;
          } else if (this.grayscale) {
            this._instanceMaterialType = InstanceMaterialType.GRAYSCALE;
          } else {
            this._instanceMaterialType = InstanceMaterialType.ADD_COLOR_AND_TEXTURE;
          }
          if (lastInstanceMaterialType !== this._instanceMaterialType) {
            this.updateMaterial();
          }
        };
        _proto._updateBuiltinMaterial = function _updateBuiltinMaterial() {
          var mat = _UIRenderer.prototype._updateBuiltinMaterial.call(this);
          if (this.spriteFrame && this.spriteFrame.texture instanceof RenderTexture) {
            var defines = _extends({
              SAMPLE_FROM_RT: true
            }, mat.passes[0].defines);
            var renderMat = new Material();
            renderMat.initialize({
              effectAsset: mat.effectAsset,
              defines: defines
            });
            mat = renderMat;
          }
          return mat;
        };
        _proto._render = function _render(render) {
          render.commitComp(this, this.renderData, this._spriteFrame, this._assembler, null);
        };
        _proto._canRender = function _canRender() {
          if (!_UIRenderer.prototype._canRender.call(this)) {
            return false;
          }
          var spriteFrame = this._spriteFrame;
          if (!spriteFrame || !spriteFrame.texture) {
            return false;
          }
          return true;
        };
        _proto._flushAssembler = function _flushAssembler() {
          var assembler = Sprite.Assembler.getAssembler(this);
          if (this._assembler !== assembler) {
            this.destroyRenderData();
            this._assembler = assembler;
          }
          if (!this._renderData) {
            if (this._assembler && this._assembler.createData) {
              this._renderData = this._assembler.createData(this);
              this._renderData.material = this.getRenderMaterial(0);
              this.markForUpdateRenderData();
              if (this.spriteFrame) {
                this._assembler.updateUVs(this);
              }
              this._updateColor();
            }
          }
          if (this._spriteFrame) {
            if (this._type === SpriteType$1.SLICED) {
              this._spriteFrame.on(SpriteFrame.EVENT_UV_UPDATED, this._updateUVs, this);
            } else {
              this._spriteFrame.off(SpriteFrame.EVENT_UV_UPDATED, this._updateUVs, this);
            }
          }
        };
        _proto._applySpriteSize = function _applySpriteSize() {
          if (this._spriteFrame) {
            {
              if (SizeMode$1.RAW === this._sizeMode) {
                var size = this._spriteFrame.originalSize;
                this.node._uiProps.uiTransformComp.setContentSize(size);
              } else if (SizeMode$1.TRIMMED === this._sizeMode) {
                var rect = this._spriteFrame.rect;
                this.node._uiProps.uiTransformComp.setContentSize(rect.width, rect.height);
              }
            }
          }
        };
        _proto._resized = function _resized() {
          {
            return;
          }
        };
        _proto._activateMaterial = function _activateMaterial() {
          var spriteFrame = this._spriteFrame;
          var material = this.getRenderMaterial(0);
          if (spriteFrame) {
            if (material) {
              this.markForUpdateRenderData();
            }
          }
          if (this.renderData) {
            this.renderData.material = material;
          }
        };
        _proto._updateUVs = function _updateUVs() {
          if (this._assembler) {
            this._assembler.updateUVs(this);
          }
        };
        _proto._applySpriteFrame = function _applySpriteFrame(oldFrame) {
          var spriteFrame = this._spriteFrame;
          if (oldFrame && this._type === SpriteType$1.SLICED) {
            oldFrame.off(SpriteFrame.EVENT_UV_UPDATED, this._updateUVs, this);
          }
          var textureChanged = false;
          if (spriteFrame) {
            if (!oldFrame || oldFrame.texture !== spriteFrame.texture) {
              textureChanged = true;
            }
            if (textureChanged) {
              if (this.renderData) this.renderData.textureDirty = true;
              this.changeMaterialForDefine();
            }
            this._applySpriteSize();
            if (this._type === SpriteType$1.SLICED) {
              spriteFrame.on(SpriteFrame.EVENT_UV_UPDATED, this._updateUVs, this);
            }
          }
        };
        _createClass(Sprite, [{
          key: "spriteAtlas",
          get: function get() {
            return this._atlas;
          },
          set: function set(value) {
            if (this._atlas === value) {
              return;
            }
            this._atlas = value;
          }
        }, {
          key: "spriteFrame",
          get: function get() {
            return this._spriteFrame;
          },
          set: function set(value) {
            if (this._spriteFrame === value) {
              return;
            }
            var lastSprite = this._spriteFrame;
            this._spriteFrame = value;
            this.markForUpdateRenderData();
            this._applySpriteFrame(lastSprite);
          }
        }, {
          key: "type",
          get: function get() {
            return this._type;
          },
          set: function set(value) {
            if (this._type !== value) {
              this._type = value;
              this._flushAssembler();
            }
          }
        }, {
          key: "fillType",
          get: function get() {
            return this._fillType;
          },
          set: function set(value) {
            if (this._fillType !== value) {
              if (value === FillType$2.RADIAL || this._fillType === FillType$2.RADIAL) {
                this.destroyRenderData();
              } else if (this.renderData) {
                this.markForUpdateRenderData(true);
              }
            }
            this._fillType = value;
            this._flushAssembler();
          }
        }, {
          key: "fillCenter",
          get: function get() {
            return this._fillCenter;
          },
          set: function set(value) {
            this._fillCenter.x = value.x;
            this._fillCenter.y = value.y;
            if (this._type === SpriteType$1.FILLED && this.renderData) {
              this.markForUpdateRenderData();
            }
          }
        }, {
          key: "fillStart",
          get: function get() {
            return this._fillStart;
          },
          set: function set(value) {
            this._fillStart = clamp$1(value, 0, 1);
            if (this._type === SpriteType$1.FILLED && this.renderData) {
              this.markForUpdateRenderData();
              this._updateUVs();
            }
          }
        }, {
          key: "fillRange",
          get: function get() {
            return this._fillRange;
          },
          set: function set(value) {
            this._fillRange = clamp$1(value, -1, 1);
            if (this._type === SpriteType$1.FILLED && this.renderData) {
              this.markForUpdateRenderData();
              this._updateUVs();
            }
          }
        }, {
          key: "trim",
          get: function get() {
            return this._isTrimmedMode;
          },
          set: function set(value) {
            if (this._isTrimmedMode === value) {
              return;
            }
            this._isTrimmedMode = value;
            if (this._type === SpriteType$1.SIMPLE && this.renderData) {
              this.markForUpdateRenderData(true);
            }
          }
        }, {
          key: "grayscale",
          get: function get() {
            return this._useGrayscale;
          },
          set: function set(value) {
            if (this._useGrayscale === value) {
              return;
            }
            this._useGrayscale = value;
            this.changeMaterialForDefine();
            this.updateMaterial();
          }
        }, {
          key: "sizeMode",
          get: function get() {
            return this._sizeMode;
          },
          set: function set(value) {
            if (this._sizeMode === value) {
              return;
            }
            this._sizeMode = value;
            if (value !== SizeMode$1.CUSTOM) {
              this._applySpriteSize();
            }
          }
        }]);
        return Sprite;
      }(UIRenderer), _class3$w.FillType = FillType$2, _class3$w.Type = SpriteType$1, _class3$w.SizeMode = SizeMode$1, _class3$w.EventType = EventType$6, _class3$w), (_applyDecoratedDescriptor(_class2$1$.prototype, "spriteAtlas", [_dec3$1f], Object.getOwnPropertyDescriptor(_class2$1$.prototype, "spriteAtlas"), _class2$1$.prototype), _applyDecoratedDescriptor(_class2$1$.prototype, "spriteFrame", [_dec4$U], Object.getOwnPropertyDescriptor(_class2$1$.prototype, "spriteFrame"), _class2$1$.prototype), _applyDecoratedDescriptor(_class2$1$.prototype, "type", [_dec5$L], Object.getOwnPropertyDescriptor(_class2$1$.prototype, "type"), _class2$1$.prototype), _applyDecoratedDescriptor(_class2$1$.prototype, "fillType", [_dec6$v], Object.getOwnPropertyDescriptor(_class2$1$.prototype, "fillType"), _class2$1$.prototype), _applyDecoratedDescriptor(_class2$1$.prototype, "sizeMode", [_dec7$o], Object.getOwnPropertyDescriptor(_class2$1$.prototype, "sizeMode"), _class2$1$.prototype), _initializer$1R = applyDecoratedInitializer(_class2$1$.prototype, "_spriteFrame", [serializable$j], function () {
        return null;
      }), _initializer2$1u = applyDecoratedInitializer(_class2$1$.prototype, "_type", [serializable$j], function () {
        return SpriteType$1.SIMPLE;
      }), _initializer3$_ = applyDecoratedInitializer(_class2$1$.prototype, "_fillType", [serializable$j], function () {
        return FillType$2.HORIZONTAL;
      }), _initializer4$M = applyDecoratedInitializer(_class2$1$.prototype, "_sizeMode", [serializable$j], function () {
        return SizeMode$1.TRIMMED;
      }), _initializer5$z = applyDecoratedInitializer(_class2$1$.prototype, "_fillCenter", [serializable$j], function () {
        return new Vec2(0, 0);
      }), _initializer6$r = applyDecoratedInitializer(_class2$1$.prototype, "_fillStart", [serializable$j], function () {
        return 0;
      }), _initializer7$m = applyDecoratedInitializer(_class2$1$.prototype, "_fillRange", [serializable$j], function () {
        return 0;
      }), _initializer8$l = applyDecoratedInitializer(_class2$1$.prototype, "_isTrimmedMode", [serializable$j], function () {
        return true;
      }), _initializer9$j = applyDecoratedInitializer(_class2$1$.prototype, "_useGrayscale", [serializable$j], function () {
        return false;
      }), _initializer10$h = applyDecoratedInitializer(_class2$1$.prototype, "_atlas", [serializable$j], function () {
        return null;
      })), _class2$1$)) || _class$2e) || _class$2e));
      legacyCC.Sprite = Sprite;

      var _dec$2e, _dec2$1K, _dec3$1e, _class$2d, _class2$1_, _initializer$1Q, _initializer2$1t, _initializer3$Z, _initializer4$L, _class3$v;
      var _worldMatrix = new Mat4();
      var _vec2_temp = new Vec2();
      var _mat4_temp = new Mat4();
      var _circlePoints = [];
      function _calculateCircle(center, radius, segments) {
        _circlePoints.length = 0;
        var anglePerStep = Math.PI * 2 / segments;
        for (var step = 0; step < segments; ++step) {
          _circlePoints.push(new Vec3(radius.x * Math.cos(anglePerStep * step) + center.x, radius.y * Math.sin(anglePerStep * step) + center.y, 0));
        }
        return _circlePoints;
      }
      var MaskType;
      (function (MaskType) {
        MaskType[MaskType["GRAPHICS_RECT"] = 0] = "GRAPHICS_RECT";
        MaskType[MaskType["GRAPHICS_ELLIPSE"] = 1] = "GRAPHICS_ELLIPSE";
        MaskType[MaskType["GRAPHICS_STENCIL"] = 2] = "GRAPHICS_STENCIL";
        MaskType[MaskType["SPRITE_STENCIL"] = 3] = "SPRITE_STENCIL";
      })(MaskType || (MaskType = {}));
      ccenum(MaskType);
      var SEGMENTS_MIN = 3;
      var SEGMENTS_MAX = 10000;
      var Mask = exports('h', (_dec$2e = ccclass$n('cc.Mask'), _dec2$1K = executionOrder$1(110), _dec3$1e = type$7(MaskType), _dec$2e(_class$2d = _dec2$1K(_class$2d = (_class2$1_ = (_class3$v = function (_Component) {
        _inheritsLoose(Mask, _Component);
        function Mask() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Component.call.apply(_Component, [this].concat(args)) || this;
          _this._type = _initializer$1Q && _initializer$1Q();
          _this._inverted = _initializer2$1t && _initializer2$1t();
          _this._segments = _initializer3$Z && _initializer3$Z();
          _this._alphaThreshold = _initializer4$L && _initializer4$L();
          _this._sprite = null;
          _this._graphics = null;
          _this._stencilStage = Stage.DISABLED;
          return _this;
        }
        var _proto = Mask.prototype;
        _proto.onLoad = function onLoad() {
          this._changeRenderType();
        };
        _proto.onEnable = function onEnable() {
          this._changeRenderType();
          this._updateGraphics();
          this._enableRender();
          this.node.on(NodeEventType.ANCHOR_CHANGED, this._nodeStateChange, this);
          this.node.on(NodeEventType.SIZE_CHANGED, this._nodeStateChange, this);
        };
        _proto.onRestore = function onRestore() {
          this._changeRenderType();
          this._updateGraphics();
        };
        _proto.onDisable = function onDisable() {
          this._disableRender();
          this.node.off(NodeEventType.ANCHOR_CHANGED, this._nodeStateChange, this);
          this.node.off(NodeEventType.SIZE_CHANGED, this._nodeStateChange, this);
        };
        _proto.onDestroy = function onDestroy() {
          this._removeMaskNode();
        };
        _proto.isHit = function isHit(worldPt) {
          var uiTrans = this.node._uiProps.uiTransformComp;
          var size = uiTrans.contentSize;
          var w = size.width;
          var h = size.height;
          var testPt = _vec2_temp;
          this.node.getWorldMatrix(_worldMatrix);
          Mat4.invert(_mat4_temp, _worldMatrix);
          Vec2.transformMat4(testPt, worldPt, _mat4_temp);
          var ap = uiTrans.anchorPoint;
          testPt.x += ap.x * w;
          testPt.y += ap.y * h;
          var result = false;
          if (this.type === MaskType.GRAPHICS_RECT || this.type === MaskType.GRAPHICS_STENCIL || this.type === MaskType.SPRITE_STENCIL) {
            result = testPt.x >= 0 && testPt.y >= 0 && testPt.x <= w && testPt.y <= h;
          } else if (this.type === MaskType.GRAPHICS_ELLIPSE) {
            var rx = w / 2;
            var ry = h / 2;
            var px = testPt.x - 0.5 * w;
            var py = testPt.y - 0.5 * h;
            result = px * px / (rx * rx) + py * py / (ry * ry) < 1;
          }
          if (this._inverted) {
            result = !result;
          }
          return result;
        };
        _proto._nodeStateChange = function _nodeStateChange(type) {
          this._updateGraphics();
        };
        _proto._changeRenderType = function _changeRenderType() {
          var isGraphics = this._type !== MaskType.SPRITE_STENCIL;
          if (isGraphics) {
            this._createGraphics();
          } else {
            this._createSprite();
          }
        };
        _proto._createSprite = function _createSprite() {
          if (!this._sprite) {
            var sprite = this._sprite = this.node.getComponent(Sprite);
            if (!sprite) {
              var node = this.node;
              sprite = this._sprite = node.addComponent(Sprite);
            }
          }
          this._sprite.stencilStage = this.inverted ? Stage.ENTER_LEVEL_INVERTED : Stage.ENTER_LEVEL;
          this._sprite.updateMaterial();
        };
        _proto._createGraphics = function _createGraphics() {
          if (!this._graphics) {
            var graphics = this._graphics = this.node.getComponent(Graphics);
            if (!graphics) {
              var node = this.node;
              graphics = this._graphics = node.addComponent(Graphics);
            }
            graphics.lineWidth = 1;
            var color = Color$1.WHITE.clone();
            color.a = 0;
            graphics.fillColor = color;
          }
          this._graphics.stencilStage = this.inverted ? Stage.ENTER_LEVEL_INVERTED : Stage.ENTER_LEVEL;
        };
        _proto._updateGraphics = function _updateGraphics() {
          if (!this._graphics || this._type !== MaskType.GRAPHICS_RECT && this._type !== MaskType.GRAPHICS_ELLIPSE) {
            return;
          }
          var uiTrans = this.node._uiProps.uiTransformComp;
          var graphics = this._graphics;
          graphics.clear();
          var size = uiTrans.contentSize;
          var width = size.width;
          var height = size.height;
          var ap = uiTrans.anchorPoint;
          var x = -width * ap.x;
          var y = -height * ap.y;
          if (this._type === MaskType.GRAPHICS_RECT) {
            graphics.rect(x, y, width, height);
          } else if (this._type === MaskType.GRAPHICS_ELLIPSE) {
            var center = new Vec3(x + width / 2, y + height / 2, 0);
            var radius = new Vec3(width / 2, height / 2, 0);
            var points = _calculateCircle(center, radius, this._segments);
            for (var i = 0; i < points.length; ++i) {
              var point = points[i];
              if (i === 0) {
                graphics.moveTo(point.x, point.y);
              } else {
                graphics.lineTo(point.x, point.y);
              }
            }
            graphics.close();
          }
          graphics.fill();
        };
        _proto._enableRender = function _enableRender() {
          if (this.subComp) {
            this.subComp.enabled = true;
          }
        };
        _proto._disableRender = function _disableRender() {
          if (this.subComp) {
            this.subComp.stencilStage = Stage.DISABLED;
            this.subComp.updateMaterial();
            if (this.node.activeInHierarchy) {
              this.subComp.enabled = false;
            }
          }
        };
        _proto._removeMaskNode = function _removeMaskNode() {
          if (this._sprite) {
            this._sprite = null;
          }
          if (this._graphics) {
            this._graphics = null;
          }
        };
        _proto.markForUpdateRenderData = function markForUpdateRenderData(enable) {
          if (enable === void 0) {
            enable = true;
          }
          warnID(9007);
          if (this.subComp) {
            this.subComp.markForUpdateRenderData(enable);
          }
        };
        _proto.requestRenderData = function requestRenderData(any) {
          warnID(9007);
        };
        _proto.destroyRenderData = function destroyRenderData() {
          warnID(9007);
        };
        _proto.updateRenderer = function updateRenderer() {
          warnID(9007);
          if (this.subComp) {
            this.subComp.updateRenderer();
          }
        };
        _proto.fillBuffers = function fillBuffers(render) {
          warnID(9007);
        };
        _proto.postUpdateAssembler = function postUpdateAssembler(render) {
          warnID(9007);
        };
        _proto.setNodeDirty = function setNodeDirty() {
          warnID(9007);
          if (this.subComp) {
            this.subComp.setNodeDirty();
          }
        };
        _proto.setTextureDirty = function setTextureDirty() {
          warnID(9007);
          if (this.subComp) {
            this.subComp.setTextureDirty();
          }
        };
        _proto.getMaterial = function getMaterial(idx) {
          warnID(9007);
          if (this.subComp) {
            return this.subComp.getSharedMaterial(idx);
          }
          return null;
        };
        _proto.setMaterial = function setMaterial(material, index) {
          warnID(9007);
          if (this.subComp) {
            this.subComp.setMaterial(material, index);
          }
        };
        _proto.getMaterialInstance = function getMaterialInstance(idx) {
          warnID(9007);
          if (this.subComp) {
            return this.subComp.getMaterialInstance(idx);
          }
          return null;
        };
        _proto.setMaterialInstance = function setMaterialInstance(matInst, index) {
          warnID(9007);
          if (this.subComp) {
            this.subComp.setMaterialInstance(matInst, index);
          }
        };
        _proto.getRenderMaterial = function getRenderMaterial(index) {
          warnID(9007);
          if (this.subComp) {
            return this.subComp.getRenderMaterial(index);
          }
          return null;
        };
        _createClass(Mask, [{
          key: "type",
          get: function get() {
            return this._type;
          },
          set: function set(value) {
            if (this._type === value) {
              return;
            }
            this._type = value;
            if (this._type !== MaskType.SPRITE_STENCIL) {
              if (this._sprite) {
                this.node.removeComponent(Sprite);
                this._sprite._destroyImmediate();
                this._sprite = null;
              }
              this._changeRenderType();
              this._updateGraphics();
            } else {
              if (this._graphics) {
                this._graphics.clear();
                this.node.removeComponent(Graphics);
                this._graphics._destroyImmediate();
                this._graphics = null;
              }
              this._changeRenderType();
            }
          }
        }, {
          key: "inverted",
          get: function get() {
            return this._inverted;
          },
          set: function set(value) {
            this._inverted = value;
            this.subComp.stencilStage = this.inverted ? Stage.ENTER_LEVEL_INVERTED : Stage.ENTER_LEVEL;
          }
        }, {
          key: "segments",
          get: function get() {
            return this._segments;
          },
          set: function set(value) {
            if (this._segments === value) {
              return;
            }
            this._segments = clamp$1(value, SEGMENTS_MIN, SEGMENTS_MAX);
            this._updateGraphics();
          }
        }, {
          key: "spriteFrame",
          get: function get() {
            if (this._sprite) {
              return this._sprite.spriteFrame;
            }
            return null;
          },
          set: function set(value) {
            if (this._sprite) {
              this._sprite.spriteFrame = value;
            } else {
              error('please change type to sprite_stencil first');
            }
          }
        }, {
          key: "alphaThreshold",
          get: function get() {
            return this._alphaThreshold;
          },
          set: function set(value) {
            if (this._alphaThreshold === value) {
              return;
            }
            this._alphaThreshold = value;
            if (this.type === MaskType.SPRITE_STENCIL && this._sprite) {
              var mat = this._sprite.getMaterialInstance(0);
              mat.setProperty('alphaThreshold', this._alphaThreshold);
            }
          }
        }, {
          key: "subComp",
          get: function get() {
            return this._graphics || this._sprite;
          }
        }, {
          key: "customMaterial",
          get: function get() {
            warnID(9007);
            if (this.subComp) {
              return this.subComp.customMaterial;
            }
            return null;
          },
          set: function set(val) {
            warnID(9007);
            if (this.subComp) {
              this.subComp.customMaterial = val;
            }
          }
        }, {
          key: "color",
          get: function get() {
            warnID(9007);
            if (this.subComp) {
              return this.subComp.color;
            }
            return null;
          },
          set: function set(value) {
            warnID(9007);
            if (this.subComp && value) {
              this.subComp.color = value;
            }
          }
        }, {
          key: "sharedMaterial",
          get: function get() {
            warnID(9007);
            if (this.subComp) {
              return this.subComp.sharedMaterial;
            }
            return null;
          }
        }, {
          key: "sharedMaterials",
          get: function get() {
            warnID(9007);
            if (this.subComp) {
              return this.subComp.sharedMaterials;
            }
            return null;
          },
          set: function set(val) {
            warnID(9007);
            if (this.subComp && val) {
              this.subComp.sharedMaterials = val;
            }
          }
        }, {
          key: "material",
          get: function get() {
            warnID(9007);
            if (this.subComp) {
              return this.subComp.material;
            }
            return null;
          },
          set: function set(val) {
            warnID(9007);
            if (this.subComp) {
              this.subComp.material = val;
            }
          }
        }, {
          key: "materials",
          get: function get() {
            warnID(9007);
            if (this.subComp) {
              return this.subComp.materials;
            }
            return [null];
          },
          set: function set(val) {
            warnID(9007);
            if (this.subComp) {
              this.subComp.materials = val;
            }
          }
        }]);
        return Mask;
      }(Component), _class3$v.Type = MaskType, _class3$v), (_applyDecoratedDescriptor(_class2$1_.prototype, "type", [_dec3$1e], Object.getOwnPropertyDescriptor(_class2$1_.prototype, "type"), _class2$1_.prototype), _initializer$1Q = applyDecoratedInitializer(_class2$1_.prototype, "_type", [serializable$j], function () {
        return MaskType.GRAPHICS_RECT;
      }), _initializer2$1t = applyDecoratedInitializer(_class2$1_.prototype, "_inverted", [serializable$j], function () {
        return false;
      }), _initializer3$Z = applyDecoratedInitializer(_class2$1_.prototype, "_segments", [serializable$j], function () {
        return 64;
      }), _initializer4$L = applyDecoratedInitializer(_class2$1_.prototype, "_alphaThreshold", [serializable$j], function () {
        return 0.1;
      })), _class2$1_)) || _class$2d) || _class$2d));
      NodeEventProcessor._maskComp = Mask;
      legacyCC.Mask = Mask;

      var eventRegx = /^(click)(\s)*=|(param)(\s)*=/;
      var imageAttrReg = /(\s)*src(\s)*=|(\s)*height(\s)*=|(\s)*width(\s)*=|(\s)*align(\s)*=|(\s)*offset(\s)*=|(\s)*click(\s)*=|(\s)*param(\s)*=/;
      var HtmlTextParser = exports('w', function () {
        function HtmlTextParser() {
          this._specialSymbolArray = [];
          this._stack = [];
          this._resultObjectArray = [];
          this._specialSymbolArray.push([/&lt;/g, '<']);
          this._specialSymbolArray.push([/&gt;/g, '>']);
          this._specialSymbolArray.push([/&amp;/g, '&']);
          this._specialSymbolArray.push([/&quot;/g, '"']);
          this._specialSymbolArray.push([/&apos;/g, '\'']);
        }
        var _proto = HtmlTextParser.prototype;
        _proto.parse = function parse(htmlString) {
          this._resultObjectArray.length = 0;
          this._stack.length = 0;
          var startIndex = 0;
          var length = htmlString.length;
          while (startIndex < length) {
            var tagEndIndex = htmlString.indexOf('>', startIndex);
            var tagBeginIndex = -1;
            if (tagEndIndex >= 0) {
              tagBeginIndex = htmlString.lastIndexOf('<', tagEndIndex);
              var noTagBegin = tagBeginIndex < startIndex - 1;
              if (noTagBegin) {
                tagBeginIndex = htmlString.indexOf('<', tagEndIndex + 1);
                tagEndIndex = htmlString.indexOf('>', tagBeginIndex + 1);
              }
            }
            if (tagBeginIndex < 0) {
              this._stack.pop();
              this._processResult(htmlString.substring(startIndex));
              startIndex = length;
            } else {
              var newStr = htmlString.substring(startIndex, tagBeginIndex);
              var tagStr = htmlString.substring(tagBeginIndex + 1, tagEndIndex);
              if (tagStr === '') newStr = htmlString.substring(startIndex, tagEndIndex + 1);
              this._processResult(newStr);
              if (tagEndIndex === -1) {
                tagEndIndex = tagBeginIndex;
              } else if (htmlString.charAt(tagBeginIndex + 1) === '/') {
                this._stack.pop();
              } else {
                this._addToStack(tagStr);
              }
              startIndex = tagEndIndex + 1;
            }
          }
          return this._resultObjectArray;
        };
        _proto._attributeToObject = function _attributeToObject(attribute) {
          attribute = attribute.trim();
          var obj = {};
          var header = /^(color|size)(\s)*=/.exec(attribute);
          var tagName = '';
          var nextSpace = 0;
          var eventHanlderString = '';
          if (header) {
            tagName = header[0];
            attribute = attribute.substring(tagName.length).trim();
            if (attribute === '') {
              return obj;
            }
            nextSpace = attribute.indexOf(' ');
            switch (tagName[0]) {
              case 'c':
                if (nextSpace > -1) {
                  obj.color = attribute.substring(0, nextSpace).trim();
                } else {
                  obj.color = attribute;
                }
                break;
              case 's':
                obj.size = parseInt(attribute);
                break;
            }
            if (nextSpace > -1) {
              eventHanlderString = attribute.substring(nextSpace + 1).trim();
              obj.event = this._processEventHandler(eventHanlderString);
            }
            return obj;
          }
          header = /^(br(\s)*\/)/.exec(attribute);
          if (header && header[0].length > 0) {
            tagName = header[0].trim();
            if (tagName.startsWith('br') && tagName[tagName.length - 1] === '/') {
              obj.isNewLine = true;
              this._resultObjectArray.push({
                text: '',
                style: {
                  isNewLine: true
                }
              });
              return obj;
            }
          }
          header = /^(img(\s)*src(\s)*=[^>]+\/)/.exec(attribute);
          var remainingArgument = '';
          var rightQuot = -1;
          if (header && header[0].length > 0) {
            tagName = header[0].trim();
            if (tagName.startsWith('img') && tagName[tagName.length - 1] === '/') {
              header = imageAttrReg.exec(attribute);
              var tagValue;
              var isValidImageTag = false;
              while (header) {
                attribute = attribute.substring(attribute.indexOf(header[0]));
                tagName = attribute.substr(0, header[0].length);
                var originTagNameLength = tagName.length;
                tagName = tagName.replace(/[^a-zA-Z]/g, '').trim();
                tagName = tagName.toLowerCase();
                remainingArgument = attribute.substring(originTagNameLength).trim();
                if (tagName === 'src') {
                  rightQuot = this.getRightQuotationIndex(remainingArgument);
                } else {
                  rightQuot = -1;
                }
                nextSpace = remainingArgument.indexOf(' ', rightQuot + 1 >= remainingArgument.length ? -1 : rightQuot + 1);
                tagValue = nextSpace > -1 ? remainingArgument.substr(0, nextSpace) : remainingArgument;
                attribute = remainingArgument.substring(nextSpace).trim();
                if (tagValue.endsWith('/')) {
                  tagValue = tagValue.slice(0, -1);
                }
                if (tagName === 'src') {
                  switch (tagValue.charCodeAt(0)) {
                    case 34:
                    case 39:
                      isValidImageTag = true;
                      tagValue = tagValue.slice(1, -1);
                      break;
                  }
                  obj.isImage = true;
                  obj.src = tagValue;
                } else if (tagName === 'height') {
                  obj.imageHeight = parseInt(tagValue);
                } else if (tagName === 'width') {
                  obj.imageWidth = parseInt(tagValue);
                } else if (tagName === 'align') {
                  switch (tagValue.charCodeAt(0)) {
                    case 34:
                    case 39:
                      tagValue = tagValue.slice(1, -1);
                      break;
                  }
                  obj.imageAlign = tagValue.toLowerCase();
                } else if (tagName === 'offset') {
                  obj.imageOffset = tagValue;
                } else if (tagName === 'click') {
                  obj.event = this._processEventHandler(tagName + "=" + tagValue);
                }
                if (obj.event && tagName === 'param') {
                  obj.event[tagName] = tagValue.replace(/^"|"$/g, '');
                }
                header = imageAttrReg.exec(attribute);
              }
              if (isValidImageTag && obj.isImage) {
                this._resultObjectArray.push({
                  text: '',
                  style: obj
                });
              }
              return {};
            }
          }
          header = /^(outline(\s)*[^>]*)/.exec(attribute);
          if (header) {
            attribute = header[0].substring('outline'.length).trim();
            var defaultOutlineObject = {
              color: '#ffffff',
              width: 1
            };
            if (attribute) {
              var outlineAttrReg = /(\s)*color(\s)*=|(\s)*width(\s)*=|(\s)*click(\s)*=|(\s)*param(\s)*=/;
              header = outlineAttrReg.exec(attribute);
              var _tagValue;
              while (header) {
                attribute = attribute.substring(attribute.indexOf(header[0]));
                tagName = attribute.substr(0, header[0].length);
                remainingArgument = attribute.substring(tagName.length).trim();
                nextSpace = remainingArgument.indexOf(' ');
                if (nextSpace > -1) {
                  _tagValue = remainingArgument.substr(0, nextSpace);
                } else {
                  _tagValue = remainingArgument;
                }
                tagName = tagName.replace(/[^a-zA-Z]/g, '').trim();
                tagName = tagName.toLowerCase();
                attribute = remainingArgument.substring(nextSpace).trim();
                if (tagName === 'click') {
                  obj.event = this._processEventHandler(tagName + "=" + _tagValue);
                } else if (tagName === 'color') {
                  defaultOutlineObject.color = _tagValue;
                } else if (tagName === 'width') {
                  defaultOutlineObject.width = parseInt(_tagValue);
                }
                if (obj.event && tagName === 'param') {
                  obj.event[tagName] = _tagValue.replace(/^"|"$/g, '');
                }
                header = outlineAttrReg.exec(attribute);
              }
            }
            obj.outline = defaultOutlineObject;
          }
          header = /^(on|u|b|i)(\s)*/.exec(attribute);
          if (header && header[0].length > 0) {
            tagName = header[0];
            attribute = attribute.substring(tagName.length).trim();
            switch (tagName[0]) {
              case 'u':
                obj.underline = true;
                break;
              case 'i':
                obj.italic = true;
                break;
              case 'b':
                obj.bold = true;
                break;
            }
            if (attribute === '') {
              return obj;
            }
            obj.event = this._processEventHandler(attribute);
          }
          return obj;
        };
        _proto.getRightQuotationIndex = function getRightQuotationIndex(remainingArgument) {
          var leftQuot = -1;
          var rightQuot = -1;
          var leftSingleQuot = remainingArgument.indexOf('\'');
          var leftDoubleQuot = remainingArgument.indexOf('"');
          var useSingleQuot = leftSingleQuot > -1 && (leftSingleQuot < leftDoubleQuot || leftDoubleQuot === -1);
          var useDoubleQuot = leftDoubleQuot > -1 && (leftDoubleQuot < leftSingleQuot || leftSingleQuot === -1);
          if (useSingleQuot) {
            leftQuot = leftSingleQuot;
            rightQuot = remainingArgument.indexOf('\'', leftQuot + 1 >= remainingArgument.length ? -1 : leftQuot + 1);
          } else if (useDoubleQuot) {
            leftQuot = leftDoubleQuot;
            rightQuot = remainingArgument.indexOf('"', leftQuot + 1 >= remainingArgument.length ? -1 : leftQuot + 1);
          }
          return rightQuot;
        };
        _proto._processEventHandler = function _processEventHandler(eventString) {
          var obj = {};
          var index = 0;
          var isValidTag = false;
          var eventNames = eventRegx.exec(eventString);
          while (eventNames) {
            var eventName = eventNames[0];
            var eventValue = '';
            isValidTag = false;
            eventString = eventString.substring(eventName.length).trim();
            if (eventString.charAt(0) === '"') {
              index = eventString.indexOf('"', 1);
              if (index > -1) {
                eventValue = eventString.substring(1, index).trim();
                isValidTag = true;
              }
              index++;
            } else if (eventString.charAt(0) === '\'') {
              index = eventString.indexOf('\'', 1);
              if (index > -1) {
                eventValue = eventString.substring(1, index).trim();
                isValidTag = true;
              }
              index++;
            } else {
              var match = /(\S)+/.exec(eventString);
              if (match) {
                eventValue = match[0];
              } else {
                eventValue = '';
              }
              index = eventValue.length;
            }
            if (isValidTag) {
              eventName = eventName.substring(0, eventName.length - 1).trim();
              obj[eventName] = eventValue;
            }
            eventString = eventString.substring(index).trim();
            eventNames = eventRegx.exec(eventString);
          }
          return obj;
        };
        _proto._addToStack = function _addToStack(attribute) {
          var obj = this._attributeToObject(attribute);
          if (this._stack.length === 0) {
            this._stack.push(obj);
          } else {
            if (obj.isNewLine || obj.isImage) {
              return;
            }
            var previousTagObj = this._stack[this._stack.length - 1];
            for (var key in previousTagObj) {
              if (!obj[key]) {
                obj[key] = previousTagObj[key];
              }
            }
            this._stack.push(obj);
          }
        };
        _proto._processResult = function _processResult(value) {
          if (value.length === 0) {
            return;
          }
          value = this._escapeSpecialSymbol(value);
          if (this._stack.length > 0) {
            this._resultObjectArray.push({
              text: value,
              style: this._stack[this._stack.length - 1]
            });
          } else {
            this._resultObjectArray.push({
              text: value
            });
          }
        };
        _proto._escapeSpecialSymbol = function _escapeSpecialSymbol(str) {
          for (var _iterator = _createForOfIteratorHelperLoose(this._specialSymbolArray), _step; !(_step = _iterator()).done;) {
            var symbolArr = _step.value;
            var key = symbolArr[0];
            var value = symbolArr[1];
            str = str.replace(key, value);
          }
          return str;
        };
        return HtmlTextParser;
      }());

      var _dec$2d, _dec2$1J, _dec3$1d, _class$2c, _class2$1Z, _initializer$1P, _initializer2$1s;
      var LabelOutline = exports('m', (_dec$2d = ccclass$n('cc.LabelOutline'), _dec2$1J = executionOrder$1(110), _dec3$1d = requireComponent(Label), _dec$2d(_class$2c = _dec2$1J(_class$2c = _dec3$1d(_class$2c = (_class2$1Z = function (_Component) {
        _inheritsLoose(LabelOutline, _Component);
        function LabelOutline() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Component.call.apply(_Component, [this].concat(args)) || this;
          _this._color = _initializer$1P && _initializer$1P();
          _this._width = _initializer2$1s && _initializer2$1s();
          return _this;
        }
        var _proto = LabelOutline.prototype;
        _proto.onEnable = function onEnable() {
          this._updateRenderData();
        };
        _proto.onDisable = function onDisable() {
          this._updateRenderData();
        };
        _proto._updateRenderData = function _updateRenderData() {
          var label = this.node.getComponent(Label);
          if (label) {
            label.updateRenderData(true);
          }
        };
        _createClass(LabelOutline, [{
          key: "color",
          get: function get() {
            return this._color;
          },
          set: function set(value) {
            if (this._color === value) {
              return;
            }
            this._color.set(value);
            this._updateRenderData();
          }
        }, {
          key: "width",
          get: function get() {
            return this._width;
          },
          set: function set(value) {
            if (this._width === value) {
              return;
            }
            this._width = value;
            this._updateRenderData();
          }
        }]);
        return LabelOutline;
      }(Component), (_initializer$1P = applyDecoratedInitializer(_class2$1Z.prototype, "_color", [serializable$j], function () {
        return new Color$1(0, 0, 0, 255);
      }), _initializer2$1s = applyDecoratedInitializer(_class2$1Z.prototype, "_width", [serializable$j], function () {
        return 2;
      })), _class2$1Z)) || _class$2c) || _class$2c) || _class$2c));
      legacyCC.LabelOutline = LabelOutline;

      var _dec$2c, _class$2b, _class2$1Y, _initializer$1O, _initializer2$1r, _initializer3$Y, _class3$u;
      var PostProcess = (_dec$2c = ccclass$n('cc.PostProcess'), _dec$2c(_class$2b = disallowMultiple$1(_class$2b = (_class2$1Y = (_class3$u = function (_Component) {
        _inheritsLoose(PostProcess, _Component);
        function PostProcess() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Component.call.apply(_Component, [this].concat(args)) || this;
          _this.global = _initializer$1O && _initializer$1O();
          _this._shadingScale = _initializer2$1r && _initializer2$1r();
          _this.enableShadingScaleInEditor = _initializer3$Y && _initializer3$Y();
          _this.settings = new Map();
          return _this;
        }
        var _proto = PostProcess.prototype;
        _proto.addSetting = function addSetting(setting) {
          this.settings.set(setting.constructor, setting);
        };
        _proto.removeSetting = function removeSetting(setting) {
          this.settings["delete"](setting.constructor);
        };
        _proto.getSetting = function getSetting(ctor) {
          return this.settings.get(ctor);
        };
        _proto.onEnable = function onEnable() {
          PostProcess.all.push(this);
        };
        _proto.onDisable = function onDisable() {
          var idx = PostProcess.all.indexOf(this);
          if (idx !== -1) {
            PostProcess.all.splice(idx, 1);
          }
        };
        _createClass(PostProcess, [{
          key: "shadingScale",
          get: function get() {
            return this._shadingScale;
          },
          set: function set(v) {
            this._shadingScale = v;
          }
        }]);
        return PostProcess;
      }(Component), _class3$u.all = [], _class3$u), (_initializer$1O = applyDecoratedInitializer(_class2$1Y.prototype, "global", [property$3, serializable$j], function () {
        return true;
      }), _initializer2$1r = applyDecoratedInitializer(_class2$1Y.prototype, "_shadingScale", [serializable$j], function () {
        return 1;
      }), _applyDecoratedDescriptor(_class2$1Y.prototype, "shadingScale", [property$3], Object.getOwnPropertyDescriptor(_class2$1Y.prototype, "shadingScale"), _class2$1Y.prototype), _initializer3$Y = applyDecoratedInitializer(_class2$1Y.prototype, "enableShadingScaleInEditor", [property$3, serializable$j], function () {
        return false;
      })), _class2$1Y)) || _class$2b) || _class$2b);

      var _dec$2b, _dec2$1I, _dec3$1c, _dec4$T, _dec5$K, _dec6$u, _dec7$n, _dec8$h, _dec9$e, _dec10$9, _class$2a, _class2$1X, _initializer$1N, _initializer2$1q, _initializer3$X, _initializer4$K, _initializer5$y, _initializer6$q, _initializer7$l, _initializer8$k, _initializer9$i, _initializer10$g, _initializer11$e, _initializer12$c, _initializer13$b, _initializer14$9, _initializer15$6, _initializer16$6, _initializer17$5, _initializer18$5, _initializer19$4, _initializer20$3, _initializer21$3, _initializer22$2, _class3$t;
      var _temp_vec3_1 = new Vec3();
      var ProjectionType = Enum(CameraProjection);
      var FOVAxis = Enum(CameraFOVAxis);
      var Aperture = Enum(CameraAperture);
      var Shutter = Enum(CameraShutter);
      var ISO = Enum(CameraISO);
      var ClearFlag = Enum({
        SKYBOX: SKYBOX_FLAG | ClearFlagBit.DEPTH_STENCIL,
        SOLID_COLOR: ClearFlagBit.ALL,
        DEPTH_ONLY: ClearFlagBit.DEPTH_STENCIL,
        DONT_CLEAR: ClearFlagBit.NONE
      });
      var Camera = exports('dS', (_dec$2b = ccclass$n('cc.Camera'), _dec2$1I = type$7(Layers.BitMask), _dec3$1c = type$7(ClearFlag), _dec4$T = type$7(ProjectionType), _dec5$K = type$7(FOVAxis), _dec6$u = type$7(Aperture), _dec7$n = type$7(Shutter), _dec8$h = type$7(ISO), _dec9$e = type$7(RenderTexture), _dec10$9 = type$7(PostProcess), _dec$2b(_class$2a = (_class2$1X = (_class3$t = function (_Component) {
        _inheritsLoose(Camera, _Component);
        function Camera() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Component.call.apply(_Component, [this].concat(args)) || this;
          _this._projection = _initializer$1N && _initializer$1N();
          _this._priority = _initializer2$1q && _initializer2$1q();
          _this._fov = _initializer3$X && _initializer3$X();
          _this._fovAxis = _initializer4$K && _initializer4$K();
          _this._orthoHeight = _initializer5$y && _initializer5$y();
          _this._near = _initializer6$q && _initializer6$q();
          _this._far = _initializer7$l && _initializer7$l();
          _this._color = _initializer8$k && _initializer8$k();
          _this._depth = _initializer9$i && _initializer9$i();
          _this._stencil = _initializer10$g && _initializer10$g();
          _this._clearFlags = _initializer11$e && _initializer11$e();
          _this._rect = _initializer12$c && _initializer12$c();
          _this._aperture = _initializer13$b && _initializer13$b();
          _this._shutter = _initializer14$9 && _initializer14$9();
          _this._iso = _initializer15$6 && _initializer15$6();
          _this._screenScale = _initializer16$6 && _initializer16$6();
          _this._visibility = _initializer17$5 && _initializer17$5();
          _this._targetTexture = _initializer18$5 && _initializer18$5();
          _this._postProcess = _initializer19$4 && _initializer19$4();
          _this._usePostProcess = _initializer20$3 && _initializer20$3();
          _this._camera = null;
          _this._inEditorMode = false;
          _this._flows = undefined;
          _this._cameraType = _initializer21$3 && _initializer21$3();
          _this._trackingType = _initializer22$2 && _initializer22$2();
          return _this;
        }
        var _proto = Camera.prototype;
        _proto.onLoad = function onLoad() {
          this._createCamera();
        };
        _proto.onEnable = function onEnable() {
          this.node.hasChangedFlags |= TransformBit.POSITION;
          if (this._camera) {
            this._attachToScene();
          }
        };
        _proto.onDisable = function onDisable() {
          if (this._camera) {
            this._detachFromScene();
          }
        };
        _proto.onDestroy = function onDestroy() {
          if (this._camera) {
            this._camera.destroy();
            this._camera = null;
          }
          if (this._targetTexture) {
            this._targetTexture.off('resize');
          }
        };
        _proto.screenPointToRay = function screenPointToRay(x, y, out) {
          if (!out) {
            out = Ray.create();
          }
          if (this._camera) {
            this._camera.screenPointToRay(out, x, y);
          }
          return out;
        };
        _proto.worldToScreen = function worldToScreen(worldPos, out) {
          if (!out) {
            out = new Vec3();
          }
          if (this._camera) {
            this._camera.worldToScreen(out, worldPos);
          }
          return out;
        };
        _proto.screenToWorld = function screenToWorld(screenPos, out) {
          if (!out) {
            out = this.node.getWorldPosition();
          }
          if (this._camera) {
            this._camera.screenToWorld(out, screenPos);
          }
          return out;
        };
        _proto.convertToUINode = function convertToUINode(wpos, uiNode, out) {
          if (!out) {
            out = new Vec3();
          }
          if (!this._camera) {
            return out;
          }
          this.worldToScreen(wpos, _temp_vec3_1);
          var cmp = uiNode.getComponent('cc.UITransform');
          var designSize = legacyCC.view.getVisibleSize();
          var xoffset = _temp_vec3_1.x - this._camera.width * 0.5;
          var yoffset = _temp_vec3_1.y - this._camera.height * 0.5;
          _temp_vec3_1.x = xoffset / legacyCC.view.getScaleX() + designSize.width * 0.5;
          _temp_vec3_1.y = yoffset / legacyCC.view.getScaleY() + designSize.height * 0.5;
          if (cmp) {
            cmp.convertToNodeSpaceAR(_temp_vec3_1, out);
          }
          return out;
        };
        _proto._createCamera = function _createCamera() {
          if (!this._camera) {
            this._camera = legacyCC.director.root.createCamera();
            this._camera.initialize({
              name: this.node.name,
              node: this.node,
              projection: this._projection,
              window: this._inEditorMode ? legacyCC.director.root && legacyCC.director.root.mainWindow : legacyCC.director.root && legacyCC.director.root.tempWindow,
              priority: this._priority,
              cameraType: this.cameraType,
              trackingType: this.trackingType
            });
            this._camera.setViewportInOrientedSpace(this._rect);
            this._camera.fovAxis = this._fovAxis;
            this._camera.fov = toRadian(this._fov);
            this._camera.orthoHeight = this._orthoHeight;
            this._camera.nearClip = this._near;
            this._camera.farClip = this._far;
            this._camera.clearColor = this._color;
            this._camera.clearDepth = this._depth;
            this._camera.clearStencil = this._stencil;
            this._camera.clearFlag = this._clearFlags;
            this._camera.visibility = this._visibility;
            this._camera.aperture = this._aperture;
            this._camera.shutter = this._shutter;
            this._camera.iso = this._iso;
            this._camera.postProcess = this._postProcess;
            this._camera.usePostProcess = this._usePostProcess;
          }
          this._updateTargetTexture();
        };
        _proto._attachToScene = function _attachToScene() {
          if (!this.node.scene || !this._camera) {
            return;
          }
          if (this._camera && this._camera.scene) {
            this._camera.scene.removeCamera(this._camera);
          }
          var rs = this._getRenderScene();
          rs.addCamera(this._camera);
        };
        _proto._detachFromScene = function _detachFromScene() {
          if (this._camera && this._camera.scene) {
            this._camera.scene.removeCamera(this._camera);
          }
        };
        _proto._checkTargetTextureEvent = function _checkTargetTextureEvent(old) {
          var _this2 = this;
          if (old) {
            old.off('resize');
          }
          if (this._targetTexture) {
            this._targetTexture.on('resize', function (window) {
              if (_this2._camera) {
                _this2._camera.setFixedSize(window.width, window.height);
              }
            }, this);
          }
        };
        _proto._updateTargetTexture = function _updateTargetTexture() {
          if (!this._camera) {
            return;
          }
          if (this._targetTexture) {
            var window = this._targetTexture.window;
            this._camera.changeTargetWindow(window);
            this._camera.setFixedSize(window.width, window.height);
          }
        };
        _createClass(Camera, [{
          key: "camera",
          get: function get() {
            return this._camera;
          }
        }, {
          key: "priority",
          get: function get() {
            return this._priority;
          },
          set: function set(val) {
            this._priority = val;
            if (this._camera) {
              this._camera.priority = val;
            }
          }
        }, {
          key: "visibility",
          get: function get() {
            return this._visibility;
          },
          set: function set(val) {
            this._visibility = val;
            if (this._camera) {
              this._camera.visibility = val;
            }
          }
        }, {
          key: "clearFlags",
          get: function get() {
            return this._clearFlags;
          },
          set: function set(val) {
            this._clearFlags = val;
            if (this._camera) {
              this._camera.clearFlag = val;
            }
          }
        }, {
          key: "clearColor",
          get: function get() {
            return this._color;
          },
          set: function set(val) {
            this._color.set(val);
            if (this._camera) {
              this._camera.clearColor = this._color;
            }
          }
        }, {
          key: "clearDepth",
          get: function get() {
            return this._depth;
          },
          set: function set(val) {
            this._depth = val;
            if (this._camera) {
              this._camera.clearDepth = val;
            }
          }
        }, {
          key: "clearStencil",
          get: function get() {
            return this._stencil;
          },
          set: function set(val) {
            this._stencil = val;
            if (this._camera) {
              this._camera.clearStencil = val;
            }
          }
        }, {
          key: "projection",
          get: function get() {
            return this._projection;
          },
          set: function set(val) {
            this._projection = val;
            if (this._camera) {
              this._camera.projectionType = val;
            }
          }
        }, {
          key: "fovAxis",
          get: function get() {
            return this._fovAxis;
          },
          set: function set(val) {
            if (val === this._fovAxis) {
              return;
            }
            this._fovAxis = val;
            if (this._camera) {
              this._camera.fovAxis = val;
              if (val === CameraFOVAxis.VERTICAL) {
                this.fov = this._fov * this._camera.aspect;
              } else {
                this.fov = this._fov / this._camera.aspect;
              }
            }
          }
        }, {
          key: "fov",
          get: function get() {
            return this._fov;
          },
          set: function set(val) {
            this._fov = val;
            if (this._camera) {
              this._camera.fov = toRadian(val);
            }
          }
        }, {
          key: "orthoHeight",
          get: function get() {
            return this._orthoHeight;
          },
          set: function set(val) {
            this._orthoHeight = val;
            if (this._camera) {
              this._camera.orthoHeight = val;
            }
          }
        }, {
          key: "near",
          get: function get() {
            return this._near;
          },
          set: function set(val) {
            this._near = val;
            if (this._camera) {
              this._camera.nearClip = val;
            }
          }
        }, {
          key: "far",
          get: function get() {
            return this._far;
          },
          set: function set(val) {
            this._far = val;
            if (this._camera) {
              this._camera.farClip = val;
            }
          }
        }, {
          key: "aperture",
          get: function get() {
            return this._aperture;
          },
          set: function set(val) {
            this._aperture = val;
            if (this._camera) {
              this._camera.aperture = val;
            }
          }
        }, {
          key: "shutter",
          get: function get() {
            return this._shutter;
          },
          set: function set(val) {
            this._shutter = val;
            if (this._camera) {
              this._camera.shutter = val;
            }
          }
        }, {
          key: "iso",
          get: function get() {
            return this._iso;
          },
          set: function set(val) {
            this._iso = val;
            if (this._camera) {
              this._camera.iso = val;
            }
          }
        }, {
          key: "rect",
          get: function get() {
            return this._rect;
          },
          set: function set(val) {
            this._rect = val;
            if (this._camera) {
              this._camera.setViewportInOrientedSpace(val);
            }
          }
        }, {
          key: "targetTexture",
          get: function get() {
            return this._targetTexture;
          },
          set: function set(value) {
            if (this._targetTexture === value) {
              return;
            }
            var old = this._targetTexture;
            this._targetTexture = value;
            this._checkTargetTextureEvent(old);
            this._updateTargetTexture();
            if (!value && this._camera) {
              this._camera.changeTargetWindow(null);
              this._camera.isWindowSize = true;
            }
            this.node.emit(Camera.TARGET_TEXTURE_CHANGE, this);
          }
        }, {
          key: "usePostProcess",
          get: function get() {
            return this._usePostProcess;
          },
          set: function set(v) {
            this._usePostProcess = v;
            if (this._camera) {
              this._camera.usePostProcess = v;
            }
          }
        }, {
          key: "postProcess",
          get: function get() {
            return this._postProcess;
          },
          set: function set(v) {
            this._postProcess = v;
            if (this._camera) {
              this._camera.postProcess = v;
            }
          }
        }, {
          key: "screenScale",
          get: function get() {
            return this._screenScale;
          },
          set: function set(val) {
            this._screenScale = val;
            if (this._camera) {
              this._camera.screenScale = val;
            }
          }
        }, {
          key: "inEditorMode",
          get: function get() {
            return this._inEditorMode;
          },
          set: function set(value) {
            this._inEditorMode = value;
            if (this._camera) {
              this._camera.changeTargetWindow(value ? legacyCC.director.root && legacyCC.director.root.mainWindow : legacyCC.director.root && legacyCC.director.root.tempWindow);
            }
          }
        }, {
          key: "cameraType",
          get: function get() {
            return this._cameraType;
          },
          set: function set(val) {
            if (this._cameraType === val) {
              return;
            }
            this._cameraType = val;
            if (this.camera) {
              this.camera.cameraType = val;
            }
          }
        }, {
          key: "trackingType",
          get: function get() {
            return this._trackingType;
          },
          set: function set(val) {
            if (this._trackingType === val) {
              return;
            }
            this._trackingType = val;
            if (this.camera) {
              this.camera.trackingType = val;
            }
          }
        }]);
        return Camera;
      }(Component), _class3$t.ProjectionType = ProjectionType, _class3$t.FOVAxis = FOVAxis, _class3$t.ClearFlag = ClearFlag, _class3$t.Aperture = Aperture, _class3$t.Shutter = Shutter, _class3$t.ISO = ISO, _class3$t.TARGET_TEXTURE_CHANGE = 'tex-change', _class3$t), (_initializer$1N = applyDecoratedInitializer(_class2$1X.prototype, "_projection", [serializable$j], function () {
        return ProjectionType.PERSPECTIVE;
      }), _initializer2$1q = applyDecoratedInitializer(_class2$1X.prototype, "_priority", [serializable$j], function () {
        return 0;
      }), _initializer3$X = applyDecoratedInitializer(_class2$1X.prototype, "_fov", [serializable$j], function () {
        return 45;
      }), _initializer4$K = applyDecoratedInitializer(_class2$1X.prototype, "_fovAxis", [serializable$j], function () {
        return FOVAxis.VERTICAL;
      }), _initializer5$y = applyDecoratedInitializer(_class2$1X.prototype, "_orthoHeight", [serializable$j], function () {
        return 10;
      }), _initializer6$q = applyDecoratedInitializer(_class2$1X.prototype, "_near", [serializable$j], function () {
        return 1;
      }), _initializer7$l = applyDecoratedInitializer(_class2$1X.prototype, "_far", [serializable$j], function () {
        return 1000;
      }), _initializer8$k = applyDecoratedInitializer(_class2$1X.prototype, "_color", [serializable$j], function () {
        return new Color$1('#333333');
      }), _initializer9$i = applyDecoratedInitializer(_class2$1X.prototype, "_depth", [serializable$j], function () {
        return 1;
      }), _initializer10$g = applyDecoratedInitializer(_class2$1X.prototype, "_stencil", [serializable$j], function () {
        return 0;
      }), _initializer11$e = applyDecoratedInitializer(_class2$1X.prototype, "_clearFlags", [serializable$j], function () {
        return ClearFlag.SOLID_COLOR;
      }), _initializer12$c = applyDecoratedInitializer(_class2$1X.prototype, "_rect", [serializable$j], function () {
        return new Rect$1(0, 0, 1, 1);
      }), _initializer13$b = applyDecoratedInitializer(_class2$1X.prototype, "_aperture", [serializable$j], function () {
        return Aperture.F16_0;
      }), _initializer14$9 = applyDecoratedInitializer(_class2$1X.prototype, "_shutter", [serializable$j], function () {
        return Shutter.D125;
      }), _initializer15$6 = applyDecoratedInitializer(_class2$1X.prototype, "_iso", [serializable$j], function () {
        return ISO.ISO100;
      }), _initializer16$6 = applyDecoratedInitializer(_class2$1X.prototype, "_screenScale", [serializable$j], function () {
        return 1;
      }), _initializer17$5 = applyDecoratedInitializer(_class2$1X.prototype, "_visibility", [serializable$j], function () {
        return CAMERA_DEFAULT_MASK;
      }), _initializer18$5 = applyDecoratedInitializer(_class2$1X.prototype, "_targetTexture", [serializable$j], function () {
        return null;
      }), _initializer19$4 = applyDecoratedInitializer(_class2$1X.prototype, "_postProcess", [serializable$j], function () {
        return null;
      }), _initializer20$3 = applyDecoratedInitializer(_class2$1X.prototype, "_usePostProcess", [serializable$j], function () {
        return false;
      }), _initializer21$3 = applyDecoratedInitializer(_class2$1X.prototype, "_cameraType", [serializable$j], function () {
        return CameraType.DEFAULT;
      }), _initializer22$2 = applyDecoratedInitializer(_class2$1X.prototype, "_trackingType", [serializable$j], function () {
        return TrackingType.NO_TRACKING;
      }), _applyDecoratedDescriptor(_class2$1X.prototype, "visibility", [_dec2$1I], Object.getOwnPropertyDescriptor(_class2$1X.prototype, "visibility"), _class2$1X.prototype), _applyDecoratedDescriptor(_class2$1X.prototype, "clearFlags", [_dec3$1c], Object.getOwnPropertyDescriptor(_class2$1X.prototype, "clearFlags"), _class2$1X.prototype), _applyDecoratedDescriptor(_class2$1X.prototype, "projection", [_dec4$T], Object.getOwnPropertyDescriptor(_class2$1X.prototype, "projection"), _class2$1X.prototype), _applyDecoratedDescriptor(_class2$1X.prototype, "fovAxis", [_dec5$K], Object.getOwnPropertyDescriptor(_class2$1X.prototype, "fovAxis"), _class2$1X.prototype), _applyDecoratedDescriptor(_class2$1X.prototype, "aperture", [_dec6$u], Object.getOwnPropertyDescriptor(_class2$1X.prototype, "aperture"), _class2$1X.prototype), _applyDecoratedDescriptor(_class2$1X.prototype, "shutter", [_dec7$n], Object.getOwnPropertyDescriptor(_class2$1X.prototype, "shutter"), _class2$1X.prototype), _applyDecoratedDescriptor(_class2$1X.prototype, "iso", [_dec8$h], Object.getOwnPropertyDescriptor(_class2$1X.prototype, "iso"), _class2$1X.prototype), _applyDecoratedDescriptor(_class2$1X.prototype, "targetTexture", [_dec9$e], Object.getOwnPropertyDescriptor(_class2$1X.prototype, "targetTexture"), _class2$1X.prototype), _applyDecoratedDescriptor(_class2$1X.prototype, "usePostProcess", [property$3], Object.getOwnPropertyDescriptor(_class2$1X.prototype, "usePostProcess"), _class2$1X.prototype), _applyDecoratedDescriptor(_class2$1X.prototype, "postProcess", [_dec10$9], Object.getOwnPropertyDescriptor(_class2$1X.prototype, "postProcess"), _class2$1X.prototype)), _class2$1X)) || _class$2a));
      legacyCC.Camera = Camera;

      var _orientationMap;
      var localWinSize = new Size$1();
      var orientationMap = (_orientationMap = {}, _orientationMap[macro.ORIENTATION_AUTO] = Orientation.AUTO, _orientationMap[macro.ORIENTATION_LANDSCAPE] = Orientation.LANDSCAPE, _orientationMap[macro.ORIENTATION_PORTRAIT] = Orientation.PORTRAIT, _orientationMap);
      var View = exports('fC', function (_Eventify) {
        _inheritsLoose(View, _Eventify);
        function View() {
          var _this;
          _this = _Eventify.call(this) || this;
          _this._designResolutionSize = void 0;
          _this._scaleX = void 0;
          _this._scaleY = void 0;
          _this._viewportRect = void 0;
          _this._visibleRect = void 0;
          _this._autoFullScreen = void 0;
          _this._retinaEnabled = void 0;
          _this._resizeCallback = void 0;
          _this._resolutionPolicy = void 0;
          _this._rpExactFit = void 0;
          _this._rpShowAll = void 0;
          _this._rpNoBorder = void 0;
          _this._rpFixedHeight = void 0;
          _this._rpFixedWidth = void 0;
          var _strategyer = ContainerStrategy;
          var _strategy = ContentStrategy;
          _this._designResolutionSize = new Size$1(0, 0);
          _this._scaleX = 1;
          _this._scaleY = 1;
          _this._viewportRect = new Rect$1(0, 0, 0, 0);
          _this._visibleRect = new Rect$1(0, 0, 0, 0);
          _this._autoFullScreen = false;
          _this._retinaEnabled = false;
          _this._resizeCallback = null;
          _this._rpExactFit = new ResolutionPolicy(_strategyer.EQUAL_TO_FRAME, _strategy.EXACT_FIT);
          _this._rpShowAll = new ResolutionPolicy(_strategyer.EQUAL_TO_FRAME, _strategy.SHOW_ALL);
          _this._rpNoBorder = new ResolutionPolicy(_strategyer.EQUAL_TO_FRAME, _strategy.NO_BORDER);
          _this._rpFixedHeight = new ResolutionPolicy(_strategyer.EQUAL_TO_FRAME, _strategy.FIXED_HEIGHT);
          _this._rpFixedWidth = new ResolutionPolicy(_strategyer.EQUAL_TO_FRAME, _strategy.FIXED_WIDTH);
          _this._resolutionPolicy = _this._rpShowAll;
          return _this;
        }
        var _proto = View.prototype;
        _proto.init = function init() {
          var windowSize = screen.windowSize;
          var w = windowSize.width;
          var h = windowSize.height;
          this._designResolutionSize.width = w;
          this._designResolutionSize.height = h;
          this._viewportRect.width = w;
          this._viewportRect.height = h;
          this._visibleRect.width = w;
          this._visibleRect.height = h;
          localWinSize.width = this._visibleRect.width;
          localWinSize.height = this._visibleRect.height;
          if (visibleRect) {
            visibleRect.init(this._visibleRect);
          }
          {
            this.resizeWithBrowserSize(true);
            var designResolution = settings.querySettings(Settings.Category.SCREEN, 'designResolution');
            if (designResolution) {
              this.setDesignResolutionSize(Number(designResolution.width), Number(designResolution.height), designResolution.policy || ResolutionPolicy.FIXED_HEIGHT);
            }
          }
          screen.on('window-resize', this._updateAdaptResult, this);
          screen.on('orientation-change', this._updateAdaptResult, this);
          screen.on('fullscreen-change', this._updateAdaptResult, this);
        };
        _proto.resizeWithBrowserSize = function resizeWithBrowserSize(enabled) {
          screenAdapter.handleResizeEvent = enabled;
        };
        _proto.setResizeCallback = function setResizeCallback(callback) {
          if (typeof callback === 'function' || callback == null) {
            this._resizeCallback = callback;
          }
        };
        _proto.setOrientation = function setOrientation(orientation) {
          screenAdapter.orientation = orientationMap[orientation];
        };
        _proto.adjustViewportMeta = function adjustViewportMeta(enabled) {};
        _proto.enableRetina = function enableRetina(enabled) {
          this._retinaEnabled = !!enabled;
        };
        _proto.isRetinaEnabled = function isRetinaEnabled() {
          return this._retinaEnabled;
        };
        _proto.enableAutoFullScreen = function enableAutoFullScreen(enabled) {
          if (enabled === this._autoFullScreen) {
            return;
          }
          this._autoFullScreen = enabled;
          if (enabled) {
            screen.requestFullScreen()["catch"](function (e) {});
          }
        };
        _proto.isAutoFullScreenEnabled = function isAutoFullScreenEnabled() {
          return this._autoFullScreen;
        };
        _proto.setCanvasSize = function setCanvasSize(width, height) {
          screenAdapter.resolutionScale = 1;
          var dpr = screenAdapter.devicePixelRatio;
          var windowSize = new Size$1(width * dpr, height * dpr);
          screen.windowSize = windowSize;
        };
        _proto.getCanvasSize = function getCanvasSize() {
          return screen.windowSize;
        };
        _proto.getFrameSize = function getFrameSize() {
          var dpr = screenAdapter.devicePixelRatio;
          var sizeInCssPixels = screen.windowSize;
          sizeInCssPixels.width /= dpr;
          sizeInCssPixels.height /= dpr;
          return sizeInCssPixels;
        };
        _proto.setFrameSize = function setFrameSize(width, height) {
          var dpr = screenAdapter.devicePixelRatio;
          screen.windowSize = new Size$1(width * dpr, height * dpr);
        };
        _proto.getVisibleSize = function getVisibleSize() {
          return new Size$1(this._visibleRect.width, this._visibleRect.height);
        };
        _proto.getVisibleSizeInPixel = function getVisibleSizeInPixel() {
          return new Size$1(this._visibleRect.width * this._scaleX, this._visibleRect.height * this._scaleY);
        };
        _proto.getVisibleOrigin = function getVisibleOrigin() {
          return new Vec2(this._visibleRect.x, this._visibleRect.y);
        };
        _proto.getVisibleOriginInPixel = function getVisibleOriginInPixel() {
          return new Vec2(this._visibleRect.x * this._scaleX, this._visibleRect.y * this._scaleY);
        };
        _proto.getResolutionPolicy = function getResolutionPolicy() {
          return this._resolutionPolicy;
        };
        _proto._updateResolutionPolicy = function _updateResolutionPolicy(resolutionPolicy) {
          if (resolutionPolicy instanceof ResolutionPolicy) {
            this._resolutionPolicy = resolutionPolicy;
          } else {
            var _locPolicy = ResolutionPolicy;
            if (resolutionPolicy === _locPolicy.EXACT_FIT) {
              this._resolutionPolicy = this._rpExactFit;
            }
            if (resolutionPolicy === _locPolicy.SHOW_ALL) {
              this._resolutionPolicy = this._rpShowAll;
            }
            if (resolutionPolicy === _locPolicy.NO_BORDER) {
              this._resolutionPolicy = this._rpNoBorder;
            }
            if (resolutionPolicy === _locPolicy.FIXED_HEIGHT) {
              this._resolutionPolicy = this._rpFixedHeight;
            }
            if (resolutionPolicy === _locPolicy.FIXED_WIDTH) {
              this._resolutionPolicy = this._rpFixedWidth;
            }
          }
        };
        _proto.setResolutionPolicy = function setResolutionPolicy(resolutionPolicy) {
          this._updateResolutionPolicy(resolutionPolicy);
          var designedResolution = view.getDesignResolutionSize();
          view.setDesignResolutionSize(designedResolution.width, designedResolution.height, resolutionPolicy);
        };
        _proto.setDesignResolutionSize = function setDesignResolutionSize(width, height, resolutionPolicy) {
          if (!(width > 0 && height > 0)) {
            errorID(2200);
            return;
          }
          this._updateResolutionPolicy(resolutionPolicy);
          var policy = this._resolutionPolicy;
          if (policy) {
            policy.preApply(this);
          }
          this._designResolutionSize.width = width;
          this._designResolutionSize.height = height;
          var result = policy.apply(this, this._designResolutionSize);
          if (result.scale && result.scale.length === 2) {
            this._scaleX = result.scale[0];
            this._scaleY = result.scale[1];
          }
          if (result.viewport) {
            var vp = this._viewportRect;
            var vb = this._visibleRect;
            var rv = result.viewport;
            vp.x = rv.x;
            vp.y = rv.y;
            vp.width = rv.width;
            vp.height = rv.height;
            vb.x = 0;
            vb.y = 0;
            vb.width = rv.width / this._scaleX;
            vb.height = rv.height / this._scaleY;
          }
          policy.postApply(this);
          localWinSize.width = this._visibleRect.width;
          localWinSize.height = this._visibleRect.height;
          if (visibleRect) {
            visibleRect.init(this._visibleRect);
          }
          this.emit('design-resolution-changed');
        };
        _proto.getDesignResolutionSize = function getDesignResolutionSize() {
          return new Size$1(this._designResolutionSize.width, this._designResolutionSize.height);
        };
        _proto.setRealPixelResolution = function setRealPixelResolution(width, height, resolutionPolicy) {
          {
            document.documentElement.style.width = width + "px";
            document.body.style.width = width + "px";
            document.body.style.left = '0px';
            document.body.style.top = '0px';
          }
          this.setDesignResolutionSize(width, height, resolutionPolicy);
        };
        _proto.getViewportRect = function getViewportRect() {
          return this._viewportRect;
        };
        _proto.getScaleX = function getScaleX() {
          return this._scaleX;
        };
        _proto.getScaleY = function getScaleY() {
          return this._scaleY;
        };
        _proto.getDevicePixelRatio = function getDevicePixelRatio() {
          return screenAdapter.devicePixelRatio;
        };
        _proto.convertToLocationInView = function convertToLocationInView(tx, ty, relatedPos, out) {
          if (out === void 0) {
            out = new Vec2();
          }
          var x = screenAdapter.devicePixelRatio * (tx - relatedPos.left);
          var y = screenAdapter.devicePixelRatio * (relatedPos.top + relatedPos.height - ty);
          if (screenAdapter.isFrameRotated) {
            out.x = screen.windowSize.width - y;
            out.y = x;
          } else {
            out.x = x;
            out.y = y;
          }
          return out;
        };
        _proto._convertToUISpace = function _convertToUISpace(point) {
          var viewport = this._viewportRect;
          point.x = (point.x - viewport.x) / this._scaleX;
          point.y = (point.y - viewport.y) / this._scaleY;
        };
        _proto._updateAdaptResult = function _updateAdaptResult(width, height, windowId) {
          var _this$_resizeCallback;
          legacyCC.director.root.resize(width, height, windowId === undefined || windowId === 0 ? 1 : windowId);
          var w = this._designResolutionSize.width;
          var h = this._designResolutionSize.height;
          if (width > 0) {
            this.setDesignResolutionSize(w, h, this._resolutionPolicy);
          }
          this.emit('canvas-resize');
          (_this$_resizeCallback = this._resizeCallback) === null || _this$_resizeCallback === void 0 ? void 0 : _this$_resizeCallback.call(this);
        };
        return View;
      }(Eventify(System)));
      View.instance = void 0;
      var ContainerStrategy = function () {
        function ContainerStrategy() {
          this.name = 'ContainerStrategy';
        }
        var _proto2 = ContainerStrategy.prototype;
        _proto2.preApply = function preApply(_view) {};
        _proto2.apply = function apply(_view, designedResolution) {};
        _proto2.postApply = function postApply(_view) {};
        _proto2._setupCanvas = function _setupCanvas() {
          var locCanvas = legacyCC.game.canvas;
          if (locCanvas) {
            var windowSize = screen.windowSize;
            if (locCanvas.width !== windowSize.width) {
              locCanvas.width = windowSize.width;
            }
            if (locCanvas.height !== windowSize.height) {
              locCanvas.height = windowSize.height;
            }
          }
        };
        return ContainerStrategy;
      }();
      ContainerStrategy.EQUAL_TO_FRAME = void 0;
      ContainerStrategy.PROPORTION_TO_FRAME = void 0;
      var ContentStrategy = function () {
        function ContentStrategy() {
          this.name = 'ContentStrategy';
          this._result = void 0;
          this._result = {
            scale: [1, 1],
            viewport: null
          };
        }
        var _proto3 = ContentStrategy.prototype;
        _proto3.preApply = function preApply(_view) {};
        _proto3.apply = function apply(_view, designedResolution) {
          return {
            scale: [1, 1]
          };
        };
        _proto3.postApply = function postApply(_view) {};
        _proto3._buildResult = function _buildResult(containerW, containerH, contentW, contentH, scaleX, scaleY) {
          if (Math.abs(containerW - contentW) < 2) {
            contentW = containerW;
          }
          if (Math.abs(containerH - contentH) < 2) {
            contentH = containerH;
          }
          var viewport = new Rect$1(Math.round((containerW - contentW) / 2), Math.round((containerH - contentH) / 2), contentW, contentH);
          this._result.scale = [scaleX, scaleY];
          this._result.viewport = viewport;
          return this._result;
        };
        return ContentStrategy;
      }();
      ContentStrategy.EXACT_FIT = void 0;
      ContentStrategy.SHOW_ALL = void 0;
      ContentStrategy.NO_BORDER = void 0;
      ContentStrategy.FIXED_HEIGHT = void 0;
      ContentStrategy.FIXED_WIDTH = void 0;
      (function () {
        var EqualToFrame = function (_ContainerStrategy) {
          _inheritsLoose(EqualToFrame, _ContainerStrategy);
          function EqualToFrame() {
            var _this2;
            for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
              args[_key] = arguments[_key];
            }
            _this2 = _ContainerStrategy.call.apply(_ContainerStrategy, [this].concat(args)) || this;
            _this2.name = 'EqualToFrame';
            return _this2;
          }
          var _proto4 = EqualToFrame.prototype;
          _proto4.apply = function apply(_view, designedResolution) {
            screenAdapter.isProportionalToFrame = false;
            this._setupCanvas();
          };
          return EqualToFrame;
        }(ContainerStrategy);
        var ProportionalToFrame = function (_ContainerStrategy2) {
          _inheritsLoose(ProportionalToFrame, _ContainerStrategy2);
          function ProportionalToFrame() {
            var _this3;
            for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
              args[_key2] = arguments[_key2];
            }
            _this3 = _ContainerStrategy2.call.apply(_ContainerStrategy2, [this].concat(args)) || this;
            _this3.name = 'ProportionalToFrame';
            return _this3;
          }
          var _proto5 = ProportionalToFrame.prototype;
          _proto5.apply = function apply(_view, designedResolution) {
            screenAdapter.isProportionalToFrame = true;
            this._setupCanvas();
          };
          return ProportionalToFrame;
        }(ContainerStrategy);
        ContainerStrategy.EQUAL_TO_FRAME = new EqualToFrame();
        ContainerStrategy.PROPORTION_TO_FRAME = new ProportionalToFrame();
        var ExactFit = function (_ContentStrategy) {
          _inheritsLoose(ExactFit, _ContentStrategy);
          function ExactFit() {
            var _this4;
            for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
              args[_key3] = arguments[_key3];
            }
            _this4 = _ContentStrategy.call.apply(_ContentStrategy, [this].concat(args)) || this;
            _this4.name = 'ExactFit';
            return _this4;
          }
          var _proto6 = ExactFit.prototype;
          _proto6.apply = function apply(_view, designedResolution) {
            var windowSize = screen.windowSize;
            var containerW = windowSize.width;
            var containerH = windowSize.height;
            var scaleX = containerW / designedResolution.width;
            var scaleY = containerH / designedResolution.height;
            return this._buildResult(containerW, containerH, containerW, containerH, scaleX, scaleY);
          };
          return ExactFit;
        }(ContentStrategy);
        var ShowAll = function (_ContentStrategy2) {
          _inheritsLoose(ShowAll, _ContentStrategy2);
          function ShowAll() {
            var _this5;
            for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
              args[_key4] = arguments[_key4];
            }
            _this5 = _ContentStrategy2.call.apply(_ContentStrategy2, [this].concat(args)) || this;
            _this5.name = 'ShowAll';
            return _this5;
          }
          var _proto7 = ShowAll.prototype;
          _proto7.apply = function apply(_view, designedResolution) {
            var windowSize = screen.windowSize;
            var containerW = windowSize.width;
            var containerH = windowSize.height;
            var designW = designedResolution.width;
            var designH = designedResolution.height;
            var scaleX = containerW / designW;
            var scaleY = containerH / designH;
            var scale = 0;
            var contentW;
            var contentH;
            if (scaleX < scaleY) {
              scale = scaleX;
              contentW = containerW;
              contentH = designH * scale;
            } else {
              scale = scaleY;
              contentW = designW * scale;
              contentH = containerH;
            }
            return this._buildResult(containerW, containerH, contentW, contentH, scale, scale);
          };
          return ShowAll;
        }(ContentStrategy);
        var NoBorder = function (_ContentStrategy3) {
          _inheritsLoose(NoBorder, _ContentStrategy3);
          function NoBorder() {
            var _this6;
            for (var _len5 = arguments.length, args = new Array(_len5), _key5 = 0; _key5 < _len5; _key5++) {
              args[_key5] = arguments[_key5];
            }
            _this6 = _ContentStrategy3.call.apply(_ContentStrategy3, [this].concat(args)) || this;
            _this6.name = 'NoBorder';
            return _this6;
          }
          var _proto8 = NoBorder.prototype;
          _proto8.apply = function apply(_view, designedResolution) {
            var windowSize = screen.windowSize;
            var containerW = windowSize.width;
            var containerH = windowSize.height;
            var designW = designedResolution.width;
            var designH = designedResolution.height;
            var scaleX = containerW / designW;
            var scaleY = containerH / designH;
            var scale;
            var contentW;
            var contentH;
            if (scaleX < scaleY) {
              scale = scaleY;
              contentW = designW * scale;
              contentH = containerH;
            } else {
              scale = scaleX;
              contentW = containerW;
              contentH = designH * scale;
            }
            return this._buildResult(containerW, containerH, contentW, contentH, scale, scale);
          };
          return NoBorder;
        }(ContentStrategy);
        var FixedHeight = function (_ContentStrategy4) {
          _inheritsLoose(FixedHeight, _ContentStrategy4);
          function FixedHeight() {
            var _this7;
            for (var _len6 = arguments.length, args = new Array(_len6), _key6 = 0; _key6 < _len6; _key6++) {
              args[_key6] = arguments[_key6];
            }
            _this7 = _ContentStrategy4.call.apply(_ContentStrategy4, [this].concat(args)) || this;
            _this7.name = 'FixedHeight';
            return _this7;
          }
          var _proto9 = FixedHeight.prototype;
          _proto9.apply = function apply(_view, designedResolution) {
            var windowSize = screen.windowSize;
            var containerW = windowSize.width;
            var containerH = windowSize.height;
            var designH = designedResolution.height;
            var scale = containerH / designH;
            var contentW = containerW;
            var contentH = containerH;
            return this._buildResult(containerW, containerH, contentW, contentH, scale, scale);
          };
          return FixedHeight;
        }(ContentStrategy);
        var FixedWidth = function (_ContentStrategy5) {
          _inheritsLoose(FixedWidth, _ContentStrategy5);
          function FixedWidth() {
            var _this8;
            for (var _len7 = arguments.length, args = new Array(_len7), _key7 = 0; _key7 < _len7; _key7++) {
              args[_key7] = arguments[_key7];
            }
            _this8 = _ContentStrategy5.call.apply(_ContentStrategy5, [this].concat(args)) || this;
            _this8.name = 'FixedWidth';
            return _this8;
          }
          var _proto10 = FixedWidth.prototype;
          _proto10.apply = function apply(_view, designedResolution) {
            var windowSize = screen.windowSize;
            var containerW = windowSize.width;
            var containerH = windowSize.height;
            var designW = designedResolution.width;
            var scale = containerW / designW;
            var contentW = containerW;
            var contentH = containerH;
            return this._buildResult(containerW, containerH, contentW, contentH, scale, scale);
          };
          return FixedWidth;
        }(ContentStrategy);
        ContentStrategy.EXACT_FIT = new ExactFit();
        ContentStrategy.SHOW_ALL = new ShowAll();
        ContentStrategy.NO_BORDER = new NoBorder();
        ContentStrategy.FIXED_HEIGHT = new FixedHeight();
        ContentStrategy.FIXED_WIDTH = new FixedWidth();
      })();
      var ResolutionPolicy = exports('fD', function () {
        function ResolutionPolicy(containerStg, contentStg) {
          this.name = 'ResolutionPolicy';
          this._containerStrategy = void 0;
          this._contentStrategy = void 0;
          this._containerStrategy = null;
          this._contentStrategy = null;
          this.setContainerStrategy(containerStg);
          this.setContentStrategy(contentStg);
        }
        var _proto11 = ResolutionPolicy.prototype;
        _proto11.preApply = function preApply(_view) {
          this._contentStrategy.preApply(_view);
        };
        _proto11.apply = function apply(_view, designedResolution) {
          this._containerStrategy.apply(_view, designedResolution);
          return this._contentStrategy.apply(_view, designedResolution);
        };
        _proto11.postApply = function postApply(_view) {
          this._contentStrategy.postApply(_view);
        };
        _proto11.setContainerStrategy = function setContainerStrategy(containerStg) {
          if (containerStg instanceof ContainerStrategy) {
            this._containerStrategy = containerStg;
          }
        };
        _proto11.setContentStrategy = function setContentStrategy(contentStg) {
          if (contentStg instanceof ContentStrategy) {
            this._contentStrategy = contentStg;
          }
        };
        _createClass(ResolutionPolicy, [{
          key: "canvasSize",
          get: function get() {
            return screen.windowSize;
          }
        }]);
        return ResolutionPolicy;
      }());
      ResolutionPolicy.EXACT_FIT = 0;
      ResolutionPolicy.NO_BORDER = 1;
      ResolutionPolicy.SHOW_ALL = 2;
      ResolutionPolicy.FIXED_HEIGHT = 3;
      ResolutionPolicy.FIXED_WIDTH = 4;
      ResolutionPolicy.UNKNOWN = 5;
      ResolutionPolicy.ContainerStrategy = ContainerStrategy;
      ResolutionPolicy.ContentStrategy = ContentStrategy;
      legacyCC.ResolutionPolicy = ResolutionPolicy;
      var view = exports('fE', View.instance = legacyCC.view = new View());
      director.registerSystem('view', view, 0);
      legacyCC.winSize = localWinSize;

      var _dec$2a, _dec2$1H, _dec3$1b, _class$29;
      var RenderRoot2D = exports('R', (_dec$2a = ccclass$n('cc.RenderRoot2D'), _dec2$1H = executionOrder$1(100), _dec3$1b = requireComponent(UITransform), _dec$2a(_class$29 = _dec2$1H(_class$29 = _dec3$1b(_class$29 = disallowMultiple$1(_class$29 = function (_Component) {
        _inheritsLoose(RenderRoot2D, _Component);
        function RenderRoot2D() {
          return _Component.apply(this, arguments) || this;
        }
        var _proto = RenderRoot2D.prototype;
        _proto.onEnable = function onEnable() {
          legacyCC.director.root.batcher2D.addScreen(this);
        };
        _proto.onDisable = function onDisable() {
          legacyCC.director.root.batcher2D.removeScreen(this);
        };
        _proto.onDestroy = function onDestroy() {
          legacyCC.director.root.batcher2D.removeScreen(this);
        };
        return RenderRoot2D;
      }(Component)) || _class$29) || _class$29) || _class$29) || _class$29));

      var _dec$29, _dec2$1G, _dec3$1a, _dec4$S, _class$28, _class2$1W, _initializer$1M, _initializer2$1p;
      var _worldPos = new Vec3();
      var RenderMode = Enum({
        OVERLAY: 0,
        INTERSPERSE: 1
      });
      var Canvas = exports('C', (_dec$29 = ccclass$n('cc.Canvas'), _dec2$1G = executionOrder$1(100), _dec3$1a = type$7(Camera), _dec4$S = type$7(Camera), _dec$29(_class$28 = _dec2$1G(_class$28 = disallowMultiple$1(_class$28 = (_class2$1W = function (_RenderRoot2D) {
        _inheritsLoose(Canvas, _RenderRoot2D);
        function Canvas() {
          var _this;
          _this = _RenderRoot2D.call(this) || this;
          _this._cameraComponent = _initializer$1M && _initializer$1M();
          _this._alignCanvasWithScreen = _initializer2$1p && _initializer2$1p();
          _this._thisOnCameraResized = void 0;
          _this.fitDesignResolution_EDITOR = void 0;
          _this._pos = new Vec3();
          _this._renderMode = RenderMode.OVERLAY;
          _this._thisOnCameraResized = _this._onResizeCamera.bind(_assertThisInitialized(_this));
          return _this;
        }
        var _proto = Canvas.prototype;
        _proto.__preload = function __preload() {
          var widget = this.getComponent('cc.Widget');
          if (widget) {
            widget.updateAlignment();
          }
          {
            if (this._cameraComponent) {
              this._cameraComponent._createCamera();
              this._cameraComponent.node.on(Camera.TARGET_TEXTURE_CHANGE, this._thisOnCameraResized);
            }
          }
          this._onResizeCamera();
          {
            this.node.on(NodeEventType.TRANSFORM_CHANGED, this._thisOnCameraResized);
          }
        };
        _proto.onEnable = function onEnable() {
          _RenderRoot2D.prototype.onEnable.call(this);
          if (this._cameraComponent) {
            this._cameraComponent.node.on(Camera.TARGET_TEXTURE_CHANGE, this._thisOnCameraResized);
          }
        };
        _proto.onDisable = function onDisable() {
          _RenderRoot2D.prototype.onDisable.call(this);
          if (this._cameraComponent) {
            this._cameraComponent.node.off(Camera.TARGET_TEXTURE_CHANGE, this._thisOnCameraResized);
          }
        };
        _proto.onDestroy = function onDestroy() {
          _RenderRoot2D.prototype.onDestroy.call(this);
          this.node.off(NodeEventType.TRANSFORM_CHANGED, this._thisOnCameraResized);
        };
        _proto._onResizeCamera = function _onResizeCamera() {
          if (this._cameraComponent && this._alignCanvasWithScreen) {
            if (this._cameraComponent.targetTexture) {
              this._cameraComponent.orthoHeight = visibleRect.height / 2;
            } else {
              var size = screen.windowSize;
              this._cameraComponent.orthoHeight = size.height / view.getScaleY() / 2;
            }
            this.node.getWorldPosition(_worldPos);
            this._cameraComponent.node.setWorldPosition(_worldPos.x, _worldPos.y, 1000);
          }
        };
        _proto._getViewPriority = function _getViewPriority() {
          if (this._cameraComponent) {
            var _this$cameraComponent;
            var priority = (_this$cameraComponent = this.cameraComponent) === null || _this$cameraComponent === void 0 ? void 0 : _this$cameraComponent.priority;
            priority = this._renderMode === RenderMode.OVERLAY ? priority | 1 << 30 : priority & ~(1 << 30);
            return priority;
          }
          return 0;
        };
        _createClass(Canvas, [{
          key: "renderMode",
          get: function get() {
            return this._renderMode;
          },
          set: function set(val) {
            this._renderMode = val;
            if (this._cameraComponent) {
              this._cameraComponent.priority = this._getViewPriority();
            }
          }
        }, {
          key: "cameraComponent",
          get: function get() {
            return this._cameraComponent;
          },
          set: function set(value) {
            if (this._cameraComponent === value) {
              return;
            }
            this._cameraComponent = value;
            this._onResizeCamera();
          }
        }, {
          key: "alignCanvasWithScreen",
          get: function get() {
            return this._alignCanvasWithScreen;
          },
          set: function set(value) {
            this._alignCanvasWithScreen = value;
            this._onResizeCamera();
          }
        }]);
        return Canvas;
      }(RenderRoot2D), (_applyDecoratedDescriptor(_class2$1W.prototype, "cameraComponent", [_dec3$1a], Object.getOwnPropertyDescriptor(_class2$1W.prototype, "cameraComponent"), _class2$1W.prototype), _initializer$1M = applyDecoratedInitializer(_class2$1W.prototype, "_cameraComponent", [_dec4$S], function () {
        return null;
      }), _initializer2$1p = applyDecoratedInitializer(_class2$1W.prototype, "_alignCanvasWithScreen", [serializable$j], function () {
        return true;
      })), _class2$1W)) || _class$28) || _class$28) || _class$28));
      legacyCC.Canvas = Canvas;

      var _dec$28, _dec2$1F, _dec3$19, _class$27;
      var UIComponent = exports('U', (_dec$28 = ccclass$n('cc.UIComponent'), _dec2$1F = requireComponent(UITransform), _dec3$19 = executionOrder$1(110), _dec$28(_class$27 = _dec2$1F(_class$27 = _dec3$19(_class$27 = disallowMultiple$1(_class$27 = function (_Component) {
        _inheritsLoose(UIComponent, _Component);
        function UIComponent() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Component.call.apply(_Component, [this].concat(args)) || this;
          _this._lastParent = null;
          _this.stencilStage = Stage.DISABLED;
          return _this;
        }
        var _proto = UIComponent.prototype;
        _proto.__preload = function __preload() {
          this.node._uiProps.uiComp = this;
        };
        _proto.onEnable = function onEnable() {};
        _proto.onDisable = function onDisable() {};
        _proto.onDestroy = function onDestroy() {
          if (this.node._uiProps.uiComp === this) {
            this.node._uiProps.uiComp = null;
          }
        };
        _proto.postUpdateAssembler = function postUpdateAssembler(render) {};
        _proto.markForUpdateRenderData = function markForUpdateRenderData(enable) {
        };
        _proto.setNodeDirty = function setNodeDirty() {};
        _proto.setTextureDirty = function setTextureDirty() {};
        return UIComponent;
      }(Component)) || _class$27) || _class$27) || _class$27) || _class$27));

      function rayAABB2(ray, min, max) {
        var o = ray.o;
        var d = ray.d;
        var ix = 1 / d.x;
        var iy = 1 / d.y;
        var iz = 1 / d.z;
        var t1 = (min.x - o.x) * ix;
        var t2 = (max.x - o.x) * ix;
        var t3 = (min.y - o.y) * iy;
        var t4 = (max.y - o.y) * iy;
        var t5 = (min.z - o.z) * iz;
        var t6 = (max.z - o.z) * iz;
        var tmin = Math.max(Math.max(Math.min(t1, t2), Math.min(t3, t4)), Math.min(t5, t6));
        var tmax = Math.min(Math.min(Math.max(t1, t2), Math.max(t3, t4)), Math.max(t5, t6));
        if (tmax < 0 || tmin > tmax) {
          return 0;
        }
        return tmin > 0 ? tmin : tmax;
      }
      var raySubMesh = function () {
        var tri = Triangle.create();
        var deOpt = {
          distance: Infinity,
          doubleSided: false,
          mode: ERaycastMode.ANY
        };
        var minDis = 0;
        var fillResult = function fillResult(m, d, i0, i1, i2, r) {
          if (m === ERaycastMode.CLOSEST) {
            if (minDis > d || minDis === 0) {
              minDis = d;
              if (r) {
                if (r.length === 0) {
                  r.push({
                    distance: d,
                    vertexIndex0: i0 / 3,
                    vertexIndex1: i1 / 3,
                    vertexIndex2: i2 / 3
                  });
                } else {
                  r[0].distance = d;
                  r[0].vertexIndex0 = i0 / 3;
                  r[0].vertexIndex1 = i1 / 3;
                  r[0].vertexIndex2 = i2 / 3;
                }
              }
            }
          } else {
            minDis = d;
            if (r) r.push({
              distance: d,
              vertexIndex0: i0 / 3,
              vertexIndex1: i1 / 3,
              vertexIndex2: i2 / 3
            });
          }
        };
        var narrowphase = function narrowphase(vb, ib, pm, ray, opt) {
          if (pm === PrimitiveMode.TRIANGLE_LIST) {
            var cnt = ib.length;
            for (var j = 0; j < cnt; j += 3) {
              var i0 = ib[j] * 3;
              var i1 = ib[j + 1] * 3;
              var i2 = ib[j + 2] * 3;
              Vec3.set(tri.a, vb[i0], vb[i0 + 1], vb[i0 + 2]);
              Vec3.set(tri.b, vb[i1], vb[i1 + 1], vb[i1 + 2]);
              Vec3.set(tri.c, vb[i2], vb[i2 + 1], vb[i2 + 2]);
              var dist = intersect.rayTriangle(ray, tri, opt.doubleSided);
              if (dist === 0 || dist > opt.distance) continue;
              fillResult(opt.mode, dist, i0, i1, i2, opt.result);
              if (opt.mode === ERaycastMode.ANY) return dist;
            }
          } else if (pm === PrimitiveMode.TRIANGLE_STRIP) {
            var _cnt = ib.length - 2;
            var rev = 0;
            for (var _j = 0; _j < _cnt; _j += 1) {
              var _i = ib[_j - rev] * 3;
              var _i2 = ib[_j + rev + 1] * 3;
              var _i3 = ib[_j + 2] * 3;
              Vec3.set(tri.a, vb[_i], vb[_i + 1], vb[_i + 2]);
              Vec3.set(tri.b, vb[_i2], vb[_i2 + 1], vb[_i2 + 2]);
              Vec3.set(tri.c, vb[_i3], vb[_i3 + 1], vb[_i3 + 2]);
              rev = ~rev;
              var _dist = intersect.rayTriangle(ray, tri, opt.doubleSided);
              if (_dist === 0 || _dist > opt.distance) continue;
              fillResult(opt.mode, _dist, _i, _i2, _i3, opt.result);
              if (opt.mode === ERaycastMode.ANY) return _dist;
            }
          } else if (pm === PrimitiveMode.TRIANGLE_FAN) {
            var _cnt2 = ib.length - 1;
            var _i4 = ib[0] * 3;
            Vec3.set(tri.a, vb[_i4], vb[_i4 + 1], vb[_i4 + 2]);
            for (var _j2 = 1; _j2 < _cnt2; _j2 += 1) {
              var _i5 = ib[_j2] * 3;
              var _i6 = ib[_j2 + 1] * 3;
              Vec3.set(tri.b, vb[_i5], vb[_i5 + 1], vb[_i5 + 2]);
              Vec3.set(tri.c, vb[_i6], vb[_i6 + 1], vb[_i6 + 2]);
              var _dist2 = intersect.rayTriangle(ray, tri, opt.doubleSided);
              if (_dist2 === 0 || _dist2 > opt.distance) continue;
              fillResult(opt.mode, _dist2, _i4, _i5, _i6, opt.result);
              if (opt.mode === ERaycastMode.ANY) return _dist2;
            }
          }
          return minDis;
        };
        return function (ray, submesh, options) {
          minDis = 0;
          if (submesh.geometricInfo.positions.length === 0) return minDis;
          var opt = options === undefined ? deOpt : options;
          var min = submesh.geometricInfo.boundingBox.min;
          var max = submesh.geometricInfo.boundingBox.max;
          if (rayAABB2(ray, min, max)) {
            var pm = submesh.primitiveMode;
            var _submesh$geometricInf = submesh.geometricInfo,
              vb = _submesh$geometricInf.positions,
              ib = _submesh$geometricInf.indices;
            narrowphase(vb, ib, pm, ray, opt);
          }
          return minDis;
        };
      }();
      var rayMesh = function () {
        var minDis = 0;
        var deOpt = {
          distance: Infinity,
          doubleSided: false,
          mode: ERaycastMode.ANY
        };
        return function (ray, mesh, options) {
          minDis = 0;
          var opt = options === undefined ? deOpt : options;
          var length = mesh.renderingSubMeshes.length;
          var min = mesh.struct.minPosition;
          var max = mesh.struct.maxPosition;
          if (min && max && !rayAABB2(ray, min, max)) return minDis;
          for (var i = 0; i < length; i++) {
            var sm = mesh.renderingSubMeshes[i];
            var dis = raySubMesh(ray, sm, opt);
            if (dis) {
              if (opt.mode === ERaycastMode.CLOSEST) {
                if (minDis === 0 || minDis > dis) {
                  minDis = dis;
                  if (opt.subIndices) opt.subIndices[0] = i;
                }
              } else {
                minDis = dis;
                if (opt.subIndices) opt.subIndices.push(i);
                if (opt.mode === ERaycastMode.ANY) {
                  return dis;
                }
              }
            }
          }
          if (minDis && opt.mode === ERaycastMode.CLOSEST) {
            if (opt.result) {
              opt.result[0].distance = minDis;
              opt.result.length = 1;
            }
            if (opt.subIndices) opt.subIndices.length = 1;
          }
          return minDis;
        };
      }();
      var rayModel = function () {
        var minDis = 0;
        var deOpt = {
          distance: Infinity,
          doubleSided: false,
          mode: ERaycastMode.ANY
        };
        var modelRay = new Ray();
        var m4 = new Mat4();
        return function (r, model, options) {
          minDis = 0;
          var opt = options === undefined ? deOpt : options;
          var wb = model.worldBounds;
          if (wb && !intersect.rayAABB(r, wb)) return minDis;
          Ray.copy(modelRay, r);
          if (model.node) {
            Mat4.invert(m4, model.node.getWorldMatrix(m4));
            Vec3.transformMat4(modelRay.o, r.o, m4);
            Vec3.transformMat4Normal(modelRay.d, r.d, m4);
          }
          var subModels = model.subModels;
          for (var i = 0; i < subModels.length; i++) {
            var subMesh = subModels[i].subMesh;
            var dis = raySubMesh(modelRay, subMesh, opt);
            if (dis) {
              if (opt.mode === ERaycastMode.CLOSEST) {
                if (minDis === 0 || minDis > dis) {
                  minDis = dis;
                  if (opt.subIndices) opt.subIndices[0] = i;
                }
              } else {
                minDis = dis;
                if (opt.subIndices) opt.subIndices.push(i);
                if (opt.mode === ERaycastMode.ANY) {
                  return dis;
                }
              }
            }
          }
          if (minDis && opt.mode === ERaycastMode.CLOSEST) {
            if (opt.result) {
              opt.result[0].distance = minDis;
              opt.result.length = 1;
            }
            if (opt.subIndices) opt.subIndices.length = 1;
          }
          return minDis;
        };
      }();
      intersect.rayModel = rayModel;
      intersect.raySubMesh = raySubMesh;
      intersect.rayMesh = rayMesh;

      var _dec$27, _class$26, _class2$1V, _initializer$1L;
      getPhaseID('specular-pass');
      var ModelRenderer = exports('dT', (_dec$27 = ccclass$n('cc.ModelRenderer'), _dec$27(_class$26 = (_class2$1V = function (_Renderer) {
        _inheritsLoose(ModelRenderer, _Renderer);
        function ModelRenderer() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Renderer.call.apply(_Renderer, [this].concat(args)) || this;
          _this._visFlags = _initializer$1L && _initializer$1L();
          _this._models = [];
          _this._priority = 0;
          return _this;
        }
        var _proto = ModelRenderer.prototype;
        _proto._collectModels = function _collectModels() {
          return this._models;
        };
        _proto.onEnable = function onEnable() {
          this._updatePriority();
        };
        _proto._attachToScene = function _attachToScene() {};
        _proto._detachFromScene = function _detachFromScene() {};
        _proto._onVisibilityChange = function _onVisibilityChange(val) {};
        _proto._updatePriority = function _updatePriority() {
          if (this._models.length > 0) {
            for (var i = 0; i < this._models.length; i++) {
              this._models[i].priority = this._priority;
            }
          }
        };
        _createClass(ModelRenderer, [{
          key: "visibility",
          get: function get() {
            return this._visFlags;
          },
          set: function set(val) {
            this._visFlags = val;
            this._onVisibilityChange(val);
          }
        }, {
          key: "priority",
          get: function get() {
            return this._priority;
          },
          set: function set(val) {
            if (val === this._priority) return;
            this._priority = val;
            this._updatePriority();
          }
        }]);
        return ModelRenderer;
      }(Renderer), (_initializer$1L = applyDecoratedInitializer(_class2$1V.prototype, "_visFlags", [serializable$j], function () {
        return Layers.Enum.NONE;
      })), _class2$1V)) || _class$26));

      var _dec$26, _dec2$1E, _class$25, _class2$1U, _initializer$1K;
      var ccclass$k = ccclass$n,
        serializable$h = serializable$j,
        type$5 = type$7;
      var PrefabLink = exports('dW', (_dec$26 = ccclass$k('cc.PrefabLink'), _dec2$1E = type$5(Prefab), _dec$26(_class$25 = (_class2$1U = function (_Component) {
        _inheritsLoose(PrefabLink, _Component);
        function PrefabLink() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Component.call.apply(_Component, [this].concat(args)) || this;
          _this.prefab = _initializer$1K && _initializer$1K();
          return _this;
        }
        return PrefabLink;
      }(Component), (_initializer$1K = applyDecoratedInitializer(_class2$1U.prototype, "prefab", [_dec2$1E, serializable$h], function () {
        return null;
      })), _class2$1U)) || _class$25));

      var _dec$25, _dec2$1D, _dec3$18, _class$24, _class2$1T, _initializer$1J, _initializer2$1o, _initializer3$W, _initializer4$J, _initializer5$x, _initializer6$p;
      var SpriteMode;
      (function (SpriteMode) {
        SpriteMode[SpriteMode["SIMPLE"] = 0] = "SIMPLE";
        SpriteMode[SpriteMode["SLICED"] = 1] = "SLICED";
        SpriteMode[SpriteMode["TILED"] = 2] = "TILED";
      })(SpriteMode || (SpriteMode = {}));
      var SpriteRenderer = exports('f', (_dec$25 = ccclass$n('cc.SpriteRenderer'), _dec2$1D = executionOrder$1(100), _dec3$18 = type$7(SpriteFrame), _dec$25(_class$24 = _dec2$1D(_class$24 = (_class2$1T = function (_ModelRenderer) {
        _inheritsLoose(SpriteRenderer, _ModelRenderer);
        function SpriteRenderer() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _ModelRenderer.call.apply(_ModelRenderer, [this].concat(args)) || this;
          _this._spriteFrame = _initializer$1J && _initializer$1J();
          _this._mode = _initializer2$1o && _initializer2$1o();
          _this._color = _initializer3$W && _initializer3$W();
          _this._flipX = _initializer4$J && _initializer4$J();
          _this._flipY = _initializer5$x && _initializer5$x();
          _this._size = _initializer6$p && _initializer6$p();
          _this._model = null;
          return _this;
        }
        var _proto = SpriteRenderer.prototype;
        _proto.onLoad = function onLoad() {
          if (this._spriteFrame) {
            if (!this._spriteFrame.mesh) {
              this._spriteFrame.ensureMeshData();
            }
            this._spriteFrame.mesh.initialize();
          }
          this._updateModels();
        };
        _proto.onRestore = function onRestore() {
          this._updateModels();
          if (this.enabledInHierarchy) {
            this._attachToScene();
          }
        };
        _proto.onEnable = function onEnable() {
          _ModelRenderer.prototype.onEnable.call(this);
          if (!this._model) {
            this._updateModels();
          }
          this._attachToScene();
        };
        _proto.onDisable = function onDisable() {
          if (this._model) {
            this._detachFromScene();
          }
        };
        _proto.onDestroy = function onDestroy() {
          if (this._model) {
            legacyCC.director.root.destroyModel(this._model);
            this._model = null;
            this._models.length = 0;
          }
        };
        _proto._updateModels = function _updateModels() {
          if (!this._spriteFrame) {
            return;
          }
          var model = this._model;
          if (model) {
            model.destroy();
            model.initialize();
            model.node = model.transform = this.node;
          } else {
            this._createModel();
          }
          if (this._model) {
            var mesh = this._spriteFrame.mesh;
            this._model.createBoundingShape(mesh.struct.minPosition, mesh.struct.maxPosition);
            this._updateModelParams();
            this._onUpdateLocalDescriptorSet();
          }
        };
        _proto._createModel = function _createModel() {
          var model = this._model = legacyCC.director.root.createModel(Model);
          model.visFlags = this.visibility;
          model.node = model.transform = this.node;
          this._models.length = 0;
          this._models.push(this._model);
        };
        _proto._updateModelParams = function _updateModelParams() {
          if (!this._spriteFrame || !this._model) {
            return;
          }
          this._spriteFrame.ensureMeshData();
          var mesh = this._spriteFrame.mesh;
          this.node.hasChangedFlags |= TransformBit.POSITION;
          this._model.transform.hasChangedFlags |= TransformBit.POSITION;
          var meshCount = mesh ? mesh.renderingSubMeshes.length : 0;
          var renderingMesh = mesh.renderingSubMeshes;
          if (renderingMesh) {
            for (var i = 0; i < meshCount; ++i) {
              var material = this.getRenderMaterial(i);
              if (material && !material.isValid) {
                material = null;
              }
              var subMeshData = renderingMesh[i];
              if (subMeshData) {
                this._model.initSubModel(i, subMeshData, material || this._getBuiltinMaterial());
              }
            }
          }
          this._model.enabled = true;
        };
        _proto._getBuiltinMaterial = function _getBuiltinMaterial() {
          return builtinResMgr.get('missing-material');
        };
        _proto._onMaterialModified = function _onMaterialModified(idx, material) {
          _ModelRenderer.prototype._onMaterialModified.call(this, idx, material);
          if (!this._spriteFrame || !this._model || !this._model.inited) {
            return;
          }
          this._onRebuildPSO(idx, material || this._getBuiltinMaterial());
        };
        _proto._onRebuildPSO = function _onRebuildPSO(idx, material) {
          if (!this._model || !this._model.inited) {
            return;
          }
          this._model.setSubModelMaterial(idx, material);
          this._onUpdateLocalDescriptorSet();
        };
        _proto._onUpdateLocalDescriptorSet = function _onUpdateLocalDescriptorSet() {
          if (!this._spriteFrame || !this._model || !this._model.inited) {
            return;
          }
          var texture = this._spriteFrame.getGFXTexture();
          var sampler = this._spriteFrame.getGFXSampler();
          var subModels = this._model.subModels;
          var binding = ModelLocalBindings.SAMPLER_SPRITE;
          for (var i = 0; i < subModels.length; i++) {
            var descriptorSet = subModels[i].descriptorSet;
            descriptorSet.bindTexture(binding, texture);
            descriptorSet.bindSampler(binding, sampler);
            descriptorSet.update();
          }
        };
        _proto._attachToScene = function _attachToScene() {
          if (!this.node.scene || !this._model) {
            return;
          }
          var renderScene = this._getRenderScene();
          if (this._model.scene !== null) {
            this._detachFromScene();
          }
          renderScene.addModel(this._model);
        };
        _proto._detachFromScene = function _detachFromScene() {
          if (this._model && this._model.scene) {
            this._model.scene.removeModel(this._model);
          }
        };
        _createClass(SpriteRenderer, [{
          key: "spriteFrame",
          get: function get() {
            return this._spriteFrame;
          },
          set: function set(value) {
            if (this._spriteFrame === value) {
              return;
            }
            this._spriteFrame;
            this._spriteFrame = value;
            if (this._spriteFrame) {
              this._spriteFrame.ensureMeshData();
              var mesh = this._spriteFrame.mesh;
              mesh.initialize();
            }
            this._updateModels();
            if (this.enabledInHierarchy) {
              this._attachToScene();
            }
          }
        }, {
          key: "model",
          get: function get() {
            return this._model;
          }
        }]);
        return SpriteRenderer;
      }(ModelRenderer), (_applyDecoratedDescriptor(_class2$1T.prototype, "spriteFrame", [_dec3$18], Object.getOwnPropertyDescriptor(_class2$1T.prototype, "spriteFrame"), _class2$1T.prototype), _initializer$1J = applyDecoratedInitializer(_class2$1T.prototype, "_spriteFrame", [serializable$j], function () {
        return null;
      }), _initializer2$1o = applyDecoratedInitializer(_class2$1T.prototype, "_mode", [serializable$j], function () {
        return SpriteMode.SIMPLE;
      }), _initializer3$W = applyDecoratedInitializer(_class2$1T.prototype, "_color", [serializable$j], function () {
        return Color$1.WHITE.clone();
      }), _initializer4$J = applyDecoratedInitializer(_class2$1T.prototype, "_flipX", [serializable$j], function () {
        return false;
      }), _initializer5$x = applyDecoratedInitializer(_class2$1T.prototype, "_flipY", [serializable$j], function () {
        return false;
      }), _initializer6$p = applyDecoratedInitializer(_class2$1T.prototype, "_size", [serializable$j], function () {
        return new Vec2();
      })), _class2$1T)) || _class$24) || _class$24));

      var _dec$24, _dec2$1C, _dec3$17, _dec4$R, _dec5$J, _dec6$t, _dec7$m, _dec8$g, _class$23, _class2$1S, _initializer$1I, _initializer2$1n, _initializer3$V, _initializer4$I, _initializer5$w, _initializer6$o, _initializer7$k, _initializer8$j, _initializer9$h, _initializer10$f, _initializer11$d, _initializer12$b, _initializer13$a, _initializer14$8, _class3$s;
      var _htmlTextParser = new HtmlTextParser();
      var RichTextChildName = 'RICHTEXT_CHILD';
      var RichTextChildImageName = 'RICHTEXT_Image_CHILD';
      var _tempSize = new Vec2();
      var _tempSizeLeft = new Vec2();
      var labelPool = new Pool$1(function (seg) {
        if (!legacyCC.isValid(seg.node)) {
          return false;
        } else {
          var outline = seg.node.getComponent(LabelOutline);
          if (outline) {
            outline.width = 0;
          }
        }
        return true;
      }, 20);
      var imagePool = new Pool$1(function (seg) {
        return legacyCC.isValid(seg.node);
      }, 10);
      function createSegment(type) {
        return {
          node: new Node$1(type),
          comp: null,
          lineCount: 0,
          styleIndex: 0,
          imageOffset: '',
          clickParam: '',
          clickHandler: '',
          type: type
        };
      }
      function getSegmentByPool(type, content) {
        var seg;
        if (type === RichTextChildName) {
          seg = labelPool._get();
        } else if (type === RichTextChildImageName) {
          seg = imagePool._get();
        }
        seg = seg || createSegment(type);
        var node = seg.node;
        if (!node) {
          node = new Node$1(type);
        }
        node.hideFlags |= CCObject.Flags.DontSave | CCObject.Flags.HideInHierarchy;
        node.active = true;
        if (type === RichTextChildImageName) {
          seg.comp = node.getComponent(Sprite) || node.addComponent(Sprite);
          seg.comp.spriteFrame = content;
          seg.comp.type = Sprite.Type.SLICED;
          seg.comp.sizeMode = Sprite.SizeMode.CUSTOM;
        } else {
          seg.comp = node.getComponent(Label) || node.addComponent(Label);
          seg.comp.string = content;
          seg.comp.horizontalAlign = HorizontalTextAlignment.LEFT;
          seg.comp.verticalAlign = VerticalTextAlignment.TOP;
          seg.comp.underlineHeight = 2;
        }
        node.setPosition(0, 0, 0);
        var trans = node._uiProps.uiTransformComp;
        trans.setAnchorPoint(0.5, 0.5);
        seg.node = node;
        seg.lineCount = 0;
        seg.styleIndex = 0;
        seg.imageOffset = '';
        seg.clickParam = '';
        seg.clickHandler = '';
        return seg;
      }
      var RichText = exports('i', (_dec$24 = ccclass$n('cc.RichText'), _dec2$1C = executionOrder$1(110), _dec3$17 = type$7(HorizontalTextAlignment), _dec4$R = type$7(VerticalTextAlignment), _dec5$J = type$7(Color$1), _dec6$t = type$7(Font), _dec7$m = type$7(CacheMode), _dec8$g = type$7(SpriteAtlas), _dec$24(_class$23 = _dec2$1C(_class$23 = (_class2$1S = (_class3$s = function (_Component) {
        _inheritsLoose(RichText, _Component);
        function RichText() {
          var _this;
          _this = _Component.call(this) || this;
          _this._lineHeight = _initializer$1I && _initializer$1I();
          _this._string = _initializer2$1n && _initializer2$1n();
          _this._horizontalAlign = _initializer3$V && _initializer3$V();
          _this._verticalAlign = _initializer4$I && _initializer4$I();
          _this._fontSize = _initializer5$w && _initializer5$w();
          _this._fontColor = _initializer6$o && _initializer6$o();
          _this._maxWidth = _initializer7$k && _initializer7$k();
          _this._fontFamily = _initializer8$j && _initializer8$j();
          _this._font = _initializer9$h && _initializer9$h();
          _this._isSystemFontUsed = _initializer10$f && _initializer10$f();
          _this._userDefinedFont = _initializer11$d && _initializer11$d();
          _this._cacheMode = _initializer12$b && _initializer12$b();
          _this._imageAtlas = _initializer13$a && _initializer13$a();
          _this._handleTouchEvent = _initializer14$8 && _initializer14$8();
          _this._textArray = [];
          _this._segments = [];
          _this._labelSegmentsCache = [];
          _this._linesWidth = [];
          _this._lineCount = 1;
          _this._labelWidth = 0;
          _this._labelHeight = 0;
          _this._layoutDirty = true;
          _this._lineOffsetX = 0;
          _this._updateRichTextStatus = void 0;
          _this._labelChildrenNum = 0;
          _this._updateRichTextStatus = _this._updateRichText;
          return _this;
        }
        var _proto = RichText.prototype;
        _proto.onLoad = function onLoad() {
          this.node.on(NodeEventType.LAYER_CHANGED, this._applyLayer, this);
          this.node.on(NodeEventType.ANCHOR_CHANGED, this._updateRichTextPosition, this);
        };
        _proto.onEnable = function onEnable() {
          if (this.handleTouchEvent) {
            this._addEventListeners();
          }
          this._updateRichText();
          this._activateChildren(true);
        };
        _proto.onDisable = function onDisable() {
          if (this.handleTouchEvent) {
            this._removeEventListeners();
          }
          this._activateChildren(false);
        };
        _proto.onRestore = function onRestore() {
          {
            return;
          }
        };
        _proto.onDestroy = function onDestroy() {
          for (var _iterator = _createForOfIteratorHelperLoose(this._segments), _step; !(_step = _iterator()).done;) {
            var seg = _step.value;
            seg.node.removeFromParent();
            if (seg.type === RichTextChildName) {
              labelPool.put(seg);
            } else if (seg.type === RichTextChildImageName) {
              imagePool.put(seg);
            }
          }
          this.node.off(NodeEventType.ANCHOR_CHANGED, this._updateRichTextPosition, this);
          this.node.off(NodeEventType.LAYER_CHANGED, this._applyLayer, this);
        };
        _proto._addEventListeners = function _addEventListeners() {
          this.node.on(NodeEventType.TOUCH_END, this._onTouchEnded, this);
        };
        _proto._removeEventListeners = function _removeEventListeners() {
          this.node.off(NodeEventType.TOUCH_END, this._onTouchEnded, this);
        };
        _proto._updateLabelSegmentTextAttributes = function _updateLabelSegmentTextAttributes() {
          var _this2 = this;
          this._segments.forEach(function (item) {
            _this2._applyTextAttribute(item);
          });
        };
        _proto._createFontLabel = function _createFontLabel(str) {
          return getSegmentByPool(RichTextChildName, str);
        };
        _proto._createImage = function _createImage(spriteFrame) {
          return getSegmentByPool(RichTextChildImageName, spriteFrame);
        };
        _proto._onTTFLoaded = function _onTTFLoaded() {
          if (this._font instanceof TTFFont) {
            this._layoutDirty = true;
            this._updateRichText();
          } else {
            this._layoutDirty = true;
            this._updateRichText();
          }
        };
        _proto.splitLongStringApproximatelyIn2048 = function splitLongStringApproximatelyIn2048(text, styleIndex) {
          var approxSize = text.length * this.fontSize;
          var partStringArr = [];
          if (approxSize <= 2048 * 0.8) {
            partStringArr.push(text);
            return partStringArr;
          }
          this._calculateSize(_tempSize, styleIndex, text);
          if (_tempSize.x < 2048) {
            partStringArr.push(text);
          } else {
            var multilineTexts = text.split('\n');
            for (var i = 0; i < multilineTexts.length; i++) {
              this._calculateSize(_tempSize, styleIndex, multilineTexts[i]);
              if (_tempSize.x < 2048) {
                partStringArr.push(multilineTexts[i]);
              } else {
                var thisPartSplitResultArr = this.splitLongStringOver2048(multilineTexts[i], styleIndex);
                partStringArr.push.apply(partStringArr, thisPartSplitResultArr);
              }
            }
          }
          return partStringArr;
        };
        _proto.splitLongStringOver2048 = function splitLongStringOver2048(text, styleIndex) {
          var partStringArr = [];
          var longStr = text;
          var curStart = 0;
          var curEnd = longStr.length / 2;
          var curString = longStr.substring(curStart, curEnd);
          var leftString = longStr.substring(curEnd);
          var curStringSize = this._calculateSize(_tempSize, styleIndex, curString);
          var leftStringSize = this._calculateSize(_tempSizeLeft, styleIndex, leftString);
          var maxWidth = this._maxWidth;
          if (this._maxWidth === 0) {
            maxWidth = 2047.9;
          }
          var lineCountForOnePart = 1;
          var sizeForOnePart = lineCountForOnePart * maxWidth;
          while (curStringSize.x > sizeForOnePart) {
            curEnd /= 2;
            if (curEnd < 1) {
              curEnd *= 2;
              break;
            }
            curString = curString.substring(curStart, curEnd);
            leftString = longStr.substring(curEnd);
            this._calculateSize(curStringSize, styleIndex, curString);
          }
          var leftTryTimes = 1000;
          var curWordStep = 1;
          while (leftTryTimes && curStart < text.length) {
            while (leftTryTimes && curStringSize.x < sizeForOnePart) {
              var nextPartExec = getEnglishWordPartAtFirst(leftString);
              if (nextPartExec && nextPartExec.length > 0) {
                curWordStep = nextPartExec[0].length;
              }
              curEnd += curWordStep;
              curString = longStr.substring(curStart, curEnd);
              leftString = longStr.substring(curEnd);
              this._calculateSize(curStringSize, styleIndex, curString);
              leftTryTimes--;
            }
            while (leftTryTimes && curString.length >= 2 && curStringSize.x > sizeForOnePart) {
              curEnd -= curWordStep;
              curString = longStr.substring(curStart, curEnd);
              this._calculateSize(curStringSize, styleIndex, curString);
              curWordStep = 1;
              leftTryTimes--;
            }
            if (curString.length >= 2) {
              var lastWordExec = getEnglishWordPartAtLast(curString);
              if (lastWordExec && lastWordExec.length > 0 && curString !== lastWordExec[0]) {
                curEnd -= lastWordExec[0].length;
                curString = longStr.substring(curStart, curEnd);
              }
            }
            partStringArr.push(curString);
            var partStep = curString.length;
            curStart = curEnd;
            curEnd += partStep;
            curString = longStr.substring(curStart, curEnd);
            leftString = longStr.substring(curEnd);
            this._calculateSize(leftStringSize, styleIndex, leftString);
            this._calculateSize(curStringSize, styleIndex, curString);
            leftTryTimes--;
            if (leftStringSize.x < 2048 && curStringSize.x < sizeForOnePart) {
              partStringArr.push(curString);
              curStart = text.length;
              curEnd = text.length;
              curString = leftString;
              if (leftString !== '') {
                partStringArr.push(curString);
              }
              break;
            }
          }
          return partStringArr;
        };
        _proto._measureText = function _measureText(styleIndex, string) {
          var _this3 = this;
          var func = function func(s) {
            var width = _this3._calculateSize(_tempSize, styleIndex, s).x;
            return width;
          };
          if (string) {
            return func(string);
          } else {
            return func;
          }
        };
        _proto._calculateSize = function _calculateSize(out, styleIndex, s) {
          var label;
          if (this._labelSegmentsCache.length === 0) {
            label = this._createFontLabel(s);
            this._labelSegmentsCache.push(label);
          } else {
            label = this._labelSegmentsCache[0];
            label.node.getComponent(Label).string = s;
          }
          label.styleIndex = styleIndex;
          this._applyTextAttribute(label);
          var size = label.node._uiProps.uiTransformComp.contentSize;
          Vec2.set(out, size.x, size.y);
          return out;
        };
        _proto._onTouchEnded = function _onTouchEnded(event) {
          var _this4 = this;
          var components = this.node.getComponents(Component);
          var _loop = function _loop() {
            var seg = _step2.value;
            var clickHandler = seg.clickHandler;
            var clickParam = seg.clickParam;
            if (clickHandler && _this4._containsTouchLocation(seg, event.touch.getUILocation())) {
              components.forEach(function (component) {
                var func = component[clickHandler];
                if (component.enabledInHierarchy && func) {
                  func.call(component, event, clickParam);
                }
              });
              event.propagationStopped = true;
            }
          };
          for (var _iterator2 = _createForOfIteratorHelperLoose(this._segments), _step2; !(_step2 = _iterator2()).done;) {
            _loop();
          }
        };
        _proto._containsTouchLocation = function _containsTouchLocation(label, point) {
          var comp = label.node.getComponent(UITransform);
          if (!comp) {
            return false;
          }
          var myRect = comp.getBoundingBoxToWorld();
          return myRect.contains(point);
        };
        _proto._resetState = function _resetState() {
          var children = this.node.children;
          for (var i = children.length - 1; i >= 0; i--) {
            var child = children[i];
            if (child.name === RichTextChildName || child.name === RichTextChildImageName) {
              {
                assert(child.parent === this.node);
              }
              child.parent = null;
              var segment = createSegment(child.name);
              segment.node = child;
              if (child.name === RichTextChildName) {
                segment.comp = child.getComponent(Label);
                labelPool.put(segment);
              } else {
                segment.comp = child.getComponent(Sprite);
                imagePool.put(segment);
              }
              this._labelChildrenNum--;
            }
          }
          this._segments.length = 0;
          this._labelSegmentsCache.length = 0;
          this._linesWidth.length = 0;
          this._lineOffsetX = 0;
          this._lineCount = 1;
          this._labelWidth = 0;
          this._labelHeight = 0;
          this._layoutDirty = true;
        };
        _proto._activateChildren = function _activateChildren(active) {
          for (var i = this.node.children.length - 1; i >= 0; i--) {
            var child = this.node.children[i];
            if (child.name === RichTextChildName || child.name === RichTextChildImageName) {
              child.active = active;
            }
          }
        };
        _proto._addLabelSegment = function _addLabelSegment(stringToken, styleIndex) {
          var labelSegment;
          if (this._labelSegmentsCache.length === 0) {
            labelSegment = this._createFontLabel(stringToken);
          } else {
            labelSegment = this._labelSegmentsCache.pop();
            var label = labelSegment.node.getComponent(Label);
            if (label) {
              label.string = stringToken;
            }
          }
          var labelComp = labelSegment.comp;
          if (labelComp.verticalAlign !== this._verticalAlign) {
            labelComp.verticalAlign = this._verticalAlign;
          }
          labelSegment.styleIndex = styleIndex;
          labelSegment.lineCount = this._lineCount;
          labelSegment.node._uiProps.uiTransformComp.setAnchorPoint(0, 0);
          labelSegment.node.layer = this.node.layer;
          this.node.insertChild(labelSegment.node, this._labelChildrenNum++);
          this._applyTextAttribute(labelSegment);
          this._segments.push(labelSegment);
          return labelSegment;
        };
        _proto._updateRichTextWithMaxWidth = function _updateRichTextWithMaxWidth(labelString, labelWidth, styleIndex) {
          var fragmentWidth = labelWidth;
          var labelSegment;
          if (this._lineOffsetX > 0 && fragmentWidth + this._lineOffsetX > this._maxWidth) {
            var checkStartIndex = 0;
            while (this._lineOffsetX <= this._maxWidth) {
              var checkEndIndex = this._getFirstWordLen(labelString, checkStartIndex, labelString.length);
              var checkString = labelString.substr(checkStartIndex, checkEndIndex);
              var checkStringWidth = this._measureText(styleIndex, checkString);
              if (this._lineOffsetX + checkStringWidth <= this._maxWidth) {
                this._lineOffsetX += checkStringWidth;
                checkStartIndex += checkEndIndex;
              } else {
                if (checkStartIndex > 0) {
                  var remainingString = labelString.substr(0, checkStartIndex);
                  this._addLabelSegment(remainingString, styleIndex);
                  labelString = labelString.substr(checkStartIndex, labelString.length);
                  fragmentWidth = this._measureText(styleIndex, labelString);
                }
                this._updateLineInfo();
                break;
              }
            }
          }
          if (fragmentWidth > this._maxWidth) {
            var fragments = fragmentText(labelString, fragmentWidth, this._maxWidth, this._measureText(styleIndex));
            for (var k = 0; k < fragments.length; ++k) {
              var splitString = fragments[k];
              labelSegment = this._addLabelSegment(splitString, styleIndex);
              var labelSize = labelSegment.node._uiProps.uiTransformComp.contentSize;
              this._lineOffsetX += labelSize.width;
              if (fragments.length > 1 && k < fragments.length - 1) {
                this._updateLineInfo();
              }
            }
          } else {
            this._lineOffsetX += fragmentWidth;
            this._addLabelSegment(labelString, styleIndex);
          }
        };
        _proto._isLastComponentCR = function _isLastComponentCR(stringToken) {
          return stringToken.length - 1 === stringToken.lastIndexOf('\n');
        };
        _proto._updateLineInfo = function _updateLineInfo() {
          this._linesWidth.push(this._lineOffsetX);
          this._lineOffsetX = 0;
          this._lineCount++;
        };
        _proto._needsUpdateTextLayout = function _needsUpdateTextLayout(newTextArray) {
          if (this._layoutDirty || !this._textArray || !newTextArray) {
            return true;
          }
          if (this._textArray.length !== newTextArray.length) {
            return true;
          }
          for (var i = 0; i < this._textArray.length; i++) {
            var oldItem = this._textArray[i];
            var newItem = newTextArray[i];
            if (oldItem.text !== newItem.text) {
              return true;
            } else {
              var oldStyle = oldItem.style;
              var newStyle = newItem.style;
              if (oldStyle) {
                if (newStyle) {
                  if (!!newStyle.outline !== !!oldStyle.outline) {
                    return true;
                  }
                  if (oldStyle.size !== newStyle.size || oldStyle.italic !== newStyle.italic || oldStyle.isImage !== newStyle.isImage) {
                    return true;
                  }
                  if (oldStyle.src !== newStyle.src || oldStyle.imageAlign !== newStyle.imageAlign || oldStyle.imageHeight !== newStyle.imageHeight || oldStyle.imageWidth !== newStyle.imageWidth || oldStyle.imageOffset !== newStyle.imageOffset) {
                    return true;
                  }
                } else if (oldStyle.size || oldStyle.italic || oldStyle.isImage || oldStyle.outline) {
                  return true;
                }
              } else if (newStyle) {
                if (newStyle.size || newStyle.italic || newStyle.isImage || newStyle.outline) {
                  return true;
                }
              }
            }
          }
          return false;
        };
        _proto._addRichTextImageElement = function _addRichTextImageElement(richTextElement) {
          if (!richTextElement.style) {
            return;
          }
          var style = richTextElement.style;
          var spriteFrameName = style.src;
          var spriteFrame = this._imageAtlas && spriteFrameName && this._imageAtlas.getSpriteFrame(spriteFrameName);
          if (!spriteFrame) {
            warnID(4400);
          } else {
            var segment = this._createImage(spriteFrame);
            segment.comp;
            switch (style.imageAlign) {
              case 'top':
                segment.node._uiProps.uiTransformComp.setAnchorPoint(0, 1);
                break;
              case 'center':
                segment.node._uiProps.uiTransformComp.setAnchorPoint(0, 0.5);
                break;
              default:
                segment.node._uiProps.uiTransformComp.setAnchorPoint(0, 0);
                break;
            }
            if (style.imageOffset) {
              segment.imageOffset = style.imageOffset;
            }
            segment.node.layer = this.node.layer;
            this.node.insertChild(segment.node, this._labelChildrenNum++);
            this._segments.push(segment);
            var spriteRect = spriteFrame.rect.clone();
            var scaleFactor = 1;
            var spriteWidth = spriteRect.width;
            var spriteHeight = spriteRect.height;
            var expectWidth = style.imageWidth || 0;
            var expectHeight = style.imageHeight || 0;
            if (expectHeight > 0) {
              scaleFactor = expectHeight / spriteHeight;
              spriteWidth *= scaleFactor;
              spriteHeight *= scaleFactor;
            } else {
              scaleFactor = this._lineHeight / spriteHeight;
              spriteWidth *= scaleFactor;
              spriteHeight *= scaleFactor;
            }
            if (expectWidth > 0) {
              spriteWidth = expectWidth;
            }
            if (this._maxWidth > 0) {
              if (this._lineOffsetX + spriteWidth > this._maxWidth) {
                this._updateLineInfo();
              }
              this._lineOffsetX += spriteWidth;
            } else {
              this._lineOffsetX += spriteWidth;
              if (this._lineOffsetX > this._labelWidth) {
                this._labelWidth = this._lineOffsetX;
              }
            }
            segment.node._uiProps.uiTransformComp.setContentSize(spriteWidth, spriteHeight);
            segment.lineCount = this._lineCount;
            segment.clickHandler = '';
            segment.clickParam = '';
            var event = style.event;
            if (event) {
              segment.clickHandler = event.click;
              segment.clickParam = event.param;
            }
          }
        };
        _proto._updateTextDefaultColor = function _updateTextDefaultColor() {
          for (var i = 0; i < this._segments.length; ++i) {
            var _this$_textArray$segm, _this$_textArray$segm2;
            var segment = this._segments[i];
            var label = segment.node.getComponent(Label);
            if (!label) {
              continue;
            }
            if ((_this$_textArray$segm = this._textArray[segment.styleIndex]) !== null && _this$_textArray$segm !== void 0 && (_this$_textArray$segm2 = _this$_textArray$segm.style) !== null && _this$_textArray$segm2 !== void 0 && _this$_textArray$segm2.color) {
              continue;
            }
            label.color = this._fontColor;
          }
        };
        _proto._updateRichText = function _updateRichText() {
          if (!this.enabledInHierarchy) {
            return;
          }
          var newTextArray = _htmlTextParser.parse(this._string);
          if (!this._needsUpdateTextLayout(newTextArray)) {
            this._textArray = newTextArray.slice();
            this._updateLabelSegmentTextAttributes();
            return;
          }
          this._textArray = newTextArray.slice();
          this._resetState();
          var lastEmptyLine = false;
          var label;
          for (var i = 0; i < this._textArray.length; ++i) {
            var richTextElement = this._textArray[i];
            var text = richTextElement.text;
            if (text === undefined) {
              continue;
            }
            if (text === '') {
              if (richTextElement.style && richTextElement.style.isNewLine) {
                this._updateLineInfo();
                continue;
              }
              if (richTextElement.style && richTextElement.style.isImage && this._imageAtlas) {
                this._addRichTextImageElement(richTextElement);
                continue;
              }
            }
            var splitArr = this.splitLongStringApproximatelyIn2048(text, i);
            text = splitArr.join('\n');
            var multilineTexts = text.split('\n');
            for (var j = 0; j < multilineTexts.length; ++j) {
              var labelString = multilineTexts[j];
              if (labelString === '') {
                if (this._isLastComponentCR(text) && j === multilineTexts.length - 1) {
                  continue;
                }
                this._updateLineInfo();
                lastEmptyLine = true;
                continue;
              }
              lastEmptyLine = false;
              if (this._maxWidth > 0) {
                var labelWidth = this._measureText(i, labelString);
                this._updateRichTextWithMaxWidth(labelString, labelWidth, i);
                if (multilineTexts.length > 1 && j < multilineTexts.length - 1) {
                  this._updateLineInfo();
                }
              } else {
                label = this._addLabelSegment(labelString, i);
                this._lineOffsetX += label.node._uiProps.uiTransformComp.width;
                if (this._lineOffsetX > this._labelWidth) {
                  this._labelWidth = this._lineOffsetX;
                }
                if (multilineTexts.length > 1 && j < multilineTexts.length - 1) {
                  this._updateLineInfo();
                }
              }
            }
          }
          if (!lastEmptyLine) {
            this._linesWidth.push(this._lineOffsetX);
          }
          if (this._maxWidth > 0) {
            this._labelWidth = this._maxWidth;
          }
          this._labelHeight = (this._lineCount + BASELINE_RATIO) * this._lineHeight;
          this.node._uiProps.uiTransformComp.setContentSize(this._labelWidth, this._labelHeight);
          this._updateRichTextPosition();
          this._layoutDirty = false;
        };
        _proto._getFirstWordLen = function _getFirstWordLen(text, startIndex, textLen) {
          var character = text.charAt(startIndex);
          if (isUnicodeCJK(character) || isUnicodeSpace(character)) {
            return 1;
          }
          var len = 1;
          for (var index = startIndex + 1; index < textLen; ++index) {
            character = text.charAt(index);
            if (isUnicodeSpace(character) || isUnicodeCJK(character)) {
              break;
            }
            len++;
          }
          return len;
        };
        _proto._updateRichTextPosition = function _updateRichTextPosition() {
          var nextTokenX = 0;
          var nextLineIndex = 1;
          var totalLineCount = this._lineCount;
          var trans = this.node._uiProps.uiTransformComp;
          var anchorX = trans.anchorX;
          var anchorY = trans.anchorY;
          for (var i = 0; i < this._segments.length; ++i) {
            var segment = this._segments[i];
            var lineCount = segment.lineCount;
            if (lineCount > nextLineIndex) {
              nextTokenX = 0;
              nextLineIndex = lineCount;
            }
            var lineOffsetX = this._labelWidth * (this._horizontalAlign * 0.5 - anchorX);
            switch (this._horizontalAlign) {
              case HorizontalTextAlignment.LEFT:
                break;
              case HorizontalTextAlignment.CENTER:
                lineOffsetX -= this._linesWidth[lineCount - 1] / 2;
                break;
              case HorizontalTextAlignment.RIGHT:
                lineOffsetX -= this._linesWidth[lineCount - 1];
                break;
            }
            var pos = segment.node.position;
            segment.node.setPosition(nextTokenX + lineOffsetX, this._lineHeight * (totalLineCount - lineCount) - this._labelHeight * anchorY, pos.z);
            if (lineCount === nextLineIndex) {
              nextTokenX += segment.node._uiProps.uiTransformComp.width;
            }
            var sprite = segment.node.getComponent(Sprite);
            if (sprite) {
              var position = segment.node.position.clone();
              var lineHeightSet = this._lineHeight;
              var lineHeightReal = this._lineHeight * (1 + BASELINE_RATIO);
              switch (segment.node._uiProps.uiTransformComp.anchorY) {
                case 1:
                  position.y += lineHeightSet + (lineHeightReal - lineHeightSet) / 2;
                  break;
                case 0.5:
                  position.y += lineHeightReal / 2;
                  break;
                default:
                  position.y += (lineHeightReal - lineHeightSet) / 2;
                  break;
              }
              if (segment.imageOffset) {
                var offsets = segment.imageOffset.split(',');
                if (offsets.length === 1 && offsets[0]) {
                  var offsetY = parseFloat(offsets[0]);
                  if (Number.isInteger(offsetY)) position.y += offsetY;
                } else if (offsets.length === 2) {
                  var offsetX = parseFloat(offsets[0]);
                  var _offsetY = parseFloat(offsets[1]);
                  if (Number.isInteger(offsetX)) position.x += offsetX;
                  if (Number.isInteger(_offsetY)) position.y += _offsetY;
                }
              }
              segment.node.position = position;
            }
            var outline = segment.node.getComponent(LabelOutline);
            if (outline) {
              var _position = segment.node.position.clone();
              _position.y -= outline.width;
              segment.node.position = _position;
            }
          }
        };
        _proto._convertLiteralColorValue = function _convertLiteralColorValue(color) {
          var colorValue = color.toUpperCase();
          if (Color$1[colorValue]) {
            var colorUse = Color$1[colorValue];
            return colorUse;
          } else {
            var out = new Color$1();
            return out.fromHEX(color);
          }
        };
        _proto._applyTextAttribute = function _applyTextAttribute(labelSeg) {
          var label = labelSeg.node.getComponent(Label);
          if (!label) {
            return;
          }
          this._resetLabelState(label);
          var index = labelSeg.styleIndex;
          var textStyle;
          if (this._textArray[index]) {
            textStyle = this._textArray[index].style;
          }
          if (textStyle) {
            if (textStyle.color) {
              label.color = this._convertLiteralColorValue(textStyle.color);
            } else {
              label.color = this._fontColor;
            }
            label.isBold = !!textStyle.bold;
            label.isItalic = !!textStyle.italic;
            label.isUnderline = !!textStyle.underline;
            if (textStyle.outline) {
              var labelOutline = labelSeg.node.getComponent(LabelOutline);
              if (!labelOutline) {
                labelOutline = labelSeg.node.addComponent(LabelOutline);
              }
              labelOutline.color = this._convertLiteralColorValue(textStyle.outline.color);
              labelOutline.width = textStyle.outline.width;
            }
            label.fontSize = textStyle.size || this._fontSize;
            labelSeg.clickHandler = '';
            labelSeg.clickParam = '';
            var event = textStyle.event;
            if (event) {
              labelSeg.clickHandler = event.click || '';
              labelSeg.clickParam = event.param || '';
            }
          }
          label.cacheMode = this._cacheMode;
          var isAsset = this._font instanceof Font;
          if (isAsset && !this._isSystemFontUsed) {
            label.font = this._font;
          } else {
            label.fontFamily = this._fontFamily;
          }
          label.useSystemFont = this._isSystemFontUsed;
          label.lineHeight = this._lineHeight;
          label.updateRenderData(true);
        };
        _proto._applyLayer = function _applyLayer() {
          for (var _iterator3 = _createForOfIteratorHelperLoose(this._segments), _step3; !(_step3 = _iterator3()).done;) {
            var seg = _step3.value;
            seg.node.layer = this.node.layer;
          }
        };
        _proto._resetLabelState = function _resetLabelState(label) {
          label.fontSize = this._fontSize;
          label.color = this._fontColor;
          label.isBold = false;
          label.isItalic = false;
          label.isUnderline = false;
        };
        _createClass(RichText, [{
          key: "string",
          get: function get() {
            return this._string;
          },
          set: function set(value) {
            if (this._string === value) {
              return;
            }
            this._string = value;
            this._updateRichTextStatus();
          }
        }, {
          key: "horizontalAlign",
          get: function get() {
            return this._horizontalAlign;
          },
          set: function set(value) {
            if (this.horizontalAlign === value) {
              return;
            }
            this._horizontalAlign = value;
            this._layoutDirty = true;
            this._updateRichTextStatus();
          }
        }, {
          key: "verticalAlign",
          get: function get() {
            return this._verticalAlign;
          },
          set: function set(value) {
            if (this._verticalAlign === value) {
              return;
            }
            this._verticalAlign = value;
            this._layoutDirty = true;
            this._updateRichTextStatus();
          }
        }, {
          key: "fontSize",
          get: function get() {
            return this._fontSize;
          },
          set: function set(value) {
            if (this._fontSize === value) {
              return;
            }
            this._fontSize = value;
            this._layoutDirty = true;
            this._updateRichTextStatus();
          }
        }, {
          key: "fontColor",
          get: function get() {
            return this._fontColor;
          },
          set: function set(value) {
            if (this._fontColor === value) {
              return;
            }
            this._fontColor = value;
            this._updateTextDefaultColor();
          }
        }, {
          key: "fontFamily",
          get: function get() {
            return this._fontFamily;
          },
          set: function set(value) {
            if (this._fontFamily === value) return;
            this._fontFamily = value;
            this._layoutDirty = true;
            this._updateRichTextStatus();
          }
        }, {
          key: "font",
          get: function get() {
            return this._font;
          },
          set: function set(value) {
            if (this._font === value) {
              return;
            }
            this._font = value;
            this._layoutDirty = true;
            if (this._font) {
              this.useSystemFont = false;
              this._onTTFLoaded();
            } else {
              this.useSystemFont = true;
            }
            this._updateRichTextStatus();
          }
        }, {
          key: "useSystemFont",
          get: function get() {
            return this._isSystemFontUsed;
          },
          set: function set(value) {
            if (this._isSystemFontUsed === value) {
              return;
            }
            this._isSystemFontUsed = value;
            this._layoutDirty = true;
            this._updateRichTextStatus();
          }
        }, {
          key: "cacheMode",
          get: function get() {
            return this._cacheMode;
          },
          set: function set(value) {
            if (this._cacheMode === value) {
              return;
            }
            this._cacheMode = value;
            this._updateRichTextStatus();
          }
        }, {
          key: "maxWidth",
          get: function get() {
            return this._maxWidth;
          },
          set: function set(value) {
            if (this._maxWidth === value) {
              return;
            }
            this._maxWidth = value;
            this._layoutDirty = true;
            this._updateRichTextStatus();
          }
        }, {
          key: "lineHeight",
          get: function get() {
            return this._lineHeight;
          },
          set: function set(value) {
            if (this._lineHeight === value) {
              return;
            }
            this._lineHeight = value;
            this._layoutDirty = true;
            this._updateRichTextStatus();
          }
        }, {
          key: "imageAtlas",
          get: function get() {
            return this._imageAtlas;
          },
          set: function set(value) {
            if (this._imageAtlas === value) {
              return;
            }
            this._imageAtlas = value;
            this._layoutDirty = true;
            this._updateRichTextStatus();
          }
        }, {
          key: "handleTouchEvent",
          get: function get() {
            return this._handleTouchEvent;
          },
          set: function set(value) {
            if (this._handleTouchEvent === value) {
              return;
            }
            this._handleTouchEvent = value;
            if (this.enabledInHierarchy) {
              if (this.handleTouchEvent) {
                this._addEventListeners();
              } else {
                this._removeEventListeners();
              }
            }
          }
        }]);
        return RichText;
      }(Component), _class3$s.HorizontalAlign = HorizontalTextAlignment, _class3$s.VerticalAlign = VerticalTextAlignment, _class3$s), (_applyDecoratedDescriptor(_class2$1S.prototype, "horizontalAlign", [_dec3$17], Object.getOwnPropertyDescriptor(_class2$1S.prototype, "horizontalAlign"), _class2$1S.prototype), _applyDecoratedDescriptor(_class2$1S.prototype, "verticalAlign", [_dec4$R], Object.getOwnPropertyDescriptor(_class2$1S.prototype, "verticalAlign"), _class2$1S.prototype), _applyDecoratedDescriptor(_class2$1S.prototype, "fontColor", [_dec5$J], Object.getOwnPropertyDescriptor(_class2$1S.prototype, "fontColor"), _class2$1S.prototype), _applyDecoratedDescriptor(_class2$1S.prototype, "font", [_dec6$t], Object.getOwnPropertyDescriptor(_class2$1S.prototype, "font"), _class2$1S.prototype), _applyDecoratedDescriptor(_class2$1S.prototype, "cacheMode", [_dec7$m], Object.getOwnPropertyDescriptor(_class2$1S.prototype, "cacheMode"), _class2$1S.prototype), _applyDecoratedDescriptor(_class2$1S.prototype, "imageAtlas", [_dec8$g], Object.getOwnPropertyDescriptor(_class2$1S.prototype, "imageAtlas"), _class2$1S.prototype), _initializer$1I = applyDecoratedInitializer(_class2$1S.prototype, "_lineHeight", [serializable$j], function () {
        return 40;
      }), _initializer2$1n = applyDecoratedInitializer(_class2$1S.prototype, "_string", [serializable$j], function () {
        return '<color=#00ff00>Rich</color><color=#0fffff>Text</color>';
      }), _initializer3$V = applyDecoratedInitializer(_class2$1S.prototype, "_horizontalAlign", [serializable$j], function () {
        return HorizontalTextAlignment.LEFT;
      }), _initializer4$I = applyDecoratedInitializer(_class2$1S.prototype, "_verticalAlign", [serializable$j], function () {
        return VerticalTextAlignment.TOP;
      }), _initializer5$w = applyDecoratedInitializer(_class2$1S.prototype, "_fontSize", [serializable$j], function () {
        return 40;
      }), _initializer6$o = applyDecoratedInitializer(_class2$1S.prototype, "_fontColor", [serializable$j], function () {
        return Color$1.WHITE.clone();
      }), _initializer7$k = applyDecoratedInitializer(_class2$1S.prototype, "_maxWidth", [serializable$j], function () {
        return 0;
      }), _initializer8$j = applyDecoratedInitializer(_class2$1S.prototype, "_fontFamily", [serializable$j], function () {
        return 'Arial';
      }), _initializer9$h = applyDecoratedInitializer(_class2$1S.prototype, "_font", [serializable$j], function () {
        return null;
      }), _initializer10$f = applyDecoratedInitializer(_class2$1S.prototype, "_isSystemFontUsed", [serializable$j], function () {
        return true;
      }), _initializer11$d = applyDecoratedInitializer(_class2$1S.prototype, "_userDefinedFont", [serializable$j], function () {
        return null;
      }), _initializer12$b = applyDecoratedInitializer(_class2$1S.prototype, "_cacheMode", [serializable$j], function () {
        return CacheMode.NONE;
      }), _initializer13$a = applyDecoratedInitializer(_class2$1S.prototype, "_imageAtlas", [serializable$j], function () {
        return null;
      }), _initializer14$8 = applyDecoratedInitializer(_class2$1S.prototype, "_handleTouchEvent", [serializable$j], function () {
        return true;
      })), _class2$1S)) || _class$23) || _class$23));
      legacyCC.RichText = RichText;

      var _dec$23, _dec2$1B, _class$22;
      var UIMeshRenderer = exports('k', (_dec$23 = ccclass$n('cc.UIMeshRenderer'), _dec2$1B = executionOrder$1(110), _dec$23(_class$22 = _dec2$1B(_class$22 = function (_Component) {
        _inheritsLoose(UIMeshRenderer, _Component);
        function UIMeshRenderer() {
          var _this;
          _this = _Component.call(this) || this;
          _this._modelComponent = null;
          _this._dirtyVersion = -1;
          _this._internalId = -1;
          _this.stencilStage = Stage.DISABLED;
          _this._renderData = null;
          _this._renderEntity = new RenderEntity(RenderEntityType.DYNAMIC);
          return _this;
        }
        var _proto = UIMeshRenderer.prototype;
        _proto.__preload = function __preload() {
          this.node._uiProps.uiComp = this;
        };
        _proto.onEnable = function onEnable() {
          uiRendererManager.addRenderer(this);
          this.markForUpdateRenderData();
        };
        _proto.onDisable = function onDisable() {
          uiRendererManager.removeRenderer(this);
          this.renderEntity.enabled = this._canRender();
        };
        _proto.onLoad = function onLoad() {
          if (!this.node._uiProps.uiTransformComp) {
            this.node.addComponent('cc.UITransform');
          }
          this._modelComponent = this.getComponent('cc.ModelRenderer');
          if (!this._modelComponent) {
            warn("node '" + (this.node && this.node.name) + "' doesn't have any renderable component");
            return;
          }
          this.renderEntity.setNode(this.node);
        };
        _proto.onDestroy = function onDestroy() {
          this.renderEntity.setNode(null);
          if (this.node._uiProps.uiComp === this) {
            this.node._uiProps.uiComp = null;
          }
          this._modelComponent = this.getComponent('cc.ModelRenderer');
          if (!this._modelComponent) {
            return;
          }
          this._modelComponent._sceneGetter = null;
        };
        _proto._render = function _render(render) {
          if (this._modelComponent) {
            var models = this._modelComponent._collectModels();
            this._modelComponent._detachFromScene();
            for (var i = 0; i < models.length; i++) {
              if (models[i].enabled) {
                render.commitModel(this, models[i], this._modelComponent.material);
              }
            }
            return true;
          }
          return false;
        };
        _proto.fillBuffers = function fillBuffers(render) {
          if (this.enabled) {
            this._render(render);
          }
        };
        _proto.updateRenderer = function updateRenderer() {
        };
        _proto._uploadRenderData = function _uploadRenderData(index) {
        };
        _proto.postUpdateAssembler = function postUpdateAssembler(render) {};
        _proto.update = function update() {
          this._fitUIRenderQueue();
        };
        _proto._fitUIRenderQueue = function _fitUIRenderQueue() {
          if (!this._modelComponent) {
            return;
          }
          var matNum = this._modelComponent.sharedMaterials.length;
          for (var i = 0; i < matNum; i++) {
            var material = this._modelComponent.getMaterialInstance(i);
            if (material == null) {
              continue;
            }
            var passes = material.passes;
            var passNum = passes.length;
            for (var j = 0; j < passNum; j++) {
              var pass = passes[j];
              pass.setPriority(RenderPriority.MAX - 11);
              material.recompileShaders({
                CC_FORCE_FORWARD_SHADING: true
              }, j);
            }
          }
        };
        _proto.markForUpdateRenderData = function markForUpdateRenderData(enable) {
          uiRendererManager.markDirtyRenderer(this);
        };
        _proto.setNodeDirty = function setNodeDirty() {};
        _proto.setTextureDirty = function setTextureDirty() {};
        _proto._canRender = function _canRender() {
          return this.enabled && this._modelComponent !== null;
        };
        _createClass(UIMeshRenderer, [{
          key: "modelComponent",
          get: function get() {
            return this._modelComponent;
          }
        }, {
          key: "renderEntity",
          get: function get() {
            {
              assert(Boolean(this._renderEntity), 'this._renderEntity should not be invalid');
            }
            return this._renderEntity;
          }
        }, {
          key: "renderData",
          get: function get() {
            return this._renderData;
          }
        }]);
        return UIMeshRenderer;
      }(Component)) || _class$22) || _class$22));
      legacyCC.UIMeshRenderer = UIMeshRenderer;

      var UI_VIS_FLAG = Layers.Enum.NONE | Layers.Enum.UI_3D;
      var DrawBatch2D = function () {
        function DrawBatch2D() {
          this.model = null;
          this.texture = null;
          this.sampler = null;
          this.useLocalData = null;
          this.isStatic = false;
          this.textureHash = 0;
          this.samplerHash = 0;
          this._passes = [];
          this._shaders = [];
          this._visFlags = UI_VIS_FLAG;
          this._inputAssembler = null;
          this._descriptorSet = null;
        }
        var _proto = DrawBatch2D.prototype;
        _proto.destroy = function destroy(ui) {
          this._passes = [];
        };
        _proto.clear = function clear() {
          this._inputAssembler = null;
          this._descriptorSet = null;
          this.texture = null;
          this.sampler = null;
          this.textureHash = 0;
          this.samplerHash = 0;
          this.model = null;
          this.isStatic = false;
          this.useLocalData = null;
          this.visFlags = UI_VIS_FLAG;
        };
        _proto.fillPasses = function fillPasses(mat, dss, dssHash, patches) {
          if (mat) {
            var passes = mat.passes;
            if (!passes) {
              return;
            }
            this._shaders.length = passes.length;
            for (var i = 0; i < passes.length; i++) {
              if (!this._passes[i]) {
                this._passes[i] = new Pass(legacyCC.director.root);
              }
              var mtlPass = passes[i];
              var passInUse = this._passes[i];
              mtlPass.update();
              if (!dss) {
                dss = mtlPass.depthStencilState;
                dssHash = 0;
              }
              passInUse._initPassFromTarget(mtlPass, dss, dssHash);
              this._shaders[i] = passInUse.getShaderVariant(patches);
            }
          }
        };
        _createClass(DrawBatch2D, [{
          key: "inputAssembler",
          get: function get() {
            return this._inputAssembler;
          },
          set: function set(ia) {
            this._inputAssembler = ia;
          }
        }, {
          key: "descriptorSet",
          get: function get() {
            return this._descriptorSet;
          },
          set: function set(ds) {
            this._descriptorSet = ds;
          }
        }, {
          key: "visFlags",
          get: function get() {
            return this._visFlags;
          },
          set: function set(vis) {
            this._visFlags = vis;
          }
        }, {
          key: "passes",
          get: function get() {
            return this._passes;
          }
        }, {
          key: "shaders",
          get: function get() {
            return this._shaders;
          }
        }]);
        return DrawBatch2D;
      }();

      var _dec$22, _dec2$1A, _class$21, _class2$1R;
      var UIStaticBatch = exports('n', (_dec$22 = ccclass$n('cc.UIStaticBatch'), _dec2$1A = executionOrder$1(110), _dec$22(_class$21 = _dec2$1A(_class$21 = (_class2$1R = function (_UIRenderer) {
        _inheritsLoose(UIStaticBatch, _UIRenderer);
        function UIStaticBatch() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _UIRenderer.call.apply(_UIRenderer, [this].concat(args)) || this;
          _this._init = false;
          _this._bufferAccessor = null;
          _this._dirty = true;
          _this._uiDrawBatchList = [];
          return _this;
        }
        var _proto = UIStaticBatch.prototype;
        _proto.postUpdateAssembler = function postUpdateAssembler(render) {};
        _proto.markAsDirty = function markAsDirty() {};
        _proto._requireDrawBatch = function _requireDrawBatch() {
          var batch = new DrawBatch2D();
          batch.isStatic = true;
          this._uiDrawBatchList.push(batch);
          return batch;
        };
        _proto._clearData = function _clearData() {
          if (this._bufferAccessor) {
            this._bufferAccessor.reset();
            var ui = this._getBatcher();
            for (var i = 0; i < this._uiDrawBatchList.length; i++) {
              var element = this._uiDrawBatchList[i];
              element.destroy(ui);
            }
          }
          this._uiDrawBatchList.length = 0;
          this._init = false;
        };
        _proto._getBatcher = function _getBatcher() {
          if (director.root && director.root.batcher2D) {
            return director.root.batcher2D;
          }
          warnID(9301);
          return null;
        };
        _createClass(UIStaticBatch, [{
          key: "color",
          get: function get() {
            return this._color;
          },
          set: function set(value) {
            if (this._color === value) {
              return;
            }
            this._color.set(value);
          }
        }, {
          key: "drawBatchList",
          get: function get() {
            return this._uiDrawBatchList;
          }
        }]);
        return UIStaticBatch;
      }(UIRenderer), (_applyDecoratedDescriptor(_class2$1R.prototype, "color", [override], Object.getOwnPropertyDescriptor(_class2$1R.prototype, "color"), _class2$1R.prototype)), _class2$1R)) || _class$21) || _class$21));

      var _dec$21, _dec2$1z, _dec3$16, _class$20, _class2$1Q, _initializer$1H, _initializer2$1m, _initializer3$U;
      var LabelShadow = exports('o', (_dec$21 = ccclass$n('cc.LabelShadow'), _dec2$1z = executionOrder$1(110), _dec3$16 = requireComponent(Label), _dec$21(_class$20 = _dec2$1z(_class$20 = _dec3$16(_class$20 = (_class2$1Q = function (_Component) {
        _inheritsLoose(LabelShadow, _Component);
        function LabelShadow() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Component.call.apply(_Component, [this].concat(args)) || this;
          _this._color = _initializer$1H && _initializer$1H();
          _this._offset = _initializer2$1m && _initializer2$1m();
          _this._blur = _initializer3$U && _initializer3$U();
          return _this;
        }
        var _proto = LabelShadow.prototype;
        _proto.onEnable = function onEnable() {
          this._updateRenderData();
        };
        _proto.onDisable = function onDisable() {
          this._updateRenderData();
        };
        _proto._updateRenderData = function _updateRenderData() {
          var label = this.node.getComponent(Label);
          if (label) {
            label.updateRenderData(true);
          }
        };
        _createClass(LabelShadow, [{
          key: "color",
          get: function get() {
            return this._color;
          },
          set: function set(value) {
            if (this._color === value) {
              return;
            }
            this._color.set(value);
            this._updateRenderData();
          }
        }, {
          key: "offset",
          get: function get() {
            return this._offset;
          },
          set: function set(value) {
            this._offset = value;
            this._updateRenderData();
          }
        }, {
          key: "blur",
          get: function get() {
            return this._blur;
          },
          set: function set(value) {
            this._blur = value;
            this._updateRenderData();
          }
        }]);
        return LabelShadow;
      }(Component), (_initializer$1H = applyDecoratedInitializer(_class2$1Q.prototype, "_color", [serializable$j], function () {
        return new Color$1(0, 0, 0, 255);
      }), _initializer2$1m = applyDecoratedInitializer(_class2$1Q.prototype, "_offset", [serializable$j], function () {
        return new Vec2(2, 2);
      }), _initializer3$U = applyDecoratedInitializer(_class2$1Q.prototype, "_blur", [serializable$j], function () {
        return 2;
      })), _class2$1Q)) || _class$20) || _class$20) || _class$20));

      var _dec$20, _dec2$1y, _class$1$, _class2$1P, _initializer$1G;
      var UIOpacity = exports('p', (_dec$20 = ccclass$n('cc.UIOpacity'), _dec2$1y = executionOrder$1(110), _dec$20(_class$1$ = _dec2$1y(_class$1$ = disallowMultiple$1(_class$1$ = (_class2$1P = function (_Component) {
        _inheritsLoose(UIOpacity, _Component);
        function UIOpacity() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Component.call.apply(_Component, [this].concat(args)) || this;
          _this._opacity = _initializer$1G && _initializer$1G();
          return _this;
        }
        var _proto = UIOpacity.prototype;
        _proto.setEntityLocalOpacityDirtyRecursively = function setEntityLocalOpacityDirtyRecursively(dirty) {
        };
        UIOpacity.setEntityLocalOpacityDirtyRecursively = function setEntityLocalOpacityDirtyRecursively(node, dirty, interruptParentOpacity) {
          if (!node.isValid) {
            return;
          }
          var render = node._uiProps.uiComp;
          var uiOp = node.getComponent(UIOpacity);
          var interruptOpacity = interruptParentOpacity;
          if (render && render.color) {
            render.renderEntity.colorDirty = dirty;
            if (uiOp) {
              render.renderEntity.localOpacity = interruptOpacity * uiOp.opacity / 255;
            } else {
              render.renderEntity.localOpacity = interruptOpacity;
            }
            interruptOpacity = 1;
          } else if (uiOp) {
            interruptOpacity = interruptOpacity * uiOp.opacity / 255;
          }
          for (var i = 0; i < node.children.length; i++) {
            UIOpacity.setEntityLocalOpacityDirtyRecursively(node.children[i], dirty || interruptOpacity < 1, interruptOpacity);
          }
        };
        _proto.onEnable = function onEnable() {
          this.node._uiProps.localOpacity = this._opacity / 255;
          this.setEntityLocalOpacityDirtyRecursively(true);
        };
        _proto.onDisable = function onDisable() {
          this.node._uiProps.localOpacity = 1;
          this.setEntityLocalOpacityDirtyRecursively(true);
        };
        _createClass(UIOpacity, [{
          key: "opacity",
          get: function get() {
            return this._opacity;
          },
          set: function set(value) {
            if (this._opacity === value) {
              return;
            }
            value = clampf(value, 0, 255);
            this._opacity = value;
            this.node._uiProps.localOpacity = value / 255;
            this.setEntityLocalOpacityDirtyRecursively(true);
          }
        }]);
        return UIOpacity;
      }(Component), (_initializer$1G = applyDecoratedInitializer(_class2$1P.prototype, "_opacity", [serializable$j], function () {
        return 255;
      })), _class2$1P)) || _class$1$) || _class$1$) || _class$1$));

      var Aim = function Aim(i, x, y) {
        this.i = void 0;
        this.x = void 0;
        this.y = void 0;
        this.prev = null;
        this.next = null;
        this.z = null;
        this.prevZ = null;
        this.nextZ = null;
        this.steiner = false;
        this.i = i;
        this.x = x;
        this.y = y;
      };
      function linkedList(datas, start, end, dim, clockwise) {
        var i = 0;
        var last = null;
        if (clockwise === signedArea(datas, start, end, dim) > 0) {
          for (i = start; i < end; i += dim) {
            last = insertNode(i, datas[i], datas[i + 1], last);
          }
        } else {
          for (i = end - dim; i >= start; i -= dim) {
            last = insertNode(i, datas[i], datas[i + 1], last);
          }
        }
        if (last && equals(last, last.next)) {
          removeNode(last);
          last = last.next;
        }
        return last;
      }
      function filterPoints(start, end) {
        if (end === void 0) {
          end = null;
        }
        if (!start) {
          return start;
        }
        if (!end) {
          end = start;
        }
        var p = start;
        var again = false;
        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) {
              return null;
            }
            again = true;
          } else {
            p = p.next;
          }
        } while (again || p !== end);
        return end;
      }
      function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
        if (pass === void 0) {
          pass = 0;
        }
        if (!ear) {
          return;
        }
        if (!pass && size) {
          indexCurve(ear, minX, minY, size);
        }
        var stop = ear;
        var prev = null;
        var next = null;
        while (ear.prev !== ear.next) {
          prev = ear.prev;
          next = ear.next;
          if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
            triangles.push(prev.i / dim);
            triangles.push(ear.i / dim);
            triangles.push(next.i / dim);
            removeNode(ear);
            ear = next.next;
            stop = next.next;
            continue;
          }
          ear = next;
          if (ear === stop) {
            if (!pass) {
              earcutLinked(filterPoints(ear), triangles, dim, minX, minY, size, 1);
            } else if (pass === 1) {
              ear = cureLocalIntersections(ear, triangles, dim);
              earcutLinked(ear, triangles, dim, minX, minY, size, 2);
            } else if (pass === 2) {
              splitEarcut(ear, triangles, dim, minX, minY, size);
            }
            break;
          }
        }
      }
      function isEar(ear) {
        var a = ear.prev;
        var b = ear;
        var c = ear.next;
        if (area(a, b, c) >= 0) {
          return false;
        }
        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, size) {
        var a = ear.prev;
        var b = ear;
        var c = ear.next;
        if (area(a, b, c) >= 0) {
          return false;
        }
        var minTX = a.x < b.x ? a.x < c.x ? a.x : c.x : b.x < c.x ? b.x : c.x;
        var minTY = a.y < b.y ? a.y < c.y ? a.y : c.y : b.y < c.y ? b.y : c.y;
        var maxTX = a.x > b.x ? a.x > c.x ? a.x : c.x : b.x > c.x ? b.x : c.x;
        var maxTY = a.y > b.y ? a.y > c.y ? a.y : c.y : b.y > c.y ? b.y : c.y;
        var minZ = zOrder(minTX, minTY, minX, minY, size);
        var maxZ = zOrder(maxTX, maxTY, minX, minY, size);
        var p = ear.nextZ;
        while (p && p.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.nextZ;
        }
        p = ear.prevZ;
        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;
        }
        return true;
      }
      function cureLocalIntersections(start, triangles, dim) {
        var p = start;
        do {
          var a = p.prev;
          var 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);
            removeNode(p);
            removeNode(p.next);
            p = start = b;
          }
          p = p.next;
        } while (p !== start);
        return p;
      }
      function splitEarcut(start, triangles, dim, minX, minY, size) {
        var a = start;
        do {
          var b = a.next.next;
          while (b !== a.prev) {
            if (a.i !== b.i && isValidDiagonal(a, b)) {
              var c = splitPolygon(a, b);
              a = filterPoints(a, a.next);
              c = filterPoints(c, c.next);
              earcutLinked(a, triangles, dim, minX, minY, size);
              earcutLinked(c, triangles, dim, minX, minY, size);
              return;
            }
            b = b.next;
          }
          a = a.next;
        } while (a !== start);
      }
      function eliminateHoles(datas, holeIndices, outerNode, dim) {
        var queue = [];
        var i = 0;
        var len = 0;
        var start = 0;
        var end = 0;
        var list = null;
        for (i = 0, len = holeIndices.length; i < len; i++) {
          start = holeIndices[i] * dim;
          end = i < len - 1 ? holeIndices[i + 1] * dim : datas.length;
          list = linkedList(datas, start, end, dim, false);
          if (!list) {
            continue;
          }
          if (list === list.next) {
            list.steiner = true;
          }
          queue.push(getLeftmost(list));
        }
        queue.sort(compareX);
        if (!outerNode) {
          return outerNode;
        }
        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;
      }
      function eliminateHole(hole, outerNode) {
        outerNode = findHoleBridge(hole, outerNode);
        if (outerNode) {
          var b = splitPolygon(outerNode, hole);
          filterPoints(b, b.next);
        }
      }
      function findHoleBridge(hole, outerNode) {
        var p = outerNode;
        var hx = hole.x;
        var hy = hole.y;
        var qx = -Infinity;
        var m = null;
        do {
          if (hy <= p.y && hy >= p.next.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;
        }
        var stop = m;
        var mx = m.x;
        var my = m.y;
        var tanMin = Infinity;
        var tan;
        p = m.next;
        while (p !== stop) {
          if (hx >= p.x && p.x >= mx && 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);
            if ((tan < tanMin || tan === tanMin && p.x > m.x) && locallyInside(p, hole)) {
              m = p;
              tanMin = tan;
            }
          }
          p = p.next;
        }
        return m;
      }
      function indexCurve(start, minX, minY, size) {
        var p = start;
        do {
          if (p.z === null) {
            p.z = zOrder(p.x, p.y, minX, minY, size);
          }
          p.prevZ = p.prev;
          p.nextZ = p.next;
          p = p.next;
        } while (p !== start);
        p.prevZ.nextZ = null;
        p.prevZ = null;
        sortLinked(p);
      }
      function sortLinked(list) {
        var i = 0;
        var p = null;
        var q = null;
        var e = null;
        var tail = null;
        var numMerges = 0;
        var pSize = 0;
        var qSize = 0;
        var 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) {
                e = q;
                q = q.nextZ;
                qSize--;
              } else if (qSize === 0 || !q) {
                e = p;
                p = p.nextZ;
                pSize--;
              } else if (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;
      }
      function zOrder(x, y, minX, minY, size) {
        x = 32767 * (x - minX) / size;
        y = 32767 * (y - minY) / size;
        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;
      }
      function getLeftmost(start) {
        var p = start;
        var leftmost = start;
        do {
          if (p.x < leftmost.x) {
            leftmost = p;
          }
          p = p.next;
        } while (p !== start);
        return leftmost;
      }
      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;
      }
      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);
      }
      function area(p, q, r) {
        return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
      }
      function equals(p1, p2) {
        return p1.x === p2.x && p1.y === p2.y;
      }
      function intersects(p1, q1, p2, q2) {
        if (equals(p1, q1) && equals(p2, 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;
      }
      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;
      }
      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;
      }
      function middleInside(a, b) {
        var p = a;
        var inside = false;
        var px = (a.x + b.x) / 2;
        var py = (a.y + b.y) / 2;
        do {
          if (p.y > py !== p.next.y > py && 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;
      }
      function splitPolygon(a, b) {
        var a2 = new Aim(a.i, a.x, a.y);
        var b2 = new Aim(b.i, b.x, b.y);
        var an = a.next;
        var 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;
      }
      function insertNode(i, x, y, last) {
        var p = new Aim(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 signedArea(datas, start, end, dim) {
        var sum = 0;
        for (var i = start, j = end - dim; i < end; i += dim) {
          sum += (datas[j] - datas[i]) * (datas[i + 1] + datas[j + 1]);
          j = i;
        }
        return sum;
      }
      function earcut(datas, holeIndices, dim) {
        dim = dim || 3;
        var hasHoles = holeIndices ? holeIndices.length : 0;
        var outerLen = hasHoles ? holeIndices[0] * dim : datas.length;
        var outerNode = linkedList(datas, 0, outerLen, dim, true);
        var triangles = [];
        if (!outerNode) {
          return triangles;
        }
        var minX = 0;
        var minY = 0;
        var maxX = 0;
        var maxY = 0;
        var x = 0;
        var y = 0;
        var size = 0;
        if (hasHoles) {
          outerNode = eliminateHoles(datas, holeIndices, outerNode, dim);
        }
        if (datas.length > 80 * dim) {
          minX = maxX = datas[0];
          minY = maxY = datas[1];
          for (var i = dim; i < outerLen; i += dim) {
            x = datas[i];
            y = datas[i + 1];
            if (x < minX) {
              minX = x;
            }
            if (y < minY) {
              minY = y;
            }
            if (x > maxX) {
              maxX = x;
            }
            if (y > maxY) {
              maxY = y;
            }
          }
          size = Math.max(maxX - minX, maxY - minY);
        }
        earcutLinked(outerNode, triangles, dim, minX, minY, size);
        return triangles;
      }

      var MAX_VERTEX = 65535;
      var MAX_INDICES = MAX_VERTEX * 2;
      var PI = Math.PI;
      var min = Math.min;
      var max = Math.max;
      var ceil = Math.ceil;
      var acos = Math.acos;
      var cos = Math.cos;
      var sin = Math.sin;
      var atan2 = Math.atan2;
      var attrBytes = 8;
      var _renderData = null;
      var _impl = null;
      var _curColor = new Color$1();
      var vec3_temps = [];
      for (var i$1 = 0; i$1 < 4; i$1++) {
        vec3_temps.push(new Vec3());
      }
      function curveDivs(r, arc, tol) {
        var da = acos(r / (r + tol)) * 2.0;
        return max(2, ceil(arc / da));
      }
      function clamp(v, minNum, maxNum) {
        if (v < minNum) {
          return minNum;
        } else if (v > maxNum) {
          return maxNum;
        }
        return v;
      }
      var graphicsAssembler = {
        useModel: true,
        updateRenderData: function updateRenderData(graphics) {
        },
        fillBuffers: function fillBuffers(graphics, renderer) {},
        renderIA: function renderIA(graphics, renderer) {},
        getRenderData: function getRenderData(graphics, vertexCount) {
          if (!_impl) {
            return null;
          }
          var renderDataList = _impl.getRenderDataList();
          var renderData = renderDataList[_impl.dataOffset];
          if (!renderData) {
            return null;
          }
          var meshBuffer = renderData;
          var maxVertexCount = meshBuffer ? meshBuffer.vertexStart + vertexCount : 0;
          if (maxVertexCount > MAX_VERTEX || maxVertexCount * 3 > MAX_INDICES) {
            ++_impl.dataOffset;
            if (_impl.dataOffset < renderDataList.length) {
              renderData = renderDataList[_impl.dataOffset];
            } else {
              renderData = _impl.requestRenderData();
              renderDataList[_impl.dataOffset] = renderData;
            }
            meshBuffer = renderData;
          }
          if (meshBuffer && meshBuffer.vertexCount < maxVertexCount) {
            meshBuffer.request(vertexCount, vertexCount * 3);
          }
          return renderData;
        },
        stroke: function stroke(graphics) {
          Color$1.copy(_curColor, graphics.strokeColor);
          if (!graphics.impl) {
            return;
          }
          this._flattenPaths(graphics.impl);
          this._expandStroke(graphics);
          graphics.impl.updatePathOffset = true;
          this.end(graphics);
        },
        fill: function fill(graphics) {
          Color$1.copy(_curColor, graphics.fillColor);
          this._expandFill(graphics);
          if (graphics.impl) {
            graphics.impl.updatePathOffset = true;
          }
          this.end(graphics);
        },
        end: function end(graphics) {
          graphics.markForUpdateRenderData();
        },
        _expandStroke: function _expandStroke(graphics) {
          var w = graphics.lineWidth * 0.5;
          var lineCap = graphics.lineCap;
          var lineJoin = graphics.lineJoin;
          var miterLimit = graphics.miterLimit;
          _impl = graphics.impl;
          if (!_impl) {
            return;
          }
          var nCap = curveDivs(w, PI, _impl.tessTol);
          this._calculateJoins(_impl, w, lineJoin, miterLimit);
          var paths = _impl.paths;
          var vertexCount = 0;
          for (var _i = _impl.pathOffset, l = _impl.pathLength; _i < l; _i++) {
            var path = paths[_i];
            var pointsLength = path.points.length;
            if (lineJoin === LineJoin.ROUND) {
              vertexCount += (pointsLength + path.bevel * (nCap + 2) + 1) * 2;
            } else {
              vertexCount += (pointsLength + path.bevel * 5 + 1) * 2;
            }
            if (!path.closed) {
              if (lineCap === LineCap.ROUND) {
                vertexCount += (nCap * 2 + 2) * 2;
              } else {
                vertexCount += (3 + 3) * 2;
              }
            }
          }
          var meshBuffer = _renderData = this.getRenderData(graphics, vertexCount);
          if (!meshBuffer) {
            return;
          }
          var vData = meshBuffer.vData;
          var iData = meshBuffer.iData;
          for (var _i2 = _impl.pathOffset, _l = _impl.pathLength; _i2 < _l; _i2++) {
            var _path = paths[_i2];
            var pts = _path.points;
            var _pointsLength = pts.length;
            var offset = meshBuffer.vertexStart;
            var p0 = void 0;
            var p1 = void 0;
            var start = 0;
            var end = 0;
            var loop = _path.closed;
            if (loop) {
              p0 = pts[_pointsLength - 1];
              p1 = pts[0];
              start = 0;
              end = _pointsLength;
            } else {
              p0 = pts[0];
              p1 = pts[1];
              start = 1;
              end = _pointsLength - 1;
            }
            p1 = p1 || p0;
            if (!loop) {
              var dPos = new Point(p1.x, p1.y);
              dPos.subtract(p0);
              dPos.normalize();
              var dx = dPos.x;
              var dy = dPos.y;
              if (lineCap === LineCap.BUTT) {
                this._buttCapStart(p0, dx, dy, w, 0);
              } else if (lineCap === LineCap.SQUARE) {
                this._buttCapStart(p0, dx, dy, w, w);
              } else if (lineCap === LineCap.ROUND) {
                this._roundCapStart(p0, dx, dy, w, nCap);
              }
            }
            for (var j = start; j < end; ++j) {
              if (lineJoin === LineJoin.ROUND) {
                this._roundJoin(p0, p1, w, w, nCap);
              } else if ((p1.flags & (PointFlags.PT_BEVEL | PointFlags.PT_INNERBEVEL)) !== 0) {
                this._bevelJoin(p0, p1, w, w);
              } else {
                this._vSet(p1.x + p1.dmx * w, p1.y + p1.dmy * w, 1);
                this._vSet(p1.x - p1.dmx * w, p1.y - p1.dmy * w, -1);
              }
              p0 = p1;
              p1 = pts[j + 1];
            }
            if (loop) {
              var vDataOffset = offset * attrBytes;
              this._vSet(vData[vDataOffset], vData[vDataOffset + 1], 1);
              this._vSet(vData[vDataOffset + attrBytes], vData[vDataOffset + attrBytes + 1], -1);
            } else {
              var _dPos = new Point(p1.x, p1.y);
              _dPos.subtract(p0);
              _dPos.normalize();
              var _dx = _dPos.x;
              var _dy = _dPos.y;
              if (lineCap === LineCap.BUTT) {
                this._buttCapEnd(p1, _dx, _dy, w, 0);
              } else if (lineCap === LineCap.SQUARE) {
                this._buttCapEnd(p1, _dx, _dy, w, w);
              } else if (lineCap === LineCap.ROUND) {
                this._roundCapEnd(p1, _dx, _dy, w, nCap);
              }
            }
            var indicesOffset = meshBuffer.indexStart;
            for (var begin = offset + 2, over = meshBuffer.vertexStart; begin < over; begin++) {
              iData[indicesOffset++] = begin - 2;
              iData[indicesOffset++] = begin - 1;
              iData[indicesOffset++] = begin;
            }
            meshBuffer.indexStart = indicesOffset;
          }
          _renderData = null;
          _impl = null;
        },
        _expandFill: function _expandFill(graphics) {
          _impl = graphics.impl;
          if (!_impl) {
            return;
          }
          var paths = _impl.paths;
          var vertexCount = 0;
          for (var _i3 = _impl.pathOffset, l = _impl.pathLength; _i3 < l; _i3++) {
            var path = paths[_i3];
            var pointsLength = path.points.length;
            vertexCount += pointsLength;
          }
          var renderData = _renderData = this.getRenderData(graphics, vertexCount);
          if (!renderData) {
            return;
          }
          var meshBuffer = renderData;
          var vData = meshBuffer.vData;
          var iData = meshBuffer.iData;
          for (var _i4 = _impl.pathOffset, _l2 = _impl.pathLength; _i4 < _l2; _i4++) {
            var _path2 = paths[_i4];
            var pts = _path2.points;
            var _pointsLength2 = pts.length;
            if (_pointsLength2 === 0) {
              continue;
            }
            var vertexOffset = renderData.vertexStart;
            for (var j = 0; j < _pointsLength2; ++j) {
              this._vSet(pts[j].x, pts[j].y);
            }
            var indicesOffset = renderData.indexStart;
            if (_path2.complex) {
              var earcutData = [];
              for (var _j = vertexOffset, end = renderData.vertexStart; _j < end; _j++) {
                var vDataOffset = _j * attrBytes;
                earcutData.push(vData[vDataOffset++]);
                earcutData.push(vData[vDataOffset++]);
                earcutData.push(vData[vDataOffset++]);
              }
              var newIndices = earcut(earcutData, null, 3);
              if (!newIndices || newIndices.length === 0) {
                continue;
              }
              for (var _j2 = 0, nIndices = newIndices.length; _j2 < nIndices; _j2++) {
                iData[indicesOffset++] = newIndices[_j2] + vertexOffset;
              }
            } else {
              var first = vertexOffset;
              for (var start = vertexOffset + 2, _end = meshBuffer.vertexStart; start < _end; start++) {
                iData[indicesOffset++] = first;
                iData[indicesOffset++] = start - 1;
                iData[indicesOffset++] = start;
              }
            }
            meshBuffer.indexStart = indicesOffset;
          }
          _renderData = null;
          _impl = null;
        },
        _calculateJoins: function _calculateJoins(impl, w, lineJoin, miterLimit) {
          var iw = 0.0;
          if (w > 0.0) {
            iw = 1 / w;
          }
          var paths = impl.paths;
          for (var _i5 = impl.pathOffset, l = impl.pathLength; _i5 < l; _i5++) {
            var path = paths[_i5];
            var pts = path.points;
            var ptsLength = pts.length;
            var p0 = pts[ptsLength - 1];
            var p1 = pts[0];
            path.bevel = 0;
            for (var j = 0; j < ptsLength; j++) {
              var dmr2 = 0;
              var cross = 0;
              var limit = 0;
              var dlx0 = p0.dy;
              var dly0 = -p0.dx;
              var dlx1 = p1.dy;
              var dly1 = -p1.dx;
              p1.dmx = (dlx0 + dlx1) * 0.5;
              p1.dmy = (dly0 + dly1) * 0.5;
              dmr2 = p1.dmx * p1.dmx + p1.dmy * p1.dmy;
              if (dmr2 > 0.000001) {
                var scale = 1 / dmr2;
                if (scale > 600) {
                  scale = 600;
                }
                p1.dmx *= scale;
                p1.dmy *= scale;
              }
              cross = p1.dx * p0.dy - p0.dx * p1.dy;
              if (cross > 0) {
                p1.flags |= PointFlags.PT_LEFT;
              }
              limit = max(11, min(p0.len, p1.len) * iw);
              if (dmr2 * limit * limit < 1) {
                p1.flags |= PointFlags.PT_INNERBEVEL;
              }
              if (p1.flags & PointFlags.PT_CORNER) {
                if (dmr2 * miterLimit * miterLimit < 1 || lineJoin === LineJoin.BEVEL || lineJoin === LineJoin.ROUND) {
                  p1.flags |= PointFlags.PT_BEVEL;
                }
              }
              if ((p1.flags & (PointFlags.PT_BEVEL | PointFlags.PT_INNERBEVEL)) !== 0) {
                path.bevel++;
              }
              p0 = p1;
              p1 = pts[j + 1];
            }
          }
        },
        _flattenPaths: function _flattenPaths(impl) {
          var paths = impl.paths;
          for (var _i6 = impl.pathOffset, l = impl.pathLength; _i6 < l; _i6++) {
            var path = paths[_i6];
            var pts = path.points;
            var p0 = pts[pts.length - 1];
            var p1 = pts[0];
            if (pts.length > 2 && p0.equals(p1)) {
              path.closed = true;
              pts.pop();
              p0 = pts[pts.length - 1];
            }
            for (var j = 0, size = pts.length; j < size; j++) {
              var dPos = new Point(p1.x, p1.y);
              dPos.subtract(p0);
              p0.len = dPos.length();
              if (dPos.x || dPos.y) {
                dPos.normalize();
              }
              p0.dx = dPos.x;
              p0.dy = dPos.y;
              p0 = p1;
              p1 = pts[j + 1];
            }
          }
        },
        _chooseBevel: function _chooseBevel(bevel, p0, p1, w) {
          var x = p1.x;
          var y = p1.y;
          var x0 = 0;
          var y0 = 0;
          var x1 = 0;
          var y1 = 0;
          if (bevel !== 0) {
            x0 = x + p0.dy * w;
            y0 = y - p0.dx * w;
            x1 = x + p1.dy * w;
            y1 = y - p1.dx * w;
          } else {
            x0 = x1 = x + p1.dmx * w;
            y0 = y1 = y + p1.dmy * w;
          }
          return [x0, y0, x1, y1];
        },
        _buttCapStart: function _buttCapStart(p, dx, dy, w, d) {
          var px = p.x - dx * d;
          var py = p.y - dy * d;
          var dlx = dy;
          var dly = -dx;
          this._vSet(px + dlx * w, py + dly * w, 1);
          this._vSet(px - dlx * w, py - dly * w, -1);
        },
        _buttCapEnd: function _buttCapEnd(p, dx, dy, w, d) {
          var px = p.x + dx * d;
          var py = p.y + dy * d;
          var dlx = dy;
          var dly = -dx;
          this._vSet(px + dlx * w, py + dly * w, 1);
          this._vSet(px - dlx * w, py - dly * w, -1);
        },
        _roundCapStart: function _roundCapStart(p, dx, dy, w, nCap) {
          var px = p.x;
          var py = p.y;
          var dlx = dy;
          var dly = -dx;
          for (var _i7 = 0; _i7 < nCap; _i7++) {
            var a = _i7 / (nCap - 1) * PI;
            var ax = cos(a) * w;
            var ay = sin(a) * w;
            this._vSet(px - dlx * ax - dx * ay, py - dly * ax - dy * ay, 1);
            this._vSet(px, py, 0);
          }
          this._vSet(px + dlx * w, py + dly * w, 1);
          this._vSet(px - dlx * w, py - dly * w, -1);
        },
        _roundCapEnd: function _roundCapEnd(p, dx, dy, w, nCap) {
          var px = p.x;
          var py = p.y;
          var dlx = dy;
          var dly = -dx;
          this._vSet(px + dlx * w, py + dly * w, 1);
          this._vSet(px - dlx * w, py - dly * w, -1);
          for (var _i8 = 0; _i8 < nCap; _i8++) {
            var a = _i8 / (nCap - 1) * PI;
            var ax = cos(a) * w;
            var ay = sin(a) * w;
            this._vSet(px, py, 0);
            this._vSet(px - dlx * ax + dx * ay, py - dly * ax + dy * ay, 1);
          }
        },
        _roundJoin: function _roundJoin(p0, p1, lw, rw, nCap) {
          var dlx0 = p0.dy;
          var dly0 = -p0.dx;
          var dlx1 = p1.dy;
          var dly1 = -p1.dx;
          var p1x = p1.x;
          var p1y = p1.y;
          if ((p1.flags & PointFlags.PT_LEFT) !== 0) {
            var out = this._chooseBevel(p1.flags & PointFlags.PT_INNERBEVEL, p0, p1, lw);
            var lx0 = out[0];
            var ly0 = out[1];
            var lx1 = out[2];
            var ly1 = out[3];
            var a0 = atan2(-dly0, -dlx0);
            var a1 = atan2(-dly1, -dlx1);
            if (a1 > a0) {
              a1 -= PI * 2;
            }
            this._vSet(lx0, ly0, 1);
            this._vSet(p1x - dlx0 * rw, p1.y - dly0 * rw, -1);
            var n = clamp(ceil((a0 - a1) / PI) * nCap, 2, nCap);
            for (var _i9 = 0; _i9 < n; _i9++) {
              var u = _i9 / (n - 1);
              var a = a0 + u * (a1 - a0);
              var rx = p1x + cos(a) * rw;
              var ry = p1y + sin(a) * rw;
              this._vSet(p1x, p1y, 0);
              this._vSet(rx, ry, -1);
            }
            this._vSet(lx1, ly1, 1);
            this._vSet(p1x - dlx1 * rw, p1y - dly1 * rw, -1);
          } else {
            var _out = this._chooseBevel(p1.flags & PointFlags.PT_INNERBEVEL, p0, p1, -rw);
            var rx0 = _out[0];
            var ry0 = _out[1];
            var rx1 = _out[2];
            var ry1 = _out[3];
            var _a = atan2(dly0, dlx0);
            var _a2 = atan2(dly1, dlx1);
            if (_a2 < _a) {
              _a2 += PI * 2;
            }
            this._vSet(p1x + dlx0 * rw, p1y + dly0 * rw, 1);
            this._vSet(rx0, ry0, -1);
            var _n = clamp(ceil((_a2 - _a) / PI) * nCap, 2, nCap);
            for (var _i10 = 0; _i10 < _n; _i10++) {
              var _u = _i10 / (_n - 1);
              var _a3 = _a + _u * (_a2 - _a);
              var lx = p1x + cos(_a3) * lw;
              var ly = p1y + sin(_a3) * lw;
              this._vSet(lx, ly, 1);
              this._vSet(p1x, p1y, 0);
            }
            this._vSet(p1x + dlx1 * rw, p1y + dly1 * rw, 1);
            this._vSet(rx1, ry1, -1);
          }
        },
        _bevelJoin: function _bevelJoin(p0, p1, lw, rw) {
          var rx0 = 0;
          var ry0 = 0;
          var rx1 = 0;
          var ry1 = 0;
          var lx0 = 0;
          var ly0 = 0;
          var lx1 = 0;
          var ly1 = 0;
          var dlx0 = p0.dy;
          var dly0 = -p0.dx;
          var dlx1 = p1.dy;
          var dly1 = -p1.dx;
          if (p1.flags & PointFlags.PT_LEFT) {
            var out = this._chooseBevel(p1.flags & PointFlags.PT_INNERBEVEL, p0, p1, lw);
            lx0 = out[0];
            ly0 = out[1];
            lx1 = out[2];
            ly1 = out[3];
            this._vSet(lx0, ly0, 1);
            this._vSet(p1.x - dlx0 * rw, p1.y - dly0 * rw, -1);
            this._vSet(lx1, ly1, 1);
            this._vSet(p1.x - dlx1 * rw, p1.y - dly1 * rw, -1);
          } else {
            var _out2 = this._chooseBevel(p1.flags & PointFlags.PT_INNERBEVEL, p0, p1, -rw);
            rx0 = _out2[0];
            ry0 = _out2[1];
            rx1 = _out2[2];
            ry1 = _out2[3];
            this._vSet(p1.x + dlx0 * lw, p1.y + dly0 * lw, 1);
            this._vSet(rx0, ry0, -1);
            this._vSet(p1.x + dlx1 * lw, p1.y + dly1 * lw, 1);
            this._vSet(rx1, ry1, -1);
          }
        },
        _vSet: function _vSet(x, y, distance) {
          if (distance === void 0) {
            distance = 0;
          }
          if (!_renderData) {
            return;
          }
          var meshBuffer = _renderData;
          var dataOffset = meshBuffer.vertexStart * attrBytes;
          var vData = meshBuffer.vData;
          vData[dataOffset++] = x;
          vData[dataOffset++] = y;
          vData[dataOffset++] = 0;
          Color$1.toArray(vData, _curColor, dataOffset);
          dataOffset += 4;
          vData[dataOffset++] = distance;
          meshBuffer.vertexStart++;
        }
      };

      var graphicsAssemblerManager = exports('g', {
        getAssembler: function getAssembler(sprite) {
          return graphicsAssembler;
        }
      });
      Graphics.Assembler = graphicsAssemblerManager;

      var Alignment = ['left', 'center', 'right'];
      var MAX_SIZE = 2048;
      var _BASELINE_OFFSET = getBaselineOffset();
      var _invisibleAlpha = (1 / 255).toFixed(3);
      var MAX_CALCULATION_NUM = 3;
      var LetterInfo = function LetterInfo() {
        this["char"] = '';
        this.valid = true;
        this.x = 0;
        this.y = 0;
        this.line = 0;
        this.hash = '';
      };
      var TextProcessing = function () {
        function TextProcessing() {
          this._context = null;
          this._canvas = null;
          this._canvasData = null;
          this._lettersInfo = [];
          this._tmpRect = new Rect$1();
          this._maxFontSize = 100;
          this._fontScale = 1;
          this._canvasData = CanvasPool.getInstance().get();
          this._canvas = this._canvasData.canvas;
          this._context = this._canvasData.context;
        }
        var _proto = TextProcessing.prototype;
        _proto.destroy = function destroy() {
          CanvasPool.getInstance().put(this._canvasData);
          this._lettersInfo.length = 0;
        };
        _proto.processingString = function processingString(isBmFont, style, layout, outputLayoutData, inputString, out) {
          if (!isBmFont) {
            var loopTime = 0;
            this._fontScale = this._getStyleFontScale(style.fontSize, style.fontScale);
            this._updatePaddingRect(style, outputLayoutData);
            this._calculateLabelFont(style, layout, outputLayoutData, inputString);
            while ((outputLayoutData.canvasSize.width > MAX_SIZE || outputLayoutData.canvasSize.height > MAX_SIZE) && loopTime <= MAX_CALCULATION_NUM) {
              loopTime++;
              if (loopTime > MAX_CALCULATION_NUM) {
                this._fontScale = 1;
              } else {
                var maxValue = Math.max(outputLayoutData.canvasSize.width, outputLayoutData.canvasSize.height);
                var canvasScaleToMaxSizeRatio = MAX_SIZE / maxValue;
                this._fontScale *= canvasScaleToMaxSizeRatio;
                this._fontScale = Math.max(1, this._fontScale);
              }
              this._updatePaddingRect(style, outputLayoutData);
              this._calculateLabelFont(style, layout, outputLayoutData, inputString);
            }
          } else {
            if (!style.fntConfig) {
              this._fontScale = this._getStyleFontScale(style.originFontSize, style.fontScale);
            } else {
              this._fontScale = 1;
            }
            shareLabelInfo.fontScale = this._fontScale;
            this._setupBMFontOverflowMetrics(layout, outputLayoutData);
            this._updateFontScale(style);
            this._computeHorizontalKerningForText(style, layout, inputString);
            this._alignText(style, layout, outputLayoutData, inputString);
          }
          if (out) {
            out = outputLayoutData.parsedString;
          }
        };
        _proto.generateRenderInfo = function generateRenderInfo(isBmFont, style, layout, outputLayoutData, outputRenderData, inputString, callback) {
          if (!isBmFont) {
            this._updateLabelDimensions(style, layout, outputLayoutData);
            this._updateTexture(style, layout, outputLayoutData, outputRenderData);
            this.generateVertexData(isBmFont, style, layout, outputLayoutData, outputRenderData, inputString, callback);
          } else {
            this._computeAlignmentOffset(style, layout, outputLayoutData);
            this.generateVertexData(isBmFont, style, layout, outputLayoutData, outputRenderData, inputString, callback);
          }
        };
        _proto.setCanvasUsed = function setCanvasUsed(canvas, content) {
          this._canvas = canvas;
          this._context = content;
        };
        _proto._getStyleFontScale = function _getStyleFontScale(fontSize, fontScale) {
          var scale = fontScale;
          if (scale * fontSize > this._maxFontSize && fontSize < this._maxFontSize) {
            scale = this._maxFontSize / fontSize;
          }
          if (scale < 1) {
            scale = 1;
          }
          return scale;
        };
        _proto._calculateLabelFont = function _calculateLabelFont(style, layout, outputLayoutData, inputString) {
          if (!this._context) {
            return;
          }
          style.actualFontSize = style.fontSize * this._fontScale;
          var paragraphedStrings = inputString.split('\n');
          var _splitStrings = outputLayoutData.parsedString = paragraphedStrings;
          var _fontDesc = this._getFontDesc(style.actualFontSize, style.fontFamily, style.isBold, style.isItalic);
          this._context.font = style.fontDesc = _fontDesc;
          switch (layout.overFlow) {
            case Overflow$1.NONE:
              {
                var canvasSizeX = 0;
                var canvasSizeY = 0;
                for (var i = 0; i < paragraphedStrings.length; ++i) {
                  var paraLength = safeMeasureText(this._context, paragraphedStrings[i], _fontDesc);
                  canvasSizeX = canvasSizeX > paraLength ? canvasSizeX : paraLength;
                }
                canvasSizeY = (_splitStrings.length + BASELINE_RATIO) * this._getLineHeight(layout.lineHeight, style.actualFontSize, style.fontSize);
                var rawWidth = canvasSizeX;
                var rawHeight = canvasSizeY;
                outputLayoutData.canvasSize.width = rawWidth + outputLayoutData.canvasPadding.width * this._fontScale;
                outputLayoutData.canvasSize.height = rawHeight + outputLayoutData.canvasPadding.height * this._fontScale;
                outputLayoutData.nodeContentSize.width = (rawWidth + outputLayoutData.contentSizeExtend.width * this._fontScale) / this._fontScale;
                outputLayoutData.nodeContentSize.height = (rawHeight + outputLayoutData.contentSizeExtend.height * this._fontScale) / this._fontScale;
                break;
              }
            case Overflow$1.SHRINK:
              {
                this._calculateShrinkFont(paragraphedStrings, style, layout, outputLayoutData);
                this._calculateWrapText(paragraphedStrings, style, layout, outputLayoutData);
                outputLayoutData.canvasSize.width = outputLayoutData.nodeContentSize.width * this._fontScale;
                outputLayoutData.canvasSize.height = outputLayoutData.nodeContentSize.height * this._fontScale;
                break;
              }
            case Overflow$1.CLAMP:
              {
                this._calculateWrapText(paragraphedStrings, style, layout, outputLayoutData);
                outputLayoutData.canvasSize.width = outputLayoutData.nodeContentSize.width * this._fontScale;
                outputLayoutData.canvasSize.height = outputLayoutData.nodeContentSize.height * this._fontScale;
                break;
              }
            case Overflow$1.RESIZE_HEIGHT:
              {
                this._calculateWrapText(paragraphedStrings, style, layout, outputLayoutData);
                var _rawHeight = (outputLayoutData.parsedString.length + BASELINE_RATIO) * this._getLineHeight(layout.lineHeight, style.actualFontSize, style.fontSize);
                outputLayoutData.canvasSize.width = outputLayoutData.nodeContentSize.width * this._fontScale;
                outputLayoutData.canvasSize.height = _rawHeight + outputLayoutData.canvasPadding.height * this._fontScale;
                outputLayoutData.nodeContentSize.height = (_rawHeight + outputLayoutData.contentSizeExtend.height * this._fontScale) / this._fontScale;
                break;
              }
          }
        };
        _proto._getFontDesc = function _getFontDesc(fontSize, fontFamily, isBold, isItalic) {
          var fontDesc = fontSize.toString() + "px ";
          fontDesc += fontFamily;
          if (isBold) {
            fontDesc = "bold " + fontDesc;
          }
          if (isItalic) {
            fontDesc = "italic " + fontDesc;
          }
          return fontDesc;
        };
        _proto._getLineHeight = function _getLineHeight(lineHeight, fontSize, drawFontsize) {
          var nodeSpacingY = lineHeight;
          if (nodeSpacingY === 0) {
            nodeSpacingY = fontSize;
          } else {
            nodeSpacingY = nodeSpacingY * fontSize / drawFontsize;
          }
          return nodeSpacingY;
        };
        _proto._calculateShrinkFont = function _calculateShrinkFont(paragraphedStrings, style, layout, outputLayoutData) {
          if (!this._context) return;
          var _fontDesc = this._getFontDesc(style.actualFontSize, style.fontFamily, style.isBold, style.isItalic);
          this._context.font = _fontDesc;
          var paragraphLength = this._calculateParagraphLength(paragraphedStrings, this._context, _fontDesc);
          var i = 0;
          var totalHeight = 0;
          var maxLength = 0;
          var _fontSize = style.actualFontSize;
          if (layout.wrapping) {
            var canvasWidthNoMargin = outputLayoutData.nodeContentSize.width * this._fontScale;
            var canvasHeightNoMargin = outputLayoutData.nodeContentSize.height * this._fontScale;
            if (canvasWidthNoMargin < 0 || canvasHeightNoMargin < 0) {
              return;
            }
            totalHeight = canvasHeightNoMargin + 1;
            var actualFontSize = style.actualFontSize + 1;
            var textFragment = [];
            var left = 0;
            var right = actualFontSize | 0;
            var mid = 0;
            while (left < right) {
              mid = left + right + 1 >> 1;
              if (mid <= 0) {
                logID(4003);
                break;
              }
              _fontSize = mid;
              _fontDesc = this._getFontDesc(_fontSize, style.fontFamily, style.isBold, style.isItalic);
              this._context.font = _fontDesc;
              var lineHeight = this._getLineHeight(layout.lineHeight, _fontSize, style.fontSize);
              totalHeight = 0;
              for (i = 0; i < paragraphedStrings.length; ++i) {
                var allWidth = safeMeasureText(this._context, paragraphedStrings[i], _fontDesc);
                textFragment = fragmentText(paragraphedStrings[i], allWidth, canvasWidthNoMargin, this._measureText(this._context, _fontDesc));
                totalHeight += textFragment.length * lineHeight;
              }
              if (totalHeight > canvasHeightNoMargin) {
                right = mid - 1;
              } else {
                left = mid;
              }
            }
            if (left === 0) {
              logID(4003);
            } else {
              _fontSize = left;
              _fontDesc = this._getFontDesc(_fontSize, style.fontFamily, style.isBold, style.isItalic);
              this._context.font = _fontDesc;
            }
          } else {
            totalHeight = paragraphedStrings.length * this._getLineHeight(layout.lineHeight, _fontSize, style.fontSize);
            for (i = 0; i < paragraphedStrings.length; ++i) {
              if (maxLength < paragraphLength[i]) {
                maxLength = paragraphLength[i];
              }
            }
            var scaleX = (outputLayoutData.canvasSize.width - outputLayoutData.canvasPadding.width) * this._fontScale / maxLength;
            var scaleY = outputLayoutData.canvasSize.height * this._fontScale / totalHeight;
            _fontSize = style.actualFontSize * Math.min(1, scaleX, scaleY) | 0;
            _fontDesc = this._getFontDesc(_fontSize, style.fontFamily, style.isBold, style.isItalic);
            this._context.font = _fontDesc;
          }
          style.actualFontSize = _fontSize;
          style.fontDesc = _fontDesc;
        };
        _proto._calculateWrapText = function _calculateWrapText(paragraphedStrings, style, layout, outputLayoutData) {
          if (!layout.wrapping || !this._context) return;
          var _splitStrings = [];
          var canvasWidthNoMargin = outputLayoutData.nodeContentSize.width * this._fontScale;
          var _fontDesc = this._getFontDesc(style.actualFontSize, style.fontFamily, style.isBold, style.isItalic);
          this._context.font = _fontDesc;
          for (var i = 0; i < paragraphedStrings.length; ++i) {
            var allWidth = safeMeasureText(this._context, paragraphedStrings[i], _fontDesc);
            var textFragment = fragmentText(paragraphedStrings[i], allWidth, canvasWidthNoMargin, this._measureText(this._context, _fontDesc));
            _splitStrings = _splitStrings.concat(textFragment);
          }
          outputLayoutData.parsedString = _splitStrings;
          style.fontDesc = _fontDesc;
        };
        _proto._measureText = function _measureText(ctx, fontDesc) {
          return function (str) {
            return safeMeasureText(ctx, str, fontDesc);
          };
        };
        _proto._calculateParagraphLength = function _calculateParagraphLength(paragraphedStrings, ctx, fontDesc) {
          var paragraphLength = [];
          for (var _iterator = _createForOfIteratorHelperLoose(paragraphedStrings), _step; !(_step = _iterator()).done;) {
            var para = _step.value;
            var width = safeMeasureText(ctx, para, fontDesc);
            paragraphLength.push(width);
          }
          return paragraphLength;
        };
        _proto._updatePaddingRect = function _updatePaddingRect(style, outputLayoutData) {
          var top = 0;
          var bottom = 0;
          var left = 0;
          var right = 0;
          var outlineWidth = 0;
          outputLayoutData.contentSizeExtend.width = outputLayoutData.contentSizeExtend.height = 0;
          if (style.isOutlined) {
            outlineWidth = style.outlineWidth;
            top = bottom = left = right = outlineWidth;
            outputLayoutData.contentSizeExtend.width = outputLayoutData.contentSizeExtend.height = outlineWidth * 2;
          }
          if (style.hasShadow) {
            var shadowWidth = style.shadowBlur + outlineWidth;
            var offsetX = style.shadowOffsetX;
            var offsetY = style.shadowOffsetY;
            left = Math.max(left, -offsetX + shadowWidth);
            right = Math.max(right, offsetX + shadowWidth);
            top = Math.max(top, offsetY + shadowWidth);
            bottom = Math.max(bottom, -offsetY + shadowWidth);
          }
          if (style.isItalic) {
            var offset = style.fontSize * Math.tan(12 * 0.0174532925);
            right += offset;
            outputLayoutData.contentSizeExtend.width += offset;
          }
          outputLayoutData.canvasPadding.x = left;
          outputLayoutData.canvasPadding.y = top;
          outputLayoutData.canvasPadding.width = left + right;
          outputLayoutData.canvasPadding.height = top + bottom;
        };
        _proto._updateLabelDimensions = function _updateLabelDimensions(style, layout, outputLayoutData) {
          outputLayoutData.canvasSize.width = Math.min(outputLayoutData.canvasSize.width, MAX_SIZE);
          outputLayoutData.canvasSize.height = Math.min(outputLayoutData.canvasSize.height, MAX_SIZE);
          this._canvas.width = outputLayoutData.canvasSize.width;
          this._canvas.height = outputLayoutData.canvasSize.height;
          this._context.font = style.fontDesc;
          this._context.textAlign = Alignment[layout.horizontalAlign];
          this._context.textBaseline = 'alphabetic';
        };
        _proto._calculateFillTextStartPosition = function _calculateFillTextStartPosition(style, layout, outputLayoutData) {
          var labelX = 0;
          if (layout.horizontalAlign === HorizontalTextAlignment.RIGHT) {
            labelX = outputLayoutData.canvasSize.width - outputLayoutData.canvasPadding.width;
          } else if (layout.horizontalAlign === HorizontalTextAlignment.CENTER) {
            labelX = (outputLayoutData.canvasSize.width - outputLayoutData.canvasPadding.width) / 2;
          }
          var lineHeight = this._getLineHeight(layout.lineHeight, style.actualFontSize, style.fontSize);
          var drawStartY = lineHeight * (outputLayoutData.parsedString.length - 1);
          var firstLinelabelY = style.actualFontSize * (1 - BASELINE_RATIO / 2);
          if (layout.verticalAlign !== VerticalTextAlignment.TOP) {
            var blank = drawStartY + outputLayoutData.canvasPadding.height + style.actualFontSize - outputLayoutData.canvasSize.height;
            if (layout.verticalAlign === VerticalTextAlignment.BOTTOM) {
              blank += BASELINE_RATIO / 2 * style.actualFontSize;
              firstLinelabelY -= blank;
            } else {
              firstLinelabelY -= blank / 2;
            }
          }
          firstLinelabelY += _BASELINE_OFFSET * style.actualFontSize;
          outputLayoutData.startPosition.set(labelX + outputLayoutData.canvasPadding.x, firstLinelabelY + outputLayoutData.canvasPadding.y);
        };
        _proto._updateTexture = function _updateTexture(style, layout, outputLayoutData, outputRenderData) {
          if (!this._context || !this._canvas) {
            return;
          }
          this._context.clearRect(0, 0, this._canvas.width, this._canvas.height);
          this._context.font = style.fontDesc;
          this._calculateFillTextStartPosition(style, layout, outputLayoutData);
          var lineHeight = this._getLineHeight(layout.lineHeight, style.actualFontSize, style.fontSize);
          this._context.lineJoin = 'round';
          if (style.isOutlined) {
            this._context.fillStyle = "rgba(" + style.outlineColor.r + ", " + style.outlineColor.g + ", " + style.outlineColor.b + ", " + _invisibleAlpha + ")";
            this._context.fillRect(0, 0, this._canvas.width, this._canvas.height);
          } else {
            this._context.fillStyle = "rgba(" + style.color.r + ", " + style.color.g + ", " + style.color.b + ", " + _invisibleAlpha + ")";
            this._context.fillRect(0, 0, this._canvas.width, this._canvas.height);
          }
          this._context.fillStyle = "rgb(" + style.color.r + ", " + style.color.g + ", " + style.color.b + ")";
          var tempPos = new Vec2(outputLayoutData.startPosition.x, outputLayoutData.startPosition.y);
          var drawTextPosX = tempPos.x;
          var drawTextPosY = 0;
          this._drawTextEffect(tempPos, lineHeight, style, layout, outputLayoutData);
          for (var i = 0; i < outputLayoutData.parsedString.length; ++i) {
            drawTextPosY = tempPos.y + i * lineHeight;
            if (style.isOutlined) {
              this._context.strokeText(outputLayoutData.parsedString[i], drawTextPosX, drawTextPosY);
            }
            this._context.fillText(outputLayoutData.parsedString[i], drawTextPosX, drawTextPosY);
          }
          if (style.hasShadow) {
            this._context.shadowColor = 'transparent';
          }
          this._uploadTexture(outputRenderData);
        };
        _proto._uploadTexture = function _uploadTexture(outputRenderData) {
          if (outputRenderData.texture && this._canvas) {
            var tex;
            if (outputRenderData.texture instanceof SpriteFrame) {
              tex = outputRenderData.texture.texture;
            } else {
              tex = outputRenderData.texture;
            }
            var uploadAgain = this._canvas.width !== 0 && this._canvas.height !== 0;
            if (uploadAgain) {
              tex.reset({
                width: this._canvas.width,
                height: this._canvas.height,
                mipmapLevel: 1
              });
              tex.uploadData(this._canvas);
              tex.setWrapMode(WrapMode$1.CLAMP_TO_EDGE, WrapMode$1.CLAMP_TO_EDGE);
              if (outputRenderData.texture instanceof SpriteFrame) {
                outputRenderData.texture.rect = new Rect$1(0, 0, this._canvas.width, this._canvas.height);
                outputRenderData.texture._calculateUV();
              }
              if (legacyCC.director.root && legacyCC.director.root.batcher2D) {
                {
                  legacyCC.director.root.batcher2D._releaseDescriptorSetCache(tex.getHash());
                }
              }
            }
          }
        };
        _proto._drawTextEffect = function _drawTextEffect(startPosition, lineHeight, style, layout, outputLayoutData) {
          if (!style.hasShadow && !style.isOutlined && !style.isUnderline) return;
          var isMultiple = outputLayoutData.parsedString.length > 1 && style.hasShadow;
          var measureText = this._measureText(this._context, style.fontDesc);
          var drawTextPosX = 0;
          var drawTextPosY = 0;
          if (style.hasShadow) {
            this._setupShadow(style);
          }
          if (style.isOutlined) {
            this._setupOutline(style);
          }
          for (var i = 0; i < outputLayoutData.parsedString.length; ++i) {
            drawTextPosX = startPosition.x;
            drawTextPosY = startPosition.y + i * lineHeight;
            if (isMultiple) {
              if (style.isOutlined) {
                this._context.strokeText(outputLayoutData.parsedString[i], drawTextPosX, drawTextPosY);
              }
              this._context.fillText(outputLayoutData.parsedString[i], drawTextPosX, drawTextPosY);
            }
            if (style.isUnderline) {
              var _drawUnderlineWidth = measureText(outputLayoutData.parsedString[i]);
              var _drawUnderlinePos = new Vec2();
              if (layout.horizontalAlign === HorizontalTextAlignment.RIGHT) {
                _drawUnderlinePos.x = startPosition.x - _drawUnderlineWidth;
              } else if (layout.horizontalAlign === HorizontalTextAlignment.CENTER) {
                _drawUnderlinePos.x = startPosition.x - _drawUnderlineWidth / 2;
              } else {
                _drawUnderlinePos.x = startPosition.x;
              }
              _drawUnderlinePos.y = drawTextPosY + style.actualFontSize / 8;
              this._context.fillRect(_drawUnderlinePos.x, _drawUnderlinePos.y, _drawUnderlineWidth, style.underlineHeight * this._fontScale);
            }
          }
          if (isMultiple) {
            this._context.shadowColor = 'transparent';
          }
        };
        _proto._setupOutline = function _setupOutline(style) {
          this._context.strokeStyle = "rgba(" + style.outlineColor.r + ", " + style.outlineColor.g + ", " + style.outlineColor.b + ", " + style.outlineColor.a / 255 + ")";
          this._context.lineWidth = style.outlineWidth * 2 * this._fontScale;
        };
        _proto._setupShadow = function _setupShadow(style) {
          var fontScale = this._fontScale;
          this._context.shadowColor = "rgba(" + style.shadowColor.r + ", " + style.shadowColor.g + ", " + style.shadowColor.b + ", " + style.shadowColor.a / 255 + ")";
          this._context.shadowBlur = style.shadowBlur * fontScale;
          this._context.shadowOffsetX = style.shadowOffsetX * fontScale;
          this._context.shadowOffsetY = -style.shadowOffsetY * fontScale;
        };
        _proto.generateVertexData = function generateVertexData(isBmFont, style, layout, outputLayoutData, outputRenderData, inputString, callback) {
          if (!isBmFont) {
            this.updateQuatCount(outputRenderData);
            callback(style, outputLayoutData, outputRenderData);
          } else {
            this._updateQuads(style, layout, outputLayoutData, outputRenderData, inputString, callback);
          }
        };
        _proto.updateQuatCount = function updateQuatCount(outputRenderData) {
          var data = outputRenderData.vertexBuffer;
          var count = outputRenderData.quadCount;
          if (data.length !== count) {
            for (var i = data.length; i < count; i++) {
              data.push({
                x: 0,
                y: 0,
                z: 0,
                u: 0,
                v: 0,
                color: Color$1.WHITE.clone()
              });
            }
            data.length = count;
          }
        };
        _proto._setupBMFontOverflowMetrics = function _setupBMFontOverflowMetrics(layout, outputLayoutData) {
          var newWidth = outputLayoutData.nodeContentSize.width;
          var newHeight = outputLayoutData.nodeContentSize.height;
          if (layout.overFlow === Overflow$1.RESIZE_HEIGHT) {
            newHeight = 0;
          }
          if (layout.overFlow === Overflow$1.NONE) {
            newWidth = 0;
            newHeight = 0;
          }
          layout.textWidthTemp = newWidth;
          layout.textHeightTemp = newHeight;
          layout.textDimensions.width = newWidth;
          layout.textDimensions.height = newHeight;
          layout.maxLineWidth = newWidth;
        };
        _proto._updateFontScale = function _updateFontScale(style) {
          style.bmfontScale = style.actualFontSize / (style.originFontSize * this._fontScale);
        };
        _proto._computeHorizontalKerningForText = function _computeHorizontalKerningForText(style, layout, inputString) {
          var string = inputString;
          var stringLen = string.length;
          if (!style.fntConfig) return;
          var kerningDict = style.fntConfig.kerningDict;
          var horizontalKerning = layout.horizontalKerning;
          if (!kerningDict || kerningDict.length === 0) {
            return;
          }
          var prev = -1;
          for (var i = 0; i < stringLen; ++i) {
            var key = string.charCodeAt(i);
            var kerningAmount = kerningDict[prev << 16 | key & 0xffff] || 0;
            if (i < stringLen - 1) {
              horizontalKerning[i] = kerningAmount;
            } else {
              horizontalKerning[i] = 0;
            }
            prev = key;
          }
        };
        _proto._alignText = function _alignText(style, layout, outputLayoutData, inputString) {
          this._multilineTextWrap(style, layout, outputLayoutData, inputString, this._getFirstWordLen);
          if (layout.overFlow === Overflow$1.SHRINK) {
            if (style.fontSize > 0 && this._isVerticalClamp(style, layout, outputLayoutData, inputString, this)) {
              this._shrinkLabelToContentSize(style, layout, outputLayoutData, inputString, this._isVerticalClamp);
            }
            if (style.fontSize > 0 && this._isHorizontalNeedShrink(layout, outputLayoutData)) {
              this._shrinkLabelToContentSize(style, layout, outputLayoutData, inputString, this._isHorizontalClamp);
            }
          }
          this._parsedString(outputLayoutData, inputString);
        };
        _proto._parsedString = function _parsedString(outputLayoutData, inputString) {
          var _splitStrings = [];
          var textFragment = '';
          for (var i = 0, line = 0, l = inputString.length; i < l; ++i) {
            var letterInfo = this._lettersInfo[i];
            if (!letterInfo.valid) {
              continue;
            }
            if (line === letterInfo.line) {
              textFragment += letterInfo["char"];
            } else {
              _splitStrings = _splitStrings.concat(textFragment);
              line = letterInfo.line;
              textFragment = '';
            }
          }
          _splitStrings = _splitStrings.concat(textFragment);
          outputLayoutData.parsedString = _splitStrings;
        };
        _proto._multilineTextWrap = function _multilineTextWrap(style, layout, outputLayoutData, inputString, nextTokenFunc) {
          layout.linesWidth.length = 0;
          var _string = inputString;
          var textLen = _string.length;
          var lineIndex = 0;
          var nextTokenX = 0;
          var nextTokenY = 0;
          var longestLine = 0;
          var letterRight = 0;
          var highestY = 0;
          var lowestY = 0;
          var letterDef = null;
          var _lineSpacing = 0;
          for (var index = 0; index < textLen;) {
            var character = _string.charAt(index);
            if (character === '\n') {
              layout.linesWidth.push(letterRight);
              letterRight = 0;
              lineIndex++;
              nextTokenX = 0;
              nextTokenY -= layout.lineHeight * this._getFontScale(style, layout) + _lineSpacing;
              this._recordPlaceholderInfo(index, character);
              index++;
              continue;
            }
            var tokenLen = nextTokenFunc(style, layout, _string, index, textLen);
            var tokenHighestY = highestY;
            var tokenLowestY = lowestY;
            var tokenRight = letterRight;
            var nextLetterX = nextTokenX;
            var newLine = false;
            var letterPosition = new Vec2();
            for (var tmp = 0; tmp < tokenLen; ++tmp) {
              var letterIndex = index + tmp;
              character = _string.charAt(letterIndex);
              if (character === '\r') {
                this._recordPlaceholderInfo(letterIndex, character);
                continue;
              }
              letterDef = shareLabelInfo.fontAtlas.getLetterDefinitionForChar(character, shareLabelInfo);
              if (!letterDef) {
                this._recordPlaceholderInfo(letterIndex, character);
                log("Can't find letter definition in texture atlas " + style.fntConfig.atlasName + " for letter:" + character);
                continue;
              }
              var letterX = nextLetterX + letterDef.offsetX * style.bmfontScale - shareLabelInfo.margin;
              if (layout.wrapping && layout.maxLineWidth > 0 && nextTokenX > 0 && letterX + letterDef.w * style.bmfontScale > layout.maxLineWidth && !isUnicodeSpace(character)) {
                layout.linesWidth.push(letterRight);
                letterRight = 0;
                lineIndex++;
                nextTokenX = 0;
                nextTokenY -= layout.lineHeight * this._getFontScale(style, layout) + _lineSpacing;
                newLine = true;
                break;
              } else {
                letterPosition.x = letterX;
              }
              letterPosition.y = nextTokenY - letterDef.offsetY * style.bmfontScale;
              this._recordLetterInfo(letterPosition, character, letterIndex, lineIndex);
              if (letterIndex + 1 < layout.horizontalKerning.length && letterIndex < textLen - 1) {
                nextLetterX += layout.horizontalKerning[letterIndex + 1] * style.bmfontScale;
              }
              nextLetterX += letterDef.xAdvance * style.bmfontScale + layout.spacingX;
              tokenRight = letterPosition.x + letterDef.w * style.bmfontScale;
              if (tokenHighestY < letterPosition.y) {
                tokenHighestY = letterPosition.y;
              }
              if (tokenLowestY > letterPosition.y - letterDef.h * style.bmfontScale) {
                tokenLowestY = letterPosition.y - letterDef.h * style.bmfontScale;
              }
            }
            if (newLine) {
              continue;
            }
            nextTokenX = nextLetterX;
            letterRight = tokenRight;
            if (highestY < tokenHighestY) {
              highestY = tokenHighestY;
            }
            if (lowestY > tokenLowestY) {
              lowestY = tokenLowestY;
            }
            if (longestLine < letterRight) {
              longestLine = letterRight;
            }
            index += tokenLen;
          }
          layout.linesWidth.push(letterRight);
          layout.numberOfLines = lineIndex + 1;
          layout.textDesiredHeight = layout.numberOfLines * layout.lineHeight * this._getFontScale(style, layout);
          if (layout.numberOfLines > 1) {
            layout.textDesiredHeight += (layout.numberOfLines - 1) * _lineSpacing;
          }
          outputLayoutData.nodeContentSize.width = layout.textWidthTemp;
          outputLayoutData.nodeContentSize.height = layout.textHeightTemp;
          if (layout.textWidthTemp <= 0) {
            outputLayoutData.nodeContentSize.width = parseFloat(longestLine.toFixed(2)) + shareLabelInfo.margin * 2;
          }
          if (layout.textHeightTemp <= 0) {
            outputLayoutData.nodeContentSize.height = parseFloat(layout.textDesiredHeight.toFixed(2)) + shareLabelInfo.margin * 2;
          }
          layout.tailoredTopY = outputLayoutData.nodeContentSize.height;
          layout.tailoredBottomY = 0;
          if (highestY > 0) {
            layout.tailoredTopY = outputLayoutData.nodeContentSize.height + highestY;
          }
          if (lowestY < -layout.textDesiredHeight) {
            layout.tailoredBottomY = layout.textDesiredHeight + lowestY;
          }
          return true;
        };
        _proto._recordPlaceholderInfo = function _recordPlaceholderInfo(letterIndex, _char) {
          if (letterIndex >= this._lettersInfo.length) {
            var tmpInfo = new LetterInfo();
            this._lettersInfo.push(tmpInfo);
          }
          this._lettersInfo[letterIndex]["char"] = _char;
          this._lettersInfo[letterIndex].hash = "" + _char.charCodeAt(0) + shareLabelInfo.hash;
          this._lettersInfo[letterIndex].valid = false;
        };
        _proto._recordLetterInfo = function _recordLetterInfo(letterPosition, character, letterIndex, lineIndex) {
          if (letterIndex >= this._lettersInfo.length) {
            var tmpInfo = new LetterInfo();
            this._lettersInfo.push(tmpInfo);
          }
          var _char2 = character.charCodeAt(0);
          var key = "" + _char2 + shareLabelInfo.hash;
          this._lettersInfo[letterIndex].line = lineIndex;
          this._lettersInfo[letterIndex]["char"] = character;
          this._lettersInfo[letterIndex].hash = key;
          this._lettersInfo[letterIndex].valid = shareLabelInfo.fontAtlas.getLetter(key).valid;
          this._lettersInfo[letterIndex].x = letterPosition.x;
          this._lettersInfo[letterIndex].y = letterPosition.y;
        };
        _proto._getFirstWordLen = function _getFirstWordLen(style, layout, text, startIndex, textLen) {
          var character = text.charAt(startIndex);
          if (isUnicodeCJK(character) || character === '\n' || isUnicodeSpace(character)) {
            return 1;
          }
          var len = 1;
          var letterDef = shareLabelInfo.fontAtlas.getLetterDefinitionForChar(character, shareLabelInfo);
          if (!letterDef) {
            return len;
          }
          var nextLetterX = letterDef.xAdvance * style.bmfontScale + layout.spacingX;
          var letterX = 0;
          for (var index = startIndex + 1; index < textLen; ++index) {
            character = text.charAt(index);
            letterDef = shareLabelInfo.fontAtlas.getLetterDefinitionForChar(character, shareLabelInfo);
            if (!letterDef) {
              break;
            }
            letterX = nextLetterX + letterDef.offsetX * style.bmfontScale;
            if (letterX + letterDef.w * style.bmfontScale > layout.maxLineWidth && !isUnicodeSpace(character) && layout.maxLineWidth > 0) {
              return len;
            }
            nextLetterX += letterDef.xAdvance * style.bmfontScale + layout.spacingX;
            if (character === '\n' || isUnicodeSpace(character) || isUnicodeCJK(character)) {
              break;
            }
            len++;
          }
          return len;
        };
        _proto._computeAlignmentOffset = function _computeAlignmentOffset(style, layout, outputLayoutData) {
          layout.linesOffsetX.length = 0;
          layout.letterOffsetY = 0;
          switch (layout.horizontalAlign) {
            case HorizontalTextAlignment.LEFT:
              for (var i = 0; i < layout.numberOfLines; ++i) {
                layout.linesOffsetX.push(0);
              }
              break;
            case HorizontalTextAlignment.CENTER:
              for (var _i = 0, l = layout.linesWidth.length; _i < l; _i++) {
                layout.linesOffsetX.push((outputLayoutData.nodeContentSize.width - layout.linesWidth[_i]) / 2);
              }
              break;
            case HorizontalTextAlignment.RIGHT:
              for (var _i2 = 0, _l = layout.linesWidth.length; _i2 < _l; _i2++) {
                layout.linesOffsetX.push(outputLayoutData.nodeContentSize.width - layout.linesWidth[_i2]);
              }
              break;
          }
          layout.letterOffsetY = outputLayoutData.nodeContentSize.height;
          if (layout.verticalAlign !== VerticalTextAlignment.TOP) {
            var blank = outputLayoutData.nodeContentSize.height - layout.textDesiredHeight + layout.lineHeight * this._getFontScale(style, layout) - style.originFontSize * this._fontScale * style.bmfontScale;
            if (layout.verticalAlign === VerticalTextAlignment.BOTTOM) {
              layout.letterOffsetY -= blank;
            } else {
              layout.letterOffsetY -= blank / 2;
            }
          }
        };
        _proto._getFontScale = function _getFontScale(style, layout) {
          return layout.overFlow === Overflow$1.SHRINK ? style.bmfontScale : 1;
        };
        _proto._isVerticalClamp = function _isVerticalClamp(style, layout, outputLayoutData, inputString, process) {
          if (layout.textDesiredHeight > outputLayoutData.nodeContentSize.height) {
            return true;
          } else {
            return false;
          }
        };
        _proto._isHorizontalClamp = function _isHorizontalClamp(style, layout, outputLayoutData, inputString, process) {
          var letterClamp = false;
          var _string = inputString;
          for (var ctr = 0, l = _string.length; ctr < l; ++ctr) {
            var letterInfo = process._lettersInfo[ctr];
            if (letterInfo.valid) {
              var letterDef = shareLabelInfo.fontAtlas.getLetterDefinitionForChar(letterInfo["char"], shareLabelInfo);
              if (!letterDef) {
                continue;
              }
              var px = letterInfo.x + letterDef.w * style.bmfontScale;
              var lineIndex = letterInfo.line;
              if (layout.textWidthTemp > 0) {
                if (!layout.wrapping) {
                  if (px > outputLayoutData.nodeContentSize.width) {
                    letterClamp = true;
                    break;
                  }
                } else {
                  var wordWidth = layout.linesWidth[lineIndex];
                  if (wordWidth > outputLayoutData.nodeContentSize.width && (px > outputLayoutData.nodeContentSize.width || px < 0)) {
                    letterClamp = true;
                    break;
                  }
                }
              }
            }
          }
          return letterClamp;
        };
        _proto._isHorizontalNeedShrink = function _isHorizontalNeedShrink(layout, outputLayoutData) {
          var wordWidth = 0;
          for (var ctr = 0, l = layout.linesWidth.length; ctr < l; ++ctr) {
            wordWidth = layout.linesWidth[ctr];
            if (wordWidth > outputLayoutData.nodeContentSize.width) return true;
          }
          return false;
        };
        _proto._shrinkLabelToContentSize = function _shrinkLabelToContentSize(style, layout, outputLayoutData, inputString, lambda) {
          var fontSize = style.actualFontSize;
          var left = 0;
          var right = fontSize | 0;
          var mid = 0;
          while (left < right) {
            mid = left + right + 1 >> 1;
            var newFontSize = mid;
            if (newFontSize <= 0) {
              break;
            }
            style.bmfontScale = newFontSize / (style.originFontSize * this._fontScale);
            this._multilineTextWrap(style, layout, outputLayoutData, inputString, this._getFirstWordLen);
            this._computeAlignmentOffset(style, layout, outputLayoutData);
            if (lambda(style, layout, outputLayoutData, inputString, this)) {
              right = mid - 1;
            } else {
              left = mid;
            }
          }
          if (left >= 0) {
            this._scaleFontSizeDown(style, layout, outputLayoutData, inputString, left);
          }
        };
        _proto._scaleFontSizeDown = function _scaleFontSizeDown(style, layout, outputLayoutData, inputString, fontSize) {
          var shouldUpdateContent = true;
          if (!fontSize) {
            fontSize = 0.1;
            shouldUpdateContent = false;
          }
          style.actualFontSize = fontSize;
          if (shouldUpdateContent) {
            this._updateFontScale(style);
            this._multilineTextWrap(style, layout, outputLayoutData, inputString, this._getFirstWordLen);
          }
        };
        _proto._updateQuads = function _updateQuads(style, layout, outputLayoutData, outputRenderData, inputString, callback) {
          var texture = style.spriteFrame ? style.spriteFrame.texture : shareLabelInfo.fontAtlas.getTexture();
          var appX = outputRenderData.uiTransAnchorX * outputLayoutData.nodeContentSize.width;
          var appY = outputRenderData.uiTransAnchorY * outputLayoutData.nodeContentSize.height;
          var ret = true;
          for (var ctr = 0, l = inputString.length; ctr < l; ++ctr) {
            var letterInfo = this._lettersInfo[ctr];
            if (!letterInfo.valid) {
              continue;
            }
            var letterDef = shareLabelInfo.fontAtlas.getLetter(letterInfo.hash);
            if (!letterDef) {
              warn('Can\'t find letter in this bitmap-font');
              continue;
            }
            this._tmpRect.height = letterDef.h;
            this._tmpRect.width = letterDef.w;
            this._tmpRect.x = letterDef.u;
            this._tmpRect.y = letterDef.v;
            var py = letterInfo.y + layout.letterOffsetY;
            if (layout.textHeightTemp > 0) {
              if (py > layout.tailoredTopY) {
                var clipTop = py - layout.tailoredTopY;
                this._tmpRect.y += clipTop;
                this._tmpRect.height -= clipTop;
                py -= clipTop;
              }
              if (py - this._tmpRect.height * style.bmfontScale < layout.tailoredBottomY && layout.overFlow === Overflow$1.CLAMP) {
                this._tmpRect.height = py < layout.tailoredBottomY ? 0 : (py - layout.tailoredBottomY) / style.bmfontScale;
              }
            }
            var lineIndex = letterInfo.line;
            var px = letterInfo.x + letterDef.w / 2 * style.bmfontScale + layout.linesOffsetX[lineIndex];
            if (layout.textWidthTemp > 0) {
              if (this._isHorizontalClamped(layout, outputLayoutData, px, lineIndex)) {
                if (layout.overFlow === Overflow$1.CLAMP) {
                  this._tmpRect.width = 0;
                }
              }
            }
            if (this._tmpRect.height > 0 && this._tmpRect.width > 0) {
              var isRotated = this._determineRect(style);
              var letterPositionX = letterInfo.x + layout.linesOffsetX[letterInfo.line];
              var offset = outputRenderData.quadCount;
              outputRenderData.quadCount += 4;
              this.updateQuatCount(outputRenderData);
              callback(style, outputLayoutData, outputRenderData, offset, texture, this._tmpRect, isRotated, letterPositionX - appX, py - appY);
            }
          }
          return ret;
        };
        _proto._isHorizontalClamped = function _isHorizontalClamped(layout, outputLayoutData, px, lineIndex) {
          var wordWidth = layout.linesWidth[lineIndex];
          var letterOverClamp = px > outputLayoutData.nodeContentSize.width || px < 0;
          if (!layout.wrapping) {
            return letterOverClamp;
          } else {
            return wordWidth > outputLayoutData.nodeContentSize.width && letterOverClamp;
          }
        };
        _proto._determineRect = function _determineRect(style) {
          var _spriteFrame = style.spriteFrame;
          if (!_spriteFrame) return false;
          var isRotated = _spriteFrame.isRotated();
          var originalSize = _spriteFrame.getOriginalSize();
          var rect = _spriteFrame.getRect();
          var offset = _spriteFrame.getOffset();
          var trimmedLeft = offset.x + (originalSize.width - rect.width) / 2;
          var trimmedTop = offset.y - (originalSize.height - rect.height) / 2;
          if (!isRotated) {
            this._tmpRect.x += rect.x - trimmedLeft;
            this._tmpRect.y += rect.y + trimmedTop;
          } else {
            var originalX = this._tmpRect.x;
            this._tmpRect.x = rect.x + rect.height - this._tmpRect.y - this._tmpRect.height - trimmedTop;
            this._tmpRect.y = originalX + rect.y - trimmedLeft;
            if (this._tmpRect.y < 0) {
              this._tmpRect.height += trimmedTop;
            }
          }
          return isRotated;
        };
        return TextProcessing;
      }();
      TextProcessing.instance = void 0;
      TextProcessing.instance = new TextProcessing();

      var _defaultLetterAtlas = new LetterAtlas(64, 64);
      var _defaultFontAtlas = new FontAtlas(null);
      var _comp = null;
      var _uiTrans = null;
      var _fntConfig = null;
      var _spriteFrame = null;
      var QUAD_INDICES$5;
      var bmfontUtils = {
        updateProcessingData: function updateProcessingData(style, layout, outputLayoutData, outputRenderData, comp, trans) {
          style.fontSize = comp.fontSize;
          style.actualFontSize = comp.fontSize;
          style.originFontSize = _fntConfig ? _fntConfig.fontSize : comp.fontSize;
          layout.horizontalAlign = comp.horizontalAlign;
          layout.verticalAlign = comp.verticalAlign;
          layout.spacingX = comp.spacingX;
          var overflow = comp.overflow;
          layout.overFlow = overflow;
          layout.lineHeight = comp.lineHeight;
          outputLayoutData.nodeContentSize.width = trans.width;
          outputLayoutData.nodeContentSize.height = trans.height;
          if (overflow === Overflow$1.NONE) {
            layout.wrapping = false;
            outputLayoutData.nodeContentSize.width += shareLabelInfo.margin * 2;
            outputLayoutData.nodeContentSize.height += shareLabelInfo.margin * 2;
          } else if (overflow === Overflow$1.RESIZE_HEIGHT) {
            layout.wrapping = true;
            outputLayoutData.nodeContentSize.height += shareLabelInfo.margin * 2;
          } else {
            layout.wrapping = comp.enableWrapText;
          }
          outputRenderData.uiTransAnchorX = trans.anchorX;
          outputRenderData.uiTransAnchorY = trans.anchorY;
          shareLabelInfo.lineHeight = comp.lineHeight;
          shareLabelInfo.fontSize = comp.fontSize;
          style.spriteFrame = _spriteFrame;
          style.fntConfig = _fntConfig;
          style.fontFamily = shareLabelInfo.fontFamily;
          style.color.set(comp.color);
        },
        updateRenderData: function updateRenderData(comp) {
          if (!comp.renderData) {
            return;
          }
          if (_comp === comp) {
            return;
          }
          if (comp.renderData.vertDirty) {
            _comp = comp;
            _uiTrans = _comp.node._uiProps.uiTransformComp;
            var renderData = comp.renderData;
            var processing = TextProcessing.instance;
            var style = comp.textStyle;
            var layout = comp.textLayout;
            var outputLayoutData = comp.textLayoutData;
            var outputRenderData = comp.textRenderData;
            style.fontScale = view.getScaleX();
            this._updateFontFamily(comp);
            this.updateProcessingData(style, layout, outputLayoutData, outputRenderData, comp, _uiTrans);
            this._updateLabelInfo(comp);
            style.fontDesc = shareLabelInfo.fontDesc;
            processing.processingString(true, style, layout, outputLayoutData, comp.string);
            this.resetRenderData(comp);
            outputRenderData.quadCount = 0;
            processing.generateRenderInfo(true, style, layout, outputLayoutData, outputRenderData, comp.string, this.generateVertexData);
            renderData.dataLength = outputRenderData.quadCount;
            renderData.resize(renderData.dataLength, renderData.dataLength / 2 * 3);
            var datalist = renderData.data;
            for (var i = 0, l = outputRenderData.quadCount; i < l; i++) {
              datalist[i] = outputRenderData.vertexBuffer[i];
            }
            var indexCount = renderData.indexCount;
            this.createQuadIndices(indexCount);
            renderData.chunk.setIndexBuffer(QUAD_INDICES$5);
            _comp.actualFontSize = style.actualFontSize;
            _uiTrans.setContentSize(outputLayoutData.nodeContentSize);
            this.updateUVs(comp);
            this.updateColor(comp);
            renderData.vertDirty = false;
            _comp = null;
            this._resetProperties();
          }
          if (comp.spriteFrame) {
            var _renderData = comp.renderData;
            _renderData.updateRenderData(comp, comp.spriteFrame);
          }
        },
        updateUVs: function updateUVs(label) {
          var renderData = label.renderData;
          var vData = renderData.chunk.vb;
          var vertexCount = renderData.vertexCount;
          var dataList = renderData.data;
          var vertexOffset = 3;
          for (var i = 0; i < vertexCount; i++) {
            var vert = dataList[i];
            vData[vertexOffset] = vert.u;
            vData[vertexOffset + 1] = vert.v;
            vertexOffset += 9;
          }
        },
        updateColor: function updateColor(label) {
        },
        resetRenderData: function resetRenderData(comp) {
          var renderData = comp.renderData;
          renderData.dataLength = 0;
          renderData.resize(0, 0);
        },
        generateVertexData: function generateVertexData(style, outputLayoutData, outputRenderData, offset, spriteFrame, rect, rotated, x, y) {
          var dataOffset = offset;
          var scale = style.bmfontScale;
          var dataList = outputRenderData.vertexBuffer;
          var texW = spriteFrame.width;
          var texH = spriteFrame.height;
          var rectWidth = rect.width;
          var rectHeight = rect.height;
          var l = 0;
          var b = 0;
          var t = 0;
          var r = 0;
          if (!rotated) {
            l = rect.x / texW;
            r = (rect.x + rectWidth) / texW;
            b = (rect.y + rectHeight) / texH;
            t = rect.y / texH;
            dataList[dataOffset].u = l;
            dataList[dataOffset].v = b;
            dataList[dataOffset + 1].u = r;
            dataList[dataOffset + 1].v = b;
            dataList[dataOffset + 2].u = l;
            dataList[dataOffset + 2].v = t;
            dataList[dataOffset + 3].u = r;
            dataList[dataOffset + 3].v = t;
          } else {
            l = rect.x / texW;
            r = (rect.x + rectHeight) / texW;
            b = (rect.y + rectWidth) / texH;
            t = rect.y / texH;
            dataList[dataOffset].u = l;
            dataList[dataOffset].v = t;
            dataList[dataOffset + 1].u = l;
            dataList[dataOffset + 1].v = b;
            dataList[dataOffset + 2].u = r;
            dataList[dataOffset + 2].v = t;
            dataList[dataOffset + 3].u = r;
            dataList[dataOffset + 3].v = b;
          }
          dataList[dataOffset].x = x;
          dataList[dataOffset].y = y - rectHeight * scale;
          dataList[dataOffset + 1].x = x + rectWidth * scale;
          dataList[dataOffset + 1].y = y - rectHeight * scale;
          dataList[dataOffset + 2].x = x;
          dataList[dataOffset + 2].y = y;
          dataList[dataOffset + 3].x = x + rectWidth * scale;
          dataList[dataOffset + 3].y = y;
        },
        _updateFontFamily: function _updateFontFamily(comp) {
          var fontAsset = comp.font;
          _spriteFrame = fontAsset.spriteFrame;
          _fntConfig = fontAsset.fntConfig;
          shareLabelInfo.fontAtlas = fontAsset.fontDefDictionary;
          if (!shareLabelInfo.fontAtlas) {
            if (comp.cacheMode === CacheMode.CHAR) {
              shareLabelInfo.fontAtlas = _defaultLetterAtlas;
            } else {
              shareLabelInfo.fontAtlas = _defaultFontAtlas;
            }
          }
          dynamicAtlasManager.packToDynamicAtlas(comp, _spriteFrame);
        },
        _updateLabelInfo: function _updateLabelInfo(comp) {
          shareLabelInfo.hash = '';
          shareLabelInfo.margin = 0;
        },
        _resetProperties: function _resetProperties() {
          _fntConfig = null;
          _spriteFrame = null;
          shareLabelInfo.hash = '';
          shareLabelInfo.margin = 0;
        },
        createQuadIndices: function createQuadIndices(indexCount) {
          if (indexCount % 6 !== 0) {
            console.error('illegal index count!');
            return;
          }
          var quadCount = indexCount / 6;
          QUAD_INDICES$5 = null;
          QUAD_INDICES$5 = new Uint16Array(indexCount);
          var offset = 0;
          for (var i = 0; i < quadCount; i++) {
            QUAD_INDICES$5[offset++] = 0 + i * 4;
            QUAD_INDICES$5[offset++] = 1 + i * 4;
            QUAD_INDICES$5[offset++] = 2 + i * 4;
            QUAD_INDICES$5[offset++] = 1 + i * 4;
            QUAD_INDICES$5[offset++] = 3 + i * 4;
            QUAD_INDICES$5[offset++] = 2 + i * 4;
          }
        }
      };

      var tempColor$1 = new Color$1(255, 255, 255, 255);
      var bmfont = {
        createData: function createData(comp) {
          var renderData = comp.requestRenderData();
          renderData.resize(0, 0);
          return renderData;
        },
        fillBuffers: function fillBuffers(comp, renderer) {
          var node = comp.node;
          tempColor$1.set(comp.color);
          tempColor$1.a = node._uiProps.opacity * 255;
          fillMeshVertices3D(node, renderer, comp.renderData, tempColor$1);
        },
        appendQuad: function appendQuad(comp, spriteFrame, rect, rotated, x, y, scale) {
          var renderData = comp.renderData;
          if (!renderData) {
            return;
          }
          var dataOffset = renderData.dataLength;
          renderData.dataLength += 4;
          renderData.resize(renderData.dataLength, renderData.dataLength / 2 * 3);
          var dataList = renderData.data;
          var texW = spriteFrame.width;
          var texH = spriteFrame.height;
          var rectWidth = rect.width;
          var rectHeight = rect.height;
          var l = 0;
          var b = 0;
          var t = 0;
          var r = 0;
          if (!rotated) {
            l = rect.x / texW;
            r = (rect.x + rectWidth) / texW;
            b = (rect.y + rectHeight) / texH;
            t = rect.y / texH;
            dataList[dataOffset].u = l;
            dataList[dataOffset].v = b;
            dataList[dataOffset + 1].u = r;
            dataList[dataOffset + 1].v = b;
            dataList[dataOffset + 2].u = l;
            dataList[dataOffset + 2].v = t;
            dataList[dataOffset + 3].u = r;
            dataList[dataOffset + 3].v = t;
          } else {
            l = rect.x / texW;
            r = (rect.x + rectHeight) / texW;
            b = (rect.y + rectWidth) / texH;
            t = rect.y / texH;
            dataList[dataOffset].u = l;
            dataList[dataOffset].v = t;
            dataList[dataOffset + 1].u = l;
            dataList[dataOffset + 1].v = b;
            dataList[dataOffset + 2].u = r;
            dataList[dataOffset + 2].v = t;
            dataList[dataOffset + 3].u = r;
            dataList[dataOffset + 3].v = b;
          }
          dataList[dataOffset].x = x;
          dataList[dataOffset].y = y - rectHeight * scale;
          dataList[dataOffset + 1].x = x + rectWidth * scale;
          dataList[dataOffset + 1].y = y - rectHeight * scale;
          dataList[dataOffset + 2].x = x;
          dataList[dataOffset + 2].y = y;
          dataList[dataOffset + 3].x = x + rectWidth * scale;
          dataList[dataOffset + 3].y = y;
        }
      };
      addon(bmfont, bmfontUtils);

      var _atlasWidth = 1024;
      var _atlasHeight = 1024;
      var _shareAtlas = null;
      var letterFont = mixin(bmfontUtils, {
        getAssemblerData: function getAssemblerData() {
          if (!_shareAtlas) {
            _shareAtlas = new LetterAtlas(_atlasWidth, _atlasHeight);
          }
          return _shareAtlas.getTexture();
        },
        _updateFontFamily: function _updateFontFamily(comp) {
          shareLabelInfo.fontAtlas = _shareAtlas;
          shareLabelInfo.fontFamily = this._getFontFamily(comp);
          var outline = comp.getComponent(LabelOutline);
          if (outline && outline.enabled) {
            shareLabelInfo.isOutlined = true;
            shareLabelInfo.margin = outline.width;
            shareLabelInfo.out = outline.color.clone();
            shareLabelInfo.out.a = outline.color.a * comp.color.a / 255.0;
          } else {
            shareLabelInfo.isOutlined = false;
            shareLabelInfo.margin = 0;
          }
        },
        _getFontFamily: function _getFontFamily(comp) {
          var fontFamily = 'Arial';
          if (!comp.useSystemFont) {
            if (comp.font) {
              fontFamily = comp.font._nativeAsset || 'Arial';
            }
          } else {
            fontFamily = comp.fontFamily || 'Arial';
          }
          return fontFamily;
        },
        _updateLabelInfo: function _updateLabelInfo(comp) {
          shareLabelInfo.fontDesc = this._getFontDesc();
          shareLabelInfo.color = comp.color;
          shareLabelInfo.hash = computeHash(shareLabelInfo);
        },
        _getFontDesc: function _getFontDesc() {
          var fontDesc = shareLabelInfo.fontSize.toString() + "px ";
          fontDesc += shareLabelInfo.fontFamily;
          return fontDesc;
        }
      });

      var tempColor = new Color$1(255, 255, 255, 255);
      var letter = {
        createData: function createData(comp) {
          var renderData = comp.requestRenderData();
          renderData.resize(0, 0);
          return renderData;
        },
        fillBuffers: function fillBuffers(comp, renderer) {
          if (!comp.renderData) {
            return;
          }
          var node = comp.node;
          tempColor.a = node._uiProps.opacity * 255;
          fillMeshVertices3D(node, renderer, comp.renderData, tempColor);
        },
        updateColor: function updateColor(label) {
        }
      };
      addon(letter, letterFont);

      var Overflow = Label.Overflow;
      var ttfUtils = {
        updateProcessingData: function updateProcessingData(style, layout, outputLayoutData, outputRenderData, comp, trans) {
          style.isSystemFontUsed = comp.useSystemFont;
          style.fontSize = comp.fontSize;
          outputLayoutData.nodeContentSize.width = outputLayoutData.canvasSize.width = trans.width;
          outputLayoutData.nodeContentSize.height = outputLayoutData.canvasSize.height = trans.height;
          layout.lineHeight = comp.lineHeight;
          layout.overFlow = comp.overflow;
          if (comp.overflow === Overflow.NONE) {
            layout.wrapping = false;
          } else if (comp.overflow === Overflow.RESIZE_HEIGHT) {
            layout.wrapping = true;
          } else {
            layout.wrapping = comp.enableWrapText;
          }
          style.isBold = comp.isBold;
          style.isItalic = comp.isItalic;
          style.isUnderline = comp.isUnderline;
          style.underlineHeight = comp.underlineHeight;
          var outlineComp = LabelOutline && comp.getComponent(LabelOutline);
          outlineComp = outlineComp && outlineComp.enabled && outlineComp.width > 0 ? outlineComp : null;
          if (outlineComp) {
            style.isOutlined = true;
            style.outlineColor.set(outlineComp.color);
            style.outlineWidth = outlineComp.width;
          } else {
            style.isOutlined = false;
          }
          var shadowComp = LabelShadow && comp.getComponent(LabelShadow);
          shadowComp = shadowComp && shadowComp.enabled ? shadowComp : null;
          if (shadowComp) {
            style.hasShadow = true;
            style.shadowColor.set(shadowComp.color);
            style.shadowBlur = shadowComp.blur;
            style.shadowOffsetX = shadowComp.offset.x;
            style.shadowOffsetY = shadowComp.offset.y;
          } else {
            style.hasShadow = false;
          }
          style.color.set(comp.color);
          outputRenderData.texture = comp.spriteFrame;
          outputRenderData.uiTransAnchorX = trans.anchorX;
          outputRenderData.uiTransAnchorY = trans.anchorY;
          layout.horizontalAlign = comp.horizontalAlign;
          layout.verticalAlign = comp.verticalAlign;
        },
        getAssemblerData: function getAssemblerData() {
          var sharedLabelData = Label._canvasPool.get();
          sharedLabelData.canvas.width = sharedLabelData.canvas.height = 1;
          return sharedLabelData;
        },
        resetAssemblerData: function resetAssemblerData(assemblerData) {
          if (assemblerData) {
            Label._canvasPool.put(assemblerData);
          }
        },
        updateRenderData: function updateRenderData(comp) {
          if (!comp.renderData) {
            return;
          }
          if (comp.renderData.vertDirty) {
            var trans = comp.node._uiProps.uiTransformComp;
            var processing = TextProcessing.instance;
            var style = comp.textStyle;
            var layout = comp.textLayout;
            var outputLayoutData = comp.textLayoutData;
            var outputRenderData = comp.textRenderData;
            style.fontScale = view.getScaleX();
            this.updateProcessingData(style, layout, outputLayoutData, outputRenderData, comp, trans);
            processing.setCanvasUsed(comp.assemblerData.canvas, comp.assemblerData.context);
            style.fontFamily = this._updateFontFamily(comp);
            this._resetDynamicAtlas(comp);
            processing.processingString(false, style, layout, outputLayoutData, comp.string);
            processing.generateRenderInfo(false, style, layout, outputLayoutData, outputRenderData, comp.string, this.generateVertexData);
            var renderData = comp.renderData;
            renderData.textureDirty = true;
            this._calDynamicAtlas(comp, outputLayoutData);
            comp.actualFontSize = style.actualFontSize;
            trans.setContentSize(outputLayoutData.nodeContentSize);
            var datalist = renderData.data;
            datalist[0] = outputRenderData.vertexBuffer[0];
            datalist[1] = outputRenderData.vertexBuffer[1];
            datalist[2] = outputRenderData.vertexBuffer[2];
            datalist[3] = outputRenderData.vertexBuffer[3];
            this.updateUVs(comp);
            comp.renderData.vertDirty = false;
            comp.contentWidth = outputLayoutData.nodeContentSize.width;
          }
          if (comp.spriteFrame) {
            var _renderData = comp.renderData;
            _renderData.updateRenderData(comp, comp.spriteFrame);
          }
        },
        generateVertexData: function generateVertexData(style, outputLayoutData, outputRenderData) {
          var data = outputRenderData.vertexBuffer;
          var width = outputLayoutData.nodeContentSize.width;
          var height = outputLayoutData.nodeContentSize.height;
          var appX = outputRenderData.uiTransAnchorX * width;
          var appY = outputRenderData.uiTransAnchorY * height;
          data[0].x = -appX;
          data[0].y = -appY;
          data[1].x = width - appX;
          data[1].y = -appY;
          data[2].x = -appX;
          data[2].y = height - appY;
          data[3].x = width - appX;
          data[3].y = height - appY;
        },
        updateVertexData: function updateVertexData(comp) {},
        updateUVs: function updateUVs(comp) {},
        _updateFontFamily: function _updateFontFamily(comp) {
          var _fontFamily = '';
          if (!comp.useSystemFont) {
            if (comp.font) {
              _fontFamily = comp.font._nativeAsset || 'Arial';
            } else {
              _fontFamily = 'Arial';
            }
          } else {
            _fontFamily = comp.fontFamily || 'Arial';
          }
          return _fontFamily;
        },
        _calDynamicAtlas: function _calDynamicAtlas(comp, outputLayoutData) {
          if (comp.cacheMode !== Label.CacheMode.BITMAP || outputLayoutData.canvasSize.width <= 0 || outputLayoutData.canvasSize.height <= 0) return;
          var frame = comp.ttfSpriteFrame;
          dynamicAtlasManager.packToDynamicAtlas(comp, frame);
        },
        _resetDynamicAtlas: function _resetDynamicAtlas(comp) {
          if (comp.cacheMode !== Label.CacheMode.BITMAP) return;
          var frame = comp.ttfSpriteFrame;
          dynamicAtlasManager.deleteAtlasSpriteFrame(frame);
          frame._resetDynamicAtlasFrame();
        }
      };

      var WHITE = Color$1.WHITE.clone();
      var QUAD_INDICES$4 = Uint16Array.from([0, 1, 2, 1, 3, 2]);
      var ttf = {
        createData: function createData(comp) {
          var renderData = comp.requestRenderData();
          renderData.dataLength = 4;
          renderData.resize(4, 6);
          comp.textRenderData.quadCount = 4;
          var vData = renderData.chunk.vb;
          vData[3] = vData[21] = vData[22] = vData[31] = 0;
          vData[4] = vData[12] = vData[13] = vData[30] = 1;
          var offset = 5;
          for (var i = 0; i < 4; i++) {
            Color$1.toArray(vData, WHITE, offset);
            offset += 9;
          }
          renderData.chunk.setIndexBuffer(QUAD_INDICES$4);
          return renderData;
        },
        fillBuffers: function fillBuffers(comp, renderer) {
          var renderData = comp.renderData;
          var chunk = renderData.chunk;
          var dataList = renderData.data;
          var node = comp.node;
          var vData = chunk.vb;
          var m = node.worldMatrix;
          var stride = renderData.floatStride;
          var offset = 0;
          var length = dataList.length;
          for (var i = 0; i < length; i++) {
            var curData = dataList[i];
            var x = curData.x;
            var y = curData.y;
            var rhw = m.m03 * x + m.m07 * y + m.m15;
            rhw = rhw ? 1 / rhw : 1;
            offset = i * stride;
            vData[offset + 0] = (m.m00 * x + m.m04 * y + m.m12) * rhw;
            vData[offset + 1] = (m.m01 * x + m.m05 * y + m.m13) * rhw;
            vData[offset + 2] = (m.m02 * x + m.m06 * y + m.m14) * rhw;
          }
          var vid = chunk.vertexOffset;
          var meshBuffer = chunk.meshBuffer;
          var ib = chunk.meshBuffer.iData;
          var indexOffset = meshBuffer.indexOffset;
          ib[indexOffset++] = vid;
          ib[indexOffset++] = vid + 1;
          ib[indexOffset++] = vid + 2;
          ib[indexOffset++] = vid + 2;
          ib[indexOffset++] = vid + 1;
          ib[indexOffset++] = vid + 3;
          meshBuffer.indexOffset += 6;
        },
        updateVertexData: function updateVertexData(comp) {
          var renderData = comp.renderData;
          if (!renderData) {
            return;
          }
          var uiTrans = comp.node._uiProps.uiTransformComp;
          var width = uiTrans.width;
          var height = uiTrans.height;
          var appX = uiTrans.anchorX * width;
          var appY = uiTrans.anchorY * height;
          var data = renderData.data;
          data[0].x = -appX;
          data[0].y = -appY;
          data[1].x = width - appX;
          data[1].y = -appY;
          data[2].x = -appX;
          data[2].y = height - appY;
          data[3].x = width - appX;
          data[3].y = height - appY;
        },
        updateUVs: function updateUVs(comp) {
          var renderData = comp.renderData;
          if (!renderData || !comp.ttfSpriteFrame) {
            return;
          }
          var vData = renderData.chunk.vb;
          var uv = comp.ttfSpriteFrame.uv;
          vData[3] = uv[0];
          vData[4] = uv[1];
          vData[12] = uv[2];
          vData[13] = uv[3];
          vData[21] = uv[4];
          vData[22] = uv[5];
          vData[30] = uv[6];
          vData[31] = uv[7];
        },
        updateColor: function updateColor(comp) {}
      };
      addon(ttf, ttfUtils);

      var labelAssembler = exports('l', {
        getAssembler: function getAssembler(comp) {
          var assembler = ttf;
          if (comp.font instanceof BitmapFont) {
            assembler = bmfont;
          } else if (comp.cacheMode === Label.CacheMode.CHAR) {
            assembler = letter;
          }
          return assembler;
        }
      });
      Label.Assembler = labelAssembler;

      var FillType$1 = Sprite.FillType;
      var m$3 = new Mat4();
      var QUAD_INDICES$3 = Uint16Array.from([0, 1, 2, 1, 3, 2]);
      var barFilled = {
        updateRenderData: function updateRenderData(sprite) {
          var frame = sprite.spriteFrame;
          dynamicAtlasManager.packToDynamicAtlas(sprite, frame);
          var renderData = sprite.renderData;
          if (renderData && frame) {
            var vertDirty = renderData.vertDirty;
            if (!vertDirty) {
              return;
            }
            var fillStart = sprite.fillStart;
            var fillRange = sprite.fillRange;
            if (fillRange < 0) {
              fillStart += fillRange;
              fillRange = -fillRange;
            }
            fillRange = fillStart + fillRange;
            fillStart = fillStart > 1.0 ? 1.0 : fillStart;
            fillStart = fillStart < 0.0 ? 0.0 : fillStart;
            fillRange = fillRange > 1.0 ? 1.0 : fillRange;
            fillRange = fillRange < 0.0 ? 0.0 : fillRange;
            fillRange -= fillStart;
            fillRange = fillRange < 0 ? 0 : fillRange;
            var fillEnd = fillStart + fillRange;
            fillEnd = fillEnd > 1 ? 1 : fillEnd;
            this.updateUVs(sprite, fillStart, fillEnd);
            this.updateVertexData(sprite, fillStart, fillEnd);
            renderData.updateRenderData(sprite, frame);
          }
        },
        updateUVs: function updateUVs(sprite, fillStart, fillEnd) {
          var spriteFrame = sprite.spriteFrame;
          var renderData = sprite.renderData;
          var vData = renderData.chunk.vb;
          var atlasWidth = spriteFrame.width;
          var atlasHeight = spriteFrame.height;
          var textureRect = spriteFrame.rect;
          var ul = 0;
          var vb = 0;
          var ur = 0;
          var vt = 0;
          var quadUV0 = 0;
          var quadUV1 = 0;
          var quadUV2 = 0;
          var quadUV3 = 0;
          var quadUV4 = 0;
          var quadUV5 = 0;
          var quadUV6 = 0;
          var quadUV7 = 0;
          if (spriteFrame.isRotated()) {
            ul = textureRect.x / atlasWidth;
            vb = (textureRect.y + textureRect.width) / atlasHeight;
            ur = (textureRect.x + textureRect.height) / atlasWidth;
            vt = textureRect.y / atlasHeight;
            quadUV0 = quadUV2 = ul;
            quadUV4 = quadUV6 = ur;
            quadUV3 = quadUV7 = vb;
            quadUV1 = quadUV5 = vt;
          } else {
            ul = textureRect.x / atlasWidth;
            vb = (textureRect.y + textureRect.height) / atlasHeight;
            ur = (textureRect.x + textureRect.width) / atlasWidth;
            vt = textureRect.y / atlasHeight;
            quadUV0 = quadUV4 = ul;
            quadUV2 = quadUV6 = ur;
            quadUV1 = quadUV3 = vb;
            quadUV5 = quadUV7 = vt;
          }
          switch (sprite.fillType) {
            case FillType$1.HORIZONTAL:
              vData[3] = quadUV0 + (quadUV2 - quadUV0) * fillStart;
              vData[4] = quadUV1 + (quadUV3 - quadUV1) * fillStart;
              vData[12] = quadUV0 + (quadUV2 - quadUV0) * fillEnd;
              vData[13] = quadUV1 + (quadUV3 - quadUV1) * fillEnd;
              vData[21] = quadUV4 + (quadUV6 - quadUV4) * fillStart;
              vData[22] = quadUV5 + (quadUV7 - quadUV5) * fillStart;
              vData[30] = quadUV4 + (quadUV6 - quadUV4) * fillEnd;
              vData[31] = quadUV5 + (quadUV7 - quadUV5) * fillEnd;
              break;
            case FillType$1.VERTICAL:
              vData[3] = quadUV0 + (quadUV4 - quadUV0) * fillStart;
              vData[4] = quadUV1 + (quadUV5 - quadUV1) * fillStart;
              vData[12] = quadUV2 + (quadUV6 - quadUV2) * fillStart;
              vData[13] = quadUV3 + (quadUV7 - quadUV3) * fillStart;
              vData[21] = quadUV0 + (quadUV4 - quadUV0) * fillEnd;
              vData[22] = quadUV1 + (quadUV5 - quadUV1) * fillEnd;
              vData[30] = quadUV2 + (quadUV6 - quadUV2) * fillEnd;
              vData[31] = quadUV3 + (quadUV7 - quadUV3) * fillEnd;
              break;
            default:
              errorID(2626);
              break;
          }
        },
        updateVertexData: function updateVertexData(sprite, fillStart, fillEnd) {
          var renderData = sprite.renderData;
          var dataList = renderData.data;
          var uiTrans = sprite.node._uiProps.uiTransformComp;
          var width = uiTrans.width;
          var height = uiTrans.height;
          var appX = uiTrans.anchorX * width;
          var appY = uiTrans.anchorY * height;
          var l = -appX;
          var b = -appY;
          var r = width - appX;
          var t = height - appY;
          var progressStart = 0;
          var progressEnd = 0;
          switch (sprite.fillType) {
            case FillType$1.HORIZONTAL:
              progressStart = l + (r - l) * fillStart;
              progressEnd = l + (r - l) * fillEnd;
              l = progressStart;
              r = progressEnd;
              break;
            case FillType$1.VERTICAL:
              progressStart = b + (t - b) * fillStart;
              progressEnd = b + (t - b) * fillEnd;
              b = progressStart;
              t = progressEnd;
              break;
            default:
              errorID(2626);
              break;
          }
          dataList[0].x = l;
          dataList[0].y = b;
          dataList[1].x = r;
          dataList[1].y = b;
          dataList[2].x = l;
          dataList[2].y = t;
          dataList[3].x = r;
          dataList[3].y = t;
        },
        createData: function createData(sprite) {
          var renderData = sprite.requestRenderData();
          renderData.dataLength = 4;
          renderData.resize(4, 6);
          renderData.chunk.setIndexBuffer(QUAD_INDICES$3);
          var dataList = renderData.data;
          for (var _iterator = _createForOfIteratorHelperLoose(dataList), _step; !(_step = _iterator()).done;) {
            var data = _step.value;
            data.z = 0;
          }
          return renderData;
        },
        updateWorldVertexData: function updateWorldVertexData(sprite, chunk) {
          var node = sprite.node;
          node.getWorldMatrix(m$3);
          var renderData = sprite.renderData;
          var stride = renderData.floatStride;
          var dataList = sprite.renderData.data;
          var vData = chunk.vb;
          var offset = 0;
          for (var i = 0; i < 4; i++) {
            var local = dataList[i];
            var x = local.x;
            var y = local.y;
            var rhw = m$3.m03 * x + m$3.m07 * y + m$3.m15;
            rhw = rhw ? 1 / rhw : 1;
            offset = i * stride;
            vData[offset] = (m$3.m00 * x + m$3.m04 * y + m$3.m12) * rhw;
            vData[offset + 1] = (m$3.m01 * x + m$3.m05 * y + m$3.m13) * rhw;
            vData[offset + 2] = (m$3.m02 * x + m$3.m06 * y + m$3.m14) * rhw;
          }
        },
        fillBuffers: function fillBuffers(sprite, renderer) {
          var renderData = sprite.renderData;
          var chunk = renderData.chunk;
          if (sprite._flagChangedVersion !== sprite.node.flagChangedVersion || renderData.vertDirty) {
            this.updateWorldVertexData(sprite, chunk);
            renderData.vertDirty = false;
            sprite._flagChangedVersion = sprite.node.flagChangedVersion;
          }
          chunk.bufferId;
          var vid = chunk.vertexOffset;
          var meshBuffer = chunk.meshBuffer;
          var ib = chunk.meshBuffer.iData;
          var indexOffset = meshBuffer.indexOffset;
          ib[indexOffset++] = vid;
          ib[indexOffset++] = vid + 1;
          ib[indexOffset++] = vid + 2;
          ib[indexOffset++] = vid + 2;
          ib[indexOffset++] = vid + 1;
          ib[indexOffset++] = vid + 3;
          meshBuffer.indexOffset += 6;
        },
        updateColor: function updateColor(sprite) {
          var renderData = sprite.renderData;
          var vData = renderData.chunk.vb;
          var stride = renderData.floatStride;
          var colorOffset = 5;
          var color = sprite.color;
          var colorR = color.r / 255;
          var colorG = color.g / 255;
          var colorB = color.b / 255;
          var colorA = sprite.node._uiProps.opacity;
          for (var i = 0; i < 4; i++) {
            vData[colorOffset] = colorR;
            vData[colorOffset + 1] = colorG;
            vData[colorOffset + 2] = colorB;
            vData[colorOffset + 3] = colorA;
            colorOffset += stride;
          }
        }
      };

      var PI_2 = Math.PI * 2;
      var EPSILON$1 = 1e-6;
      var m$2 = new Mat4();
      var _vertPos = [new Vec2(), new Vec2(), new Vec2(), new Vec2()];
      var _vertices = new Array(4);
      var _uvs = new Array(8);
      var _intersectPoint_1 = [new Vec2(), new Vec2(), new Vec2(), new Vec2()];
      var _intersectPoint_2 = [new Vec2(), new Vec2(), new Vec2(), new Vec2()];
      var _center = new Vec2();
      var _triangles = [new Vec2(), new Vec2(), new Vec2(), new Vec2()];
      var QUAD_INDICES$2 = null;
      function _calcIntersectedPoints(left, right, bottom, top, center, angle, intersectPoints) {
        var sinAngle = Math.sin(angle);
        sinAngle = Math.abs(sinAngle) > EPSILON$1 ? sinAngle : 0;
        var cosAngle = Math.cos(angle);
        cosAngle = Math.abs(cosAngle) > EPSILON$1 ? cosAngle : 0;
        var tanAngle = 0;
        var cotAngle = 0;
        if (cosAngle !== 0) {
          tanAngle = sinAngle / cosAngle;
          if ((left - center.x) * cosAngle > 0) {
            var yLeft = center.y + tanAngle * (left - center.x);
            intersectPoints[0].x = left;
            intersectPoints[0].y = yLeft;
          }
          if ((right - center.x) * cosAngle > 0) {
            var yRight = center.y + tanAngle * (right - center.x);
            intersectPoints[2].x = right;
            intersectPoints[2].y = yRight;
          }
        }
        if (sinAngle !== 0) {
          cotAngle = cosAngle / sinAngle;
          if ((top - center.y) * sinAngle > 0) {
            var xTop = center.x + cotAngle * (top - center.y);
            intersectPoints[3].x = xTop;
            intersectPoints[3].y = top;
          }
          if ((bottom - center.y) * sinAngle > 0) {
            var xBottom = center.x + cotAngle * (bottom - center.y);
            intersectPoints[1].x = xBottom;
            intersectPoints[1].y = bottom;
          }
        }
      }
      function _calculateVertices(sprite) {
        var uiTrans = sprite.node._uiProps.uiTransformComp;
        var width = uiTrans.width;
        var height = uiTrans.height;
        var appX = uiTrans.anchorX * width;
        var appY = uiTrans.anchorY * height;
        var l = -appX;
        var b = -appY;
        var r = width - appX;
        var t = height - appY;
        var vertices = _vertices;
        vertices[0] = l;
        vertices[1] = b;
        vertices[2] = r;
        vertices[3] = t;
        var fillCenter = sprite.fillCenter;
        var cx = _center.x = Math.min(Math.max(0, fillCenter.x), 1) * (r - l) + l;
        var cy = _center.y = Math.min(Math.max(0, fillCenter.y), 1) * (t - b) + b;
        _vertPos[0].x = _vertPos[3].x = l;
        _vertPos[1].x = _vertPos[2].x = r;
        _vertPos[0].y = _vertPos[1].y = b;
        _vertPos[2].y = _vertPos[3].y = t;
        for (var _i = 0, _triangles2 = _triangles; _i < _triangles2.length; _i++) {
          var num = _triangles2[_i];
          Vec2.set(num, 0, 0);
        }
        if (cx !== vertices[0]) {
          Vec2.set(_triangles[0], 3, 0);
        }
        if (cx !== vertices[2]) {
          Vec2.set(_triangles[2], 1, 2);
        }
        if (cy !== vertices[1]) {
          Vec2.set(_triangles[1], 0, 1);
        }
        if (cy !== vertices[3]) {
          Vec2.set(_triangles[3], 2, 3);
        }
      }
      function _calculateUVs(spriteFrame) {
        var atlasWidth = spriteFrame.width;
        var atlasHeight = spriteFrame.height;
        var textureRect = spriteFrame.getRect();
        var u0 = 0;
        var u1 = 0;
        var v0 = 0;
        var v1 = 0;
        var uvs = _uvs;
        if (spriteFrame.isRotated()) {
          u0 = textureRect.x / atlasWidth;
          u1 = (textureRect.x + textureRect.height) / atlasWidth;
          v0 = textureRect.y / atlasHeight;
          v1 = (textureRect.y + textureRect.width) / atlasHeight;
          uvs[0] = uvs[2] = u0;
          uvs[4] = uvs[6] = u1;
          uvs[3] = uvs[7] = v1;
          uvs[1] = uvs[5] = v0;
        } else {
          u0 = textureRect.x / atlasWidth;
          u1 = (textureRect.x + textureRect.width) / atlasWidth;
          v0 = textureRect.y / atlasHeight;
          v1 = (textureRect.y + textureRect.height) / atlasHeight;
          uvs[0] = uvs[4] = u0;
          uvs[2] = uvs[6] = u1;
          uvs[1] = uvs[3] = v1;
          uvs[5] = uvs[7] = v0;
        }
      }
      function _getVertAngle(start, end) {
        var placementX = end.x - start.x;
        var placementY = end.y - start.y;
        if (placementX === 0 && placementY === 0) {
          return 0;
        } else if (placementX === 0) {
          if (placementY > 0) {
            return Math.PI * 0.5;
          } else {
            return Math.PI * 1.5;
          }
        } else {
          var angle = Math.atan(placementY / placementX);
          if (placementX < 0) {
            angle += Math.PI;
          }
          return angle;
        }
      }
      function _generateTriangle(dataList, offset, vert0, vert1, vert2) {
        var vertices = _vertices;
        var v0x = vertices[0];
        var v0y = vertices[1];
        var v1x = vertices[2];
        var v1y = vertices[3];
        dataList[offset].x = vert0.x;
        dataList[offset].y = vert0.y;
        dataList[offset + 1].x = vert1.x;
        dataList[offset + 1].y = vert1.y;
        dataList[offset + 2].x = vert2.x;
        dataList[offset + 2].y = vert2.y;
        var progressX = 0;
        var progressY = 0;
        progressX = (vert0.x - v0x) / (v1x - v0x);
        progressY = (vert0.y - v0y) / (v1y - v0y);
        _generateUV(progressX, progressY, dataList, offset);
        progressX = (vert1.x - v0x) / (v1x - v0x);
        progressY = (vert1.y - v0y) / (v1y - v0y);
        _generateUV(progressX, progressY, dataList, offset + 1);
        progressX = (vert2.x - v0x) / (v1x - v0x);
        progressY = (vert2.y - v0y) / (v1y - v0y);
        _generateUV(progressX, progressY, dataList, offset + 2);
      }
      function _generateUV(progressX, progressY, data, offset) {
        var uvs = _uvs;
        var px1 = uvs[0] + (uvs[2] - uvs[0]) * progressX;
        var px2 = uvs[4] + (uvs[6] - uvs[4]) * progressX;
        var py1 = uvs[1] + (uvs[3] - uvs[1]) * progressX;
        var py2 = uvs[5] + (uvs[7] - uvs[5]) * progressX;
        var uv = data[offset];
        uv.u = px1 + (px2 - px1) * progressY;
        uv.v = py1 + (py2 - py1) * progressY;
      }
      var radialFilled = {
        useModel: false,
        createData: function createData(sprite) {
          return sprite.requestRenderData();
        },
        updateRenderData: function updateRenderData(sprite) {
          var frame = sprite.spriteFrame;
          dynamicAtlasManager.packToDynamicAtlas(sprite, frame);
          this.updateUVs(sprite);
          var renderData = sprite.renderData;
          if (renderData && frame) {
            if (!renderData.vertDirty) {
              return;
            }
            var dataList = renderData.data;
            var fillStart = sprite.fillStart;
            var fillRange = sprite.fillRange;
            if (fillRange < 0) {
              fillStart += fillRange;
              fillRange = -fillRange;
            }
            while (fillStart >= 1.0) {
              fillStart -= 1.0;
            }
            while (fillStart < 0.0) {
              fillStart += 1.0;
            }
            fillStart *= PI_2;
            fillRange *= PI_2;
            var fillEnd = fillStart + fillRange;
            _calculateVertices(sprite);
            _calculateUVs(frame);
            _calcIntersectedPoints(_vertices[0], _vertices[2], _vertices[1], _vertices[3], _center, fillStart, _intersectPoint_1);
            _calcIntersectedPoints(_vertices[0], _vertices[2], _vertices[1], _vertices[3], _center, fillStart + fillRange, _intersectPoint_2);
            var offset = 0;
            for (var triangleIndex = 0; triangleIndex < 4; ++triangleIndex) {
              var triangle = _triangles[triangleIndex];
              if (!triangle) {
                continue;
              }
              if (fillRange >= PI_2) {
                renderData.dataLength = offset + 3;
                _generateTriangle(dataList, offset, _center, _vertPos[triangle.x], _vertPos[triangle.y]);
                offset += 3;
                continue;
              }
              var startAngle = _getVertAngle(_center, _vertPos[triangle.x]);
              var endAngle = _getVertAngle(_center, _vertPos[triangle.y]);
              if (endAngle < startAngle) {
                endAngle += PI_2;
              }
              startAngle -= PI_2;
              endAngle -= PI_2;
              for (var testIndex = 0; testIndex < 3; ++testIndex) {
                if (startAngle >= fillEnd) ; else if (startAngle >= fillStart) {
                  renderData.dataLength = offset + 3;
                  if (endAngle >= fillEnd) {
                    _generateTriangle(dataList, offset, _center, _vertPos[triangle.x], _intersectPoint_2[triangleIndex]);
                  } else {
                    _generateTriangle(dataList, offset, _center, _vertPos[triangle.x], _vertPos[triangle.y]);
                  }
                  offset += 3;
                } else if (endAngle > fillStart) {
                  if (endAngle <= fillEnd) {
                    renderData.dataLength = offset + 3;
                    _generateTriangle(dataList, offset, _center, _intersectPoint_1[triangleIndex], _vertPos[triangle.y]);
                    offset += 3;
                  } else {
                    renderData.dataLength = offset + 3;
                    _generateTriangle(dataList, offset, _center, _intersectPoint_1[triangleIndex], _intersectPoint_2[triangleIndex]);
                    offset += 3;
                  }
                }
                startAngle += PI_2;
                endAngle += PI_2;
              }
            }
            if (offset === 0) {
              renderData.dataLength = 0;
            }
            renderData.resize(offset, offset);
            renderData.updateRenderData(sprite, frame);
          }
        },
        createQuadIndices: function createQuadIndices(indexCount) {
          QUAD_INDICES$2 = null;
          QUAD_INDICES$2 = new Uint16Array(indexCount);
          var offset = 0;
          for (var i = 0; i < indexCount; i++) {
            QUAD_INDICES$2[offset++] = i;
          }
        },
        fillBuffers: function fillBuffers(comp, renderer) {
          var node = comp.node;
          var renderData = comp.renderData;
          var chunk = renderData.chunk;
          if (comp._flagChangedVersion !== node.flagChangedVersion || renderData.vertDirty) {
            this.updateWorldVertexAndUVData(comp, chunk);
            renderData.vertDirty = false;
            comp._flagChangedVersion = node.flagChangedVersion;
          }
          this.updateColorLate(comp);
          chunk.bufferId;
          var vid = chunk.vertexOffset;
          var meshBuffer = chunk.meshBuffer;
          var ib = chunk.meshBuffer.iData;
          var indexOffset = meshBuffer.indexOffset;
          for (var i = 0; i < renderData.indexCount; i++) {
            ib[indexOffset + i] = vid + i;
          }
          meshBuffer.indexOffset += renderData.indexCount;
          meshBuffer.setDirty();
        },
        updateWorldUVData: function updateWorldUVData(sprite, chunk) {
          var renderData = sprite.renderData;
          var stride = renderData.floatStride;
          var dataList = renderData.data;
          var vData = renderData.chunk.vb;
          for (var i = 0; i < dataList.length; i++) {
            var offset = i * stride;
            vData[offset + 3] = dataList[i].u;
            vData[offset + 4] = dataList[i].v;
          }
        },
        updateWorldVertexAndUVData: function updateWorldVertexAndUVData(sprite, chunk) {
          var node = sprite.node;
          node.getWorldMatrix(m$2);
          var renderData = sprite.renderData;
          var stride = renderData.floatStride;
          var dataList = sprite.renderData.data;
          var vData = chunk.vb;
          var vertexCount = renderData.vertexCount;
          var vertexOffset = 0;
          for (var i = 0; i < vertexCount; i++) {
            var vert = dataList[i];
            var x = vert.x;
            var y = vert.y;
            var rhw = m$2.m03 * x + m$2.m07 * y + m$2.m15;
            rhw = rhw ? 1 / rhw : 1;
            vData[vertexOffset + 0] = (m$2.m00 * x + m$2.m04 * y + m$2.m12) * rhw;
            vData[vertexOffset + 1] = (m$2.m01 * x + m$2.m05 * y + m$2.m13) * rhw;
            vData[vertexOffset + 2] = (m$2.m02 * x + m$2.m06 * y + m$2.m14) * rhw;
            vData[vertexOffset + 3] = vert.u;
            vData[vertexOffset + 4] = vert.v;
            vertexOffset += stride;
          }
        },
        updateUVs: function updateUVs(sprite) {
          var renderData = sprite.renderData;
          renderData.vertDirty = true;
          sprite.markForUpdateRenderData();
        },
        updateColorLate: function updateColorLate(sprite) {
          var renderData = sprite.renderData;
          var vData = renderData.chunk.vb;
          var stride = renderData.floatStride;
          var vertexCount = renderData.vertexCount;
          var colorOffset = 5;
          var color = sprite.color;
          var colorR = color.r / 255;
          var colorG = color.g / 255;
          var colorB = color.b / 255;
          var colorA = sprite.node._uiProps.opacity;
          for (var i = 0; i < vertexCount; i++) {
            vData[colorOffset] = colorR;
            vData[colorOffset + 1] = colorG;
            vData[colorOffset + 2] = colorB;
            vData[colorOffset + 3] = colorA;
            colorOffset += stride;
          }
        },
        updateColor: function updateColor(sprite) {}
      };

      var QUAD_INDICES$1 = Uint16Array.from([0, 1, 2, 1, 3, 2]);
      var simple = {
        createData: function createData(sprite) {
          var renderData = sprite.requestRenderData();
          renderData.dataLength = 4;
          renderData.resize(4, 6);
          renderData.chunk.setIndexBuffer(QUAD_INDICES$1);
          return renderData;
        },
        updateRenderData: function updateRenderData(sprite) {
          var frame = sprite.spriteFrame;
          dynamicAtlasManager.packToDynamicAtlas(sprite, frame);
          this.updateUVs(sprite);
          var renderData = sprite.renderData;
          if (renderData && frame) {
            if (renderData.vertDirty) {
              this.updateVertexData(sprite);
            }
            renderData.updateRenderData(sprite, frame);
          }
        },
        updateWorldVerts: function updateWorldVerts(sprite, chunk) {
          var renderData = sprite.renderData;
          var vData = chunk.vb;
          var dataList = renderData.data;
          var node = sprite.node;
          var m = node.worldMatrix;
          var stride = renderData.floatStride;
          var offset = 0;
          var length = dataList.length;
          for (var i = 0; i < length; i++) {
            var curData = dataList[i];
            var x = curData.x;
            var y = curData.y;
            var rhw = m.m03 * x + m.m07 * y + m.m15;
            rhw = rhw ? 1 / rhw : 1;
            offset = i * stride;
            vData[offset + 0] = (m.m00 * x + m.m04 * y + m.m12) * rhw;
            vData[offset + 1] = (m.m01 * x + m.m05 * y + m.m13) * rhw;
            vData[offset + 2] = (m.m02 * x + m.m06 * y + m.m14) * rhw;
          }
        },
        fillBuffers: function fillBuffers(sprite, renderer) {
          if (sprite === null) {
            return;
          }
          var renderData = sprite.renderData;
          var chunk = renderData.chunk;
          if (sprite._flagChangedVersion !== sprite.node.flagChangedVersion || renderData.vertDirty) {
            this.updateWorldVerts(sprite, chunk);
            renderData.vertDirty = false;
            sprite._flagChangedVersion = sprite.node.flagChangedVersion;
          }
          var vidOrigin = chunk.vertexOffset;
          var meshBuffer = chunk.meshBuffer;
          var ib = chunk.meshBuffer.iData;
          var indexOffset = meshBuffer.indexOffset;
          var vid = vidOrigin;
          ib[indexOffset++] = vid;
          ib[indexOffset++] = vid + 1;
          ib[indexOffset++] = vid + 2;
          ib[indexOffset++] = vid + 1;
          ib[indexOffset++] = vid + 3;
          ib[indexOffset++] = vid + 2;
          meshBuffer.indexOffset += 6;
        },
        updateVertexData: function updateVertexData(sprite) {
          var renderData = sprite.renderData;
          if (!renderData) {
            return;
          }
          var uiTrans = sprite.node._uiProps.uiTransformComp;
          var dataList = renderData.data;
          var cw = uiTrans.width;
          var ch = uiTrans.height;
          var appX = uiTrans.anchorX * cw;
          var appY = uiTrans.anchorY * ch;
          var l = 0;
          var b = 0;
          var r = 0;
          var t = 0;
          if (sprite.trim) {
            l = -appX;
            b = -appY;
            r = cw - appX;
            t = ch - appY;
          } else {
            var frame = sprite.spriteFrame;
            var originSize = frame.originalSize;
            var ow = originSize.width;
            var oh = originSize.height;
            var scaleX = cw / ow;
            var scaleY = ch / oh;
            var trimmedBorder = frame.trimmedBorder;
            l = trimmedBorder.x * scaleX - appX;
            b = trimmedBorder.z * scaleY - appY;
            r = cw + trimmedBorder.y * scaleX - appX;
            t = ch + trimmedBorder.w * scaleY - appY;
          }
          dataList[0].x = l;
          dataList[0].y = b;
          dataList[1].x = r;
          dataList[1].y = b;
          dataList[2].x = l;
          dataList[2].y = t;
          dataList[3].x = r;
          dataList[3].y = t;
          renderData.vertDirty = true;
        },
        updateUVs: function updateUVs(sprite) {
          if (!sprite.spriteFrame) return;
          var renderData = sprite.renderData;
          var vData = renderData.chunk.vb;
          var uv = sprite.spriteFrame.uv;
          vData[3] = uv[0];
          vData[4] = uv[1];
          vData[12] = uv[2];
          vData[13] = uv[3];
          vData[21] = uv[4];
          vData[22] = uv[5];
          vData[30] = uv[6];
          vData[31] = uv[7];
        },
        updateColor: function updateColor(sprite) {
          var renderData = sprite.renderData;
          var vData = renderData.chunk.vb;
          var colorOffset = 5;
          var color = sprite.color;
          var colorR = color.r / 255;
          var colorG = color.g / 255;
          var colorB = color.b / 255;
          var colorA = color.a / 255;
          for (var i = 0; i < 4; i++, colorOffset += renderData.floatStride) {
            vData[colorOffset] = colorR;
            vData[colorOffset + 1] = colorG;
            vData[colorOffset + 2] = colorB;
            vData[colorOffset + 3] = colorA;
          }
        }
      };

      var m$1 = new Mat4();
      var tempRenderData$1 = [];
      for (var i = 0; i < 4; i++) {
        tempRenderData$1.push({
          x: 0,
          y: 0,
          z: 0,
          u: 0,
          v: 0,
          color: new Color$1()
        });
      }
      var sliced = {
        createData: function createData(sprite) {
          var renderData = sprite.requestRenderData();
          renderData.dataLength = 16;
          renderData.resize(16, 54);
          this.QUAD_INDICES = new Uint16Array(54);
          this.createQuadIndices(4, 4);
          renderData.chunk.setIndexBuffer(this.QUAD_INDICES);
          return renderData;
        },
        createQuadIndices: function createQuadIndices(vertexRow, vertexCol) {
          var offset = 0;
          for (var curRow = 0; curRow < vertexRow - 1; curRow++) {
            for (var curCol = 0; curCol < vertexCol - 1; curCol++) {
              var vid = curRow * vertexCol + curCol;
              this.QUAD_INDICES[offset++] = vid;
              this.QUAD_INDICES[offset++] = vid + 1;
              this.QUAD_INDICES[offset++] = vid + vertexCol;
              this.QUAD_INDICES[offset++] = vid + 1;
              this.QUAD_INDICES[offset++] = vid + 1 + vertexCol;
              this.QUAD_INDICES[offset++] = vid + vertexCol;
            }
          }
        },
        updateRenderData: function updateRenderData(sprite) {
          var frame = sprite.spriteFrame;
          dynamicAtlasManager.packToDynamicAtlas(sprite, frame);
          this.updateUVs(sprite);
          var renderData = sprite.renderData;
          if (renderData && frame) {
            var vertDirty = renderData.vertDirty;
            if (vertDirty) {
              this.updateVertexData(sprite);
            }
            renderData.updateRenderData(sprite, frame);
          }
        },
        updateVertexData: function updateVertexData(sprite) {
          var renderData = sprite.renderData;
          var dataList = renderData.data;
          var uiTrans = sprite.node._uiProps.uiTransformComp;
          var width = uiTrans.width;
          var height = uiTrans.height;
          var appX = uiTrans.anchorX * width;
          var appY = uiTrans.anchorY * height;
          var frame = sprite.spriteFrame;
          var leftWidth = frame.insetLeft;
          var rightWidth = frame.insetRight;
          var topHeight = frame.insetTop;
          var bottomHeight = frame.insetBottom;
          var sizableWidth = width - leftWidth - rightWidth;
          var sizableHeight = height - topHeight - bottomHeight;
          var xScale = width / (leftWidth + rightWidth);
          var yScale = height / (topHeight + bottomHeight);
          xScale = Number.isNaN(xScale) || xScale > 1 ? 1 : xScale;
          yScale = Number.isNaN(yScale) || yScale > 1 ? 1 : yScale;
          sizableWidth = sizableWidth < 0 ? 0 : sizableWidth;
          sizableHeight = sizableHeight < 0 ? 0 : sizableHeight;
          tempRenderData$1[0].x = -appX;
          tempRenderData$1[0].y = -appY;
          tempRenderData$1[1].x = leftWidth * xScale - appX;
          tempRenderData$1[1].y = bottomHeight * yScale - appY;
          tempRenderData$1[2].x = tempRenderData$1[1].x + sizableWidth;
          tempRenderData$1[2].y = tempRenderData$1[1].y + sizableHeight;
          tempRenderData$1[3].x = width - appX;
          tempRenderData$1[3].y = height - appY;
          for (var curRow = 0; curRow < 4; curRow++) {
            for (var curCol = 0; curCol < 4; curCol++) {
              var curIndex = curRow * 4 + curCol;
              if (curIndex < renderData.dataLength && curRow < tempRenderData$1.length && curCol < tempRenderData$1.length) {
                dataList[curIndex].x = tempRenderData$1[curCol].x;
                dataList[curIndex].y = tempRenderData$1[curRow].y;
              }
            }
          }
        },
        fillBuffers: function fillBuffers(sprite, renderer) {
          var renderData = sprite.renderData;
          var chunk = renderData.chunk;
          if (sprite._flagChangedVersion !== sprite.node.flagChangedVersion || renderData.vertDirty) {
            this.updateWorldVertexData(sprite, chunk);
            renderData.vertDirty = false;
            sprite._flagChangedVersion = sprite.node.flagChangedVersion;
          }
          chunk.bufferId;
          var vid = chunk.vertexOffset;
          var meshBuffer = chunk.meshBuffer;
          var ib = chunk.meshBuffer.iData;
          var indexOffset = meshBuffer.indexOffset;
          for (var r = 0; r < 3; ++r) {
            for (var c = 0; c < 3; ++c) {
              var start = vid + r * 4 + c;
              ib[indexOffset++] = start;
              ib[indexOffset++] = start + 1;
              ib[indexOffset++] = start + 4;
              ib[indexOffset++] = start + 1;
              ib[indexOffset++] = start + 5;
              ib[indexOffset++] = start + 4;
            }
          }
          meshBuffer.indexOffset = indexOffset;
        },
        updateWorldVertexData: function updateWorldVertexData(sprite, chunk) {
          var node = sprite.node;
          node.getWorldMatrix(m$1);
          var renderData = sprite.renderData;
          var stride = renderData.floatStride;
          var dataList = renderData.data;
          var vData = chunk.vb;
          var offset = 0;
          for (var row = 0; row < 4; ++row) {
            var rowD = dataList[row * 4];
            for (var col = 0; col < 4; ++col) {
              var colD = dataList[col];
              var x = colD.x;
              var y = rowD.y;
              var rhw = m$1.m03 * x + m$1.m07 * y + m$1.m15;
              rhw = rhw ? 1 / rhw : 1;
              offset = (row * 4 + col) * stride;
              vData[offset + 0] = (m$1.m00 * x + m$1.m04 * y + m$1.m12) * rhw;
              vData[offset + 1] = (m$1.m01 * x + m$1.m05 * y + m$1.m13) * rhw;
              vData[offset + 2] = (m$1.m02 * x + m$1.m06 * y + m$1.m14) * rhw;
            }
          }
        },
        updateUVs: function updateUVs(sprite) {
          if (!sprite.spriteFrame) return;
          var renderData = sprite.renderData;
          var vData = renderData.chunk.vb;
          var stride = renderData.floatStride;
          var uv = sprite.spriteFrame.uvSliced;
          var uvOffset = 3;
          for (var _i = 0; _i < 16; _i++) {
            vData[uvOffset] = uv[_i].u;
            vData[uvOffset + 1] = uv[_i].v;
            uvOffset += stride;
          }
        },
        updateColor: function updateColor(sprite) {
          var renderData = sprite.renderData;
          var vData = renderData.chunk.vb;
          var stride = renderData.floatStride;
          var colorOffset = 5;
          var color = sprite.color;
          var colorR = color.r / 255;
          var colorG = color.g / 255;
          var colorB = color.b / 255;
          var colorA = sprite.node._uiProps.opacity;
          for (var _i2 = 0; _i2 < 16; _i2++) {
            vData[colorOffset] = colorR;
            vData[colorOffset + 1] = colorG;
            vData[colorOffset + 2] = colorB;
            vData[colorOffset + 3] = colorA;
            colorOffset += stride;
          }
        }
      };

      var m = new Mat4();
      var origin;
      var leftInner;
      var rightInner;
      var rightOuter;
      var bottomInner;
      var topInner;
      var topOuter;
      var tempRenderDataLength = 0;
      var tempRenderData = [];
      var QUAD_INDICES = null;
      function has9SlicedOffsetVertexCount(spriteFrame) {
        if (spriteFrame) {
          if (spriteFrame.insetTop > 0 || spriteFrame.insetBottom > 0 || spriteFrame.insetLeft > 0 || spriteFrame.insetRight > 0) {
            return 2;
          }
        }
        return 0;
      }
      var tiled = {
        createData: function createData(sprite) {
          return sprite.requestRenderData();
        },
        updateRenderData: function updateRenderData(sprite) {
          var renderData = sprite.renderData;
          var frame = sprite.spriteFrame;
          if (!frame || !renderData) {
            return;
          }
          if (!renderData.vertDirty) {
            return;
          }
          var uiTrans = sprite.node._uiProps.uiTransformComp;
          var contentWidth = Math.abs(uiTrans.width);
          var contentHeight = Math.abs(uiTrans.height);
          var rect = frame.getRect();
          var leftWidth = frame.insetLeft;
          var rightWidth = frame.insetRight;
          var centerWidth = rect.width - leftWidth - rightWidth;
          var topHeight = frame.insetTop;
          var bottomHeight = frame.insetBottom;
          var centerHeight = rect.height - topHeight - bottomHeight;
          var sizableWidth = contentWidth - leftWidth - rightWidth;
          var sizableHeight = contentHeight - topHeight - bottomHeight;
          sizableWidth = sizableWidth > 0 ? sizableWidth : 0;
          sizableHeight = sizableHeight > 0 ? sizableHeight : 0;
          var hRepeat = centerWidth === 0 ? sizableWidth : sizableWidth / centerWidth;
          var vRepeat = centerHeight === 0 ? sizableHeight : sizableHeight / centerHeight;
          var offsetVertexCount = has9SlicedOffsetVertexCount(frame);
          var row = Math.ceil(vRepeat + offsetVertexCount);
          var col = Math.ceil(hRepeat + offsetVertexCount);
          renderData.dataLength = row * 2 * (col * 2);
          this.updateVerts(sprite, sizableWidth, sizableHeight, row, col);
          if (renderData.vertexCount !== row * col * 4) {
            sprite.renderEntity.colorDirty = true;
          }
          renderData.resize(row * col * 4, row * col * 6);
          renderData.updateRenderData(sprite, frame);
        },
        createQuadIndices: function createQuadIndices(indexCount) {
          if (indexCount % 6 !== 0) {
            error('illegal index count!');
            return;
          }
          var quadCount = indexCount / 6;
          QUAD_INDICES = null;
          QUAD_INDICES = new Uint16Array(indexCount);
          var offset = 0;
          for (var i = 0; i < quadCount; i++) {
            QUAD_INDICES[offset++] = 0 + i * 4;
            QUAD_INDICES[offset++] = 1 + i * 4;
            QUAD_INDICES[offset++] = 2 + i * 4;
            QUAD_INDICES[offset++] = 1 + i * 4;
            QUAD_INDICES[offset++] = 3 + i * 4;
            QUAD_INDICES[offset++] = 2 + i * 4;
          }
        },
        updateUVs: function updateUVs(sprite) {
          var renderData = sprite.renderData;
          renderData.vertDirty = true;
          sprite.markForUpdateRenderData();
        },
        fillBuffers: function fillBuffers(sprite, renderer) {
          var node = sprite.node;
          var renderData = sprite.renderData;
          var chunk = renderData.chunk;
          if (sprite._flagChangedVersion !== node.flagChangedVersion || renderData.vertDirty) {
            this.updateWorldVertexAndUVData(sprite, chunk);
            renderData.vertDirty = false;
            sprite._flagChangedVersion = node.flagChangedVersion;
          }
          this.updateColorLate(sprite);
          chunk.bufferId;
          var vid = chunk.vertexOffset;
          var meshBuffer = chunk.meshBuffer;
          var ib = chunk.meshBuffer.iData;
          var indexOffset = meshBuffer.indexOffset;
          for (var i = 0; i < renderData.indexCount; i += 6) {
            ib[indexOffset++] = vid;
            ib[indexOffset++] = vid + 1;
            ib[indexOffset++] = vid + 2;
            ib[indexOffset++] = vid + 1;
            ib[indexOffset++] = vid + 3;
            ib[indexOffset++] = vid + 2;
            vid += 4;
            meshBuffer.indexOffset += 6;
          }
          meshBuffer.setDirty();
        },
        updateWorldUVData: function updateWorldUVData(sprite) {
          var renderData = sprite.renderData;
          var stride = renderData.floatStride;
          var dataList = renderData.data;
          var vData = renderData.chunk.vb;
          for (var i = 0; i < dataList.length; i++) {
            var offset = i * stride;
            vData[offset + 3] = dataList[i].u;
            vData[offset + 4] = dataList[i].v;
          }
        },
        updateWorldVertexAndUVData: function updateWorldVertexAndUVData(sprite, chunk) {
          var node = sprite.node;
          node.getWorldMatrix(m);
          var renderData = sprite.renderData;
          var stride = renderData.floatStride;
          var dataList = renderData.data;
          var vData = chunk.vb;
          var length = dataList.length;
          for (var i = 0; i < length; i++) {
            var x = dataList[i].x;
            var y = dataList[i].y;
            var z = dataList[i].z;
            var rhw = m.m03 * x + m.m07 * y + m.m11 * z + m.m15;
            rhw = rhw ? 1 / rhw : 1;
            var offset = i * stride;
            vData[offset] = (m.m00 * x + m.m04 * y + m.m08 * z + m.m12) * rhw;
            vData[offset + 1] = (m.m01 * x + m.m05 * y + m.m09 * z + m.m13) * rhw;
            vData[offset + 2] = (m.m02 * x + m.m06 * y + m.m10 * z + m.m14) * rhw;
          }
          this.updateWorldUVData(sprite);
        },
        updateVerts: function updateVerts(sprite, sizableWidth, sizableHeight, row, col) {
          var uiTrans = sprite.node._uiProps.uiTransformComp;
          var renderData = sprite.renderData;
          var dataList = renderData.data;
          var frame = sprite.spriteFrame;
          var rect = frame.rect;
          var contentWidth = Math.abs(uiTrans.width);
          var contentHeight = Math.abs(uiTrans.height);
          var appx = uiTrans.anchorX * contentWidth;
          var appy = uiTrans.anchorY * contentHeight;
          var leftWidth = frame.insetLeft;
          var rightWidth = frame.insetRight;
          var centerWidth = rect.width - leftWidth - rightWidth;
          var topHeight = frame.insetTop;
          var bottomHeight = frame.insetBottom;
          var centerHeight = rect.height - topHeight - bottomHeight;
          var xScale = uiTrans.width / (leftWidth + rightWidth) > 1 ? 1 : uiTrans.width / (leftWidth + rightWidth);
          var yScale = uiTrans.height / (topHeight + bottomHeight) > 1 ? 1 : uiTrans.height / (topHeight + bottomHeight);
          var offsetWidth = 0;
          var offsetHeight = 0;
          if (centerWidth > 0) {
            offsetWidth = Math.floor(sizableWidth * 1000) / 1000 % centerWidth === 0 ? centerWidth : sizableWidth % centerWidth;
          } else {
            offsetWidth = sizableWidth;
          }
          if (centerHeight > 0) {
            offsetHeight = Math.floor(sizableHeight * 1000) / 1000 % centerHeight === 0 ? centerHeight : sizableHeight % centerHeight;
          } else {
            offsetHeight = sizableHeight;
          }
          tempRenderData.length = 0;
          tempRenderDataLength = Math.max(row + 1, col + 1);
          for (var i = 0; i < tempRenderDataLength; i++) {
            tempRenderData.push({
              x: 0,
              y: 0,
              z: 0,
              u: 0,
              v: 0,
              color: new Color$1()
            });
          }
          var offsetVertexCount = has9SlicedOffsetVertexCount(frame);
          if (offsetVertexCount === 0) {
            for (var _i = 0; _i < tempRenderDataLength; _i++) {
              if (_i >= col) {
                tempRenderData[_i].x = contentWidth - appx;
              } else {
                tempRenderData[_i].x = -appx + _i * centerWidth;
              }
              if (_i >= row) {
                tempRenderData[_i].y = contentHeight - appy;
              } else {
                tempRenderData[_i].y = -appy + _i * centerHeight;
              }
            }
          } else {
            for (var _i2 = 0; _i2 < tempRenderDataLength; _i2++) {
              if (_i2 === 0) {
                tempRenderData[_i2].x = -appx;
              } else if (_i2 === 1) {
                tempRenderData[_i2].x = -appx + leftWidth * xScale;
              } else if (_i2 > 1 && _i2 < col - 1) {
                if (centerWidth > 0) {
                  tempRenderData[_i2].x = -appx + leftWidth * xScale + centerWidth * (_i2 - 1);
                } else {
                  tempRenderData[_i2].x = leftWidth + sizableWidth - appx;
                }
              } else if (_i2 === col - 1) {
                tempRenderData[_i2].x = -appx + leftWidth * xScale + offsetWidth + centerWidth * (_i2 - 2);
              } else if (_i2 >= col) {
                tempRenderData[_i2].x = Math.min(leftWidth + sizableWidth + rightWidth, contentWidth) - appx;
              }
              if (_i2 === 0) {
                tempRenderData[_i2].y = -appy;
              } else if (_i2 === 1) {
                tempRenderData[_i2].y = -appy + bottomHeight * yScale;
              } else if (_i2 > 1 && _i2 < row - 1) {
                if (centerHeight > 0) {
                  tempRenderData[_i2].y = -appy + bottomHeight * yScale + centerHeight * (_i2 - 1);
                } else {
                  tempRenderData[_i2].y = bottomHeight + sizableHeight - appy;
                }
              } else if (_i2 === row - 1) {
                tempRenderData[_i2].y = -appy + bottomHeight * yScale + offsetHeight + centerHeight * (_i2 - 2);
              } else if (_i2 >= row) {
                tempRenderData[_i2].y = Math.min(bottomHeight + sizableHeight + topHeight, contentHeight) - appy;
              }
            }
          }
          var x = 0;
          var x1 = 0;
          var y = 0;
          var y1 = 0;
          for (var yIndex = 0; yIndex < row; ++yIndex) {
            y = tempRenderData[yIndex].y;
            y1 = tempRenderData[yIndex + 1].y;
            for (var xIndex = 0; xIndex < col; ++xIndex) {
              x = tempRenderData[xIndex].x;
              x1 = tempRenderData[xIndex + 1].x;
              var curIndex = 4 * (yIndex * col + xIndex);
              dataList[curIndex].x = x;
              dataList[curIndex].y = y;
              dataList[curIndex + 1].x = x1;
              dataList[curIndex + 1].y = y;
              dataList[curIndex + 2].x = x;
              dataList[curIndex + 2].y = y1;
              dataList[curIndex + 3].x = x1;
              dataList[curIndex + 3].y = y1;
            }
          }
          var rotated = frame.rotated;
          frame.uv;
          var uvSliced = frame.uvSliced;
          origin = uvSliced[0];
          leftInner = uvSliced[1];
          rightInner = uvSliced[2];
          rightOuter = uvSliced[3];
          bottomInner = uvSliced[4];
          topInner = uvSliced[8];
          topOuter = uvSliced[12];
          var coefU = 0;
          var coefV = 0;
          var hRepeat = centerWidth === 0 ? sizableWidth : sizableWidth / centerWidth;
          var vRepeat = centerHeight === 0 ? sizableHeight : sizableHeight / centerHeight;
          var tempXVerts = [];
          var tempYVerts = [];
          for (var yIndexUV = 0; yIndexUV < row; ++yIndexUV) {
            if (sizableHeight > centerHeight) {
              var curYRectCount = offsetVertexCount > 0 ? yIndexUV : yIndexUV + 1;
              if (sizableHeight >= curYRectCount * centerHeight) {
                coefV = 1;
              } else {
                coefV = vRepeat % 1;
              }
            } else {
              coefV = vRepeat;
            }
            for (var xIndexUV = 0; xIndexUV < col; ++xIndexUV) {
              if (sizableWidth > centerWidth) {
                var curXRectCount = offsetVertexCount > 0 ? xIndexUV : xIndexUV + 1;
                if (sizableWidth >= curXRectCount * centerWidth) {
                  coefU = 1;
                } else {
                  coefU = hRepeat % 1;
                }
              } else {
                coefU = hRepeat;
              }
              if (rotated) {
                if (offsetVertexCount === 0) {
                  tempXVerts[0] = bottomInner.u;
                  tempXVerts[1] = bottomInner.u;
                  tempXVerts[2] = bottomInner.u + (topInner.u - bottomInner.u) * coefV;
                  tempYVerts[0] = leftInner.v;
                  tempYVerts[1] = leftInner.v + (rightInner.v - leftInner.v) * coefU;
                  tempYVerts[2] = leftInner.v;
                } else {
                  if (yIndexUV === 0) {
                    tempXVerts[0] = origin.u;
                    tempXVerts[1] = origin.u;
                    tempXVerts[2] = bottomInner.u;
                  } else if (yIndexUV < row - 1) {
                    tempXVerts[0] = bottomInner.u;
                    tempXVerts[1] = bottomInner.u;
                    tempXVerts[2] = bottomInner.u + (topInner.u - bottomInner.u) * coefV;
                  } else if (yIndexUV === row - 1) {
                    tempXVerts[0] = topInner.u;
                    tempXVerts[1] = topInner.u;
                    tempXVerts[2] = topOuter.u;
                  }
                  if (xIndexUV === 0) {
                    tempYVerts[0] = origin.v;
                    tempYVerts[1] = leftInner.v;
                    tempYVerts[2] = origin.v;
                  } else if (xIndexUV < col - 1) {
                    tempYVerts[0] = leftInner.v;
                    tempYVerts[1] = leftInner.v + (rightInner.v - leftInner.v) * coefU;
                    tempYVerts[2] = leftInner.v;
                  } else if (xIndexUV === col - 1) {
                    tempYVerts[0] = rightInner.v;
                    tempYVerts[1] = rightOuter.v;
                    tempYVerts[2] = rightInner.v;
                  }
                }
                tempXVerts[3] = tempXVerts[2];
                tempYVerts[3] = tempYVerts[1];
              } else {
                if (offsetVertexCount === 0) {
                  tempXVerts[0] = leftInner.u;
                  tempXVerts[1] = leftInner.u + (rightInner.u - leftInner.u) * coefU;
                  tempXVerts[2] = leftInner.u;
                  tempYVerts[0] = bottomInner.v;
                  tempYVerts[1] = bottomInner.v;
                  tempYVerts[2] = bottomInner.v + (topInner.v - bottomInner.v) * coefV;
                } else {
                  if (xIndexUV === 0) {
                    tempXVerts[0] = origin.u;
                    tempXVerts[1] = leftInner.u;
                    tempXVerts[2] = origin.u;
                  } else if (xIndexUV < col - 1) {
                    tempXVerts[0] = leftInner.u;
                    tempXVerts[1] = leftInner.u + (rightInner.u - leftInner.u) * coefU;
                    tempXVerts[2] = leftInner.u;
                  } else if (xIndexUV === col - 1) {
                    tempXVerts[0] = rightInner.u;
                    tempXVerts[1] = rightOuter.u;
                    tempXVerts[2] = rightInner.u;
                  }
                  if (yIndexUV === 0) {
                    tempYVerts[0] = origin.v;
                    tempYVerts[1] = origin.v;
                    tempYVerts[2] = bottomInner.v;
                  } else if (yIndexUV < row - 1) {
                    tempYVerts[0] = bottomInner.v;
                    tempYVerts[1] = bottomInner.v;
                    tempYVerts[2] = bottomInner.v + (topInner.v - bottomInner.v) * coefV;
                  } else if (yIndexUV === row - 1) {
                    tempYVerts[0] = topInner.v;
                    tempYVerts[1] = topInner.v;
                    tempYVerts[2] = topOuter.v;
                  }
                }
                tempXVerts[3] = tempXVerts[1];
                tempYVerts[3] = tempYVerts[2];
              }
              var _curIndex = 4 * (yIndexUV * col + xIndexUV);
              dataList[_curIndex].u = tempXVerts[0];
              dataList[_curIndex].v = tempYVerts[0];
              dataList[_curIndex + 1].u = tempXVerts[1];
              dataList[_curIndex + 1].v = tempYVerts[1];
              dataList[_curIndex + 2].u = tempXVerts[2];
              dataList[_curIndex + 2].v = tempYVerts[2];
              dataList[_curIndex + 3].u = tempXVerts[3];
              dataList[_curIndex + 3].v = tempYVerts[3];
            }
          }
        },
        updateColorLate: function updateColorLate(sprite) {
          var renderData = sprite.renderData;
          var vData = renderData.chunk.vb;
          var stride = renderData.floatStride;
          var vertexCount = renderData.vertexCount;
          var colorOffset = 5;
          var color = sprite.color;
          var colorR = color.r / 255;
          var colorG = color.g / 255;
          var colorB = color.b / 255;
          var colorA = sprite.node._uiProps.opacity;
          for (var i = 0; i < vertexCount; i++) {
            vData[colorOffset] = colorR;
            vData[colorOffset + 1] = colorG;
            vData[colorOffset + 2] = colorB;
            vData[colorOffset + 3] = colorA;
            colorOffset += stride;
          }
        },
        updateColor: function updateColor(sprite) {}
      };

      var SpriteType = Sprite.Type;
      var FillType = Sprite.FillType;
      var spriteAssembler = exports('s', {
        getAssembler: function getAssembler(spriteComp) {
          var util = simple;
          var comp = spriteComp;
          switch (comp.type) {
            case SpriteType.SLICED:
              util = sliced;
              break;
            case SpriteType.TILED:
              util = tiled;
              break;
            case SpriteType.FILLED:
              if (comp.fillType === FillType.RADIAL) {
                util = radialFilled;
              } else {
                util = barFilled;
              }
              break;
          }
          return util;
        }
      });
      Sprite.Assembler = spriteAssembler;

      var mouseEvents = [Input.EventType.MOUSE_DOWN, Input.EventType.MOUSE_MOVE, Input.EventType.MOUSE_UP, Input.EventType.MOUSE_WHEEL];
      var touchEvents = [Input.EventType.TOUCH_START, Input.EventType.TOUCH_MOVE, Input.EventType.TOUCH_END, Input.EventType.TOUCH_CANCEL];
      var PointerEventDispatcher = function () {
        function PointerEventDispatcher() {
          this.priority = EventDispatcherPriority.UI;
          this._isListDirty = false;
          this._inDispatchCount = 0;
          this._pointerEventProcessorList = [];
          this._processorListToAdd = [];
          this._processorListToRemove = [];
          input$1._registerEventDispatcher(this);
          NodeEventProcessor.callbacksInvoker.on(DispatcherEventType.ADD_POINTER_EVENT_PROCESSOR, this.addPointerEventProcessor, this);
          NodeEventProcessor.callbacksInvoker.on(DispatcherEventType.REMOVE_POINTER_EVENT_PROCESSOR, this.removePointerEventProcessor, this);
          NodeEventProcessor.callbacksInvoker.on(DispatcherEventType.MARK_LIST_DIRTY, this._markListDirty, this);
        }
        var _proto = PointerEventDispatcher.prototype;
        _proto.dispatchEvent = function dispatchEvent(event) {
          var eventType = event.type;
          if (touchEvents.includes(eventType)) {
            return this.dispatchEventTouch(event);
          } else if (mouseEvents.includes(eventType)) {
            return this.dispatchEventMouse(event);
          }
          return true;
        };
        _proto.addPointerEventProcessor = function addPointerEventProcessor(pointerEventProcessor) {
          if (this._inDispatchCount === 0) {
            if (!this._pointerEventProcessorList.includes(pointerEventProcessor)) {
              this._pointerEventProcessorList.push(pointerEventProcessor);
              this._isListDirty = true;
            }
          } else if (!this._processorListToAdd.includes(pointerEventProcessor)) {
            this._processorListToAdd.push(pointerEventProcessor);
          }
          remove(this._processorListToRemove, pointerEventProcessor);
        };
        _proto.removePointerEventProcessor = function removePointerEventProcessor(pointerEventProcessor) {
          if (this._inDispatchCount === 0) {
            remove(this._pointerEventProcessorList, pointerEventProcessor);
            this._isListDirty = true;
          } else if (!this._processorListToRemove.includes(pointerEventProcessor)) {
            this._processorListToRemove.push(pointerEventProcessor);
          }
          remove(this._processorListToAdd, pointerEventProcessor);
        };
        _proto.dispatchEventMouse = function dispatchEventMouse(eventMouse) {
          this._inDispatchCount++;
          this._sortPointerEventProcessorList();
          var pointerEventProcessorList = this._pointerEventProcessorList;
          var length = pointerEventProcessorList.length;
          var dispatchToNextEventDispatcher = true;
          for (var i = 0; i < length; ++i) {
            var pointerEventProcessor = pointerEventProcessorList[i];
            if (pointerEventProcessor.isEnabled && pointerEventProcessor.shouldHandleEventMouse && pointerEventProcessor._handleEventMouse(eventMouse)) {
              dispatchToNextEventDispatcher = false;
              if (!eventMouse.preventSwallow) {
                break;
              } else {
                eventMouse.preventSwallow = false;
              }
            }
          }
          if (--this._inDispatchCount <= 0) {
            this._updatePointerEventProcessorList();
          }
          return dispatchToNextEventDispatcher;
        };
        _proto.dispatchEventTouch = function dispatchEventTouch(eventTouch) {
          this._inDispatchCount++;
          this._sortPointerEventProcessorList();
          var pointerEventProcessorList = this._pointerEventProcessorList;
          var length = pointerEventProcessorList.length;
          var touch = eventTouch.touch;
          var dispatchToNextEventDispatcher = true;
          for (var i = 0; i < length; ++i) {
            var pointerEventProcessor = pointerEventProcessorList[i];
            if (pointerEventProcessor.isEnabled && pointerEventProcessor.shouldHandleEventTouch) {
              if (eventTouch.type === InputEventType.TOUCH_START) {
                if (pointerEventProcessor._handleEventTouch(eventTouch)) {
                  pointerEventProcessor.claimedTouchIdList.push(touch.getID());
                  dispatchToNextEventDispatcher = false;
                  if (!eventTouch.preventSwallow) {
                    break;
                  } else {
                    eventTouch.preventSwallow = false;
                  }
                }
              } else if (pointerEventProcessor.claimedTouchIdList.length > 0) {
                var index = pointerEventProcessor.claimedTouchIdList.indexOf(touch.getID());
                if (index !== -1) {
                  pointerEventProcessor._handleEventTouch(eventTouch);
                  if (eventTouch.type === InputEventType.TOUCH_END || eventTouch.type === InputEventType.TOUCH_CANCEL) {
                    removeAt(pointerEventProcessor.claimedTouchIdList, index);
                  }
                  dispatchToNextEventDispatcher = false;
                  if (!eventTouch.preventSwallow) {
                    break;
                  } else {
                    eventTouch.preventSwallow = false;
                  }
                }
              }
            }
          }
          if (--this._inDispatchCount <= 0) {
            this._updatePointerEventProcessorList();
          }
          return dispatchToNextEventDispatcher;
        };
        _proto._updatePointerEventProcessorList = function _updatePointerEventProcessorList() {
          var listToAdd = this._processorListToAdd;
          var addLength = listToAdd.length;
          for (var i = 0; i < addLength; ++i) {
            this.addPointerEventProcessor(listToAdd[i]);
          }
          listToAdd.length = 0;
          var listToRemove = this._processorListToRemove;
          var removeLength = listToRemove.length;
          for (var _i = 0; _i < removeLength; ++_i) {
            this.removePointerEventProcessor(listToRemove[_i]);
          }
          listToRemove.length = 0;
        };
        _proto._sortPointerEventProcessorList = function _sortPointerEventProcessorList() {
          if (!this._isListDirty) {
            return;
          }
          var pointerEventProcessorList = this._pointerEventProcessorList;
          var length = pointerEventProcessorList.length;
          for (var i = 0; i < length; ++i) {
            var pointerEventProcessor = pointerEventProcessorList[i];
            var node = pointerEventProcessor.node;
            if (node._uiProps) {
              var trans = node._uiProps.uiTransformComp;
              pointerEventProcessor.cachedCameraPriority = trans.cameraPriority;
            }
          }
          pointerEventProcessorList.sort(this._sortByPriority);
          this._isListDirty = false;
        };
        _proto._sortByPriority = function _sortByPriority(p1, p2) {
          var node1 = p1.node;
          var node2 = p2.node;
          if (!p2 || !node2 || !node2.activeInHierarchy || !node2._uiProps.uiTransformComp) {
            return -1;
          } else if (!p1 || !node1 || !node1.activeInHierarchy || !node1._uiProps.uiTransformComp) {
            return 1;
          }
          if (p1.cachedCameraPriority !== p2.cachedCameraPriority) {
            return p2.cachedCameraPriority - p1.cachedCameraPriority;
          }
          var n1 = node1;
          var n2 = node2;
          var ex = false;
          while (((_parent = n1.parent) === null || _parent === void 0 ? void 0 : _parent.uuid) !== ((_parent2 = n2.parent) === null || _parent2 === void 0 ? void 0 : _parent2.uuid)) {
            var _parent, _parent2, _n, _n$parent, _n2, _n2$parent;
            n1 = ((_n = n1) === null || _n === void 0 ? void 0 : (_n$parent = _n.parent) === null || _n$parent === void 0 ? void 0 : _n$parent.parent) === null ? (ex = true) && node2 : n1 && n1.parent;
            n2 = ((_n2 = n2) === null || _n2 === void 0 ? void 0 : (_n2$parent = _n2.parent) === null || _n2$parent === void 0 ? void 0 : _n2$parent.parent) === null ? (ex = true) && node1 : n2 && n2.parent;
          }
          if (n1.uuid === n2.uuid) {
            if (n1.uuid === node2.uuid) {
              return -1;
            }
            if (n1.uuid === node1.uuid) {
              return 1;
            }
          }
          var priority1 = n1 ? n1.getSiblingIndex() : 0;
          var priority2 = n2 ? n2.getSiblingIndex() : 0;
          return ex ? priority1 - priority2 : priority2 - priority1;
        };
        _proto._markListDirty = function _markListDirty() {
          this._isListDirty = true;
        };
        return PointerEventDispatcher;
      }();
      new PointerEventDispatcher();

      var _dsInfo = new DescriptorSetInfo(null);
      var m4_1$5 = new Mat4();
      var Batcher2D = function () {
        function Batcher2D(_root) {
          var _this = this;
          this.device = void 0;
          this._screens = [];
          this._staticVBBuffer = null;
          this._bufferAccessors = new Map();
          this._drawBatchPool = void 0;
          this._batches = void 0;
          this._currBID = -1;
          this._indexStart = 0;
          this._emptyMaterial = new Material();
          this._currRenderData = null;
          this._currMaterial = this._emptyMaterial;
          this._currTexture = null;
          this._currSampler = null;
          this._currStaticRoot = null;
          this._currComponent = null;
          this._currTransform = null;
          this._currTextureHash = 0;
          this._currSamplerHash = 0;
          this._currLayer = 0;
          this._currDepthStencilStateStage = null;
          this._currIsStatic = false;
          this._currHash = 0;
          this._currIsMiddleware = false;
          this._middlewareEnableBatch = false;
          this._middlewareBuffer = null;
          this._middlewareIndexStart = 0;
          this._middlewareIndexCount = 0;
          this._pOpacity = 1;
          this._opacityDirty = 0;
          this._descriptorSetCache = new DescriptorSetCache();
          this._meshDataArray = [];
          this._maskClearModel = null;
          this._maskClearMtl = null;
          this._maskModelMesh = null;
          this._root = _root;
          this.device = _root.device;
          this._batches = new CachedArray(64);
          this._drawBatchPool = new Pool(function () {
            return new DrawBatch2D();
          }, 128, function (obj) {
            return obj.destroy(_this);
          });
        }
        var _proto = Batcher2D.prototype;
        _proto.initialize = function initialize() {
          return true;
        };
        _proto.destroy = function destroy() {
          for (var i = 0; i < this._batches.length; i++) {
            if (this._batches.array[i]) {
              this._batches.array[i].destroy(this);
            }
          }
          this._batches.destroy();
          for (var _iterator = _createForOfIteratorHelperLoose(this._bufferAccessors.values()), _step; !(_step = _iterator()).done;) {
            var accessor = _step.value;
            accessor.destroy();
          }
          this._bufferAccessors.clear();
          if (this._drawBatchPool) {
            this._drawBatchPool.destroy();
          }
          this._descriptorSetCache.destroy();
          StencilManager.sharedManager.destroy();
          if (this._maskClearModel && this._maskModelMesh) {
            legacyCC.director.root.destroyModel(this._maskClearModel);
            this._maskModelMesh.destroy();
          }
          if (this._maskClearMtl) {
            this._maskClearMtl.destroy();
          }
        };
        _proto.syncRootNodesToNative = function syncRootNodesToNative() {
        };
        _proto.addScreen = function addScreen(comp) {
          this._screens.push(comp);
          this._screens.sort(this._screenSort);
        };
        _proto.removeScreen = function removeScreen(comp) {
          var idx = this._screens.indexOf(comp);
          if (idx === -1) {
            return;
          }
          this._screens.splice(idx, 1);
        };
        _proto.sortScreens = function sortScreens() {
          this._screens.sort(this._screenSort);
        };
        _proto.getFirstRenderCamera = function getFirstRenderCamera(node) {
          if (node.scene && node.scene.renderScene) {
            var cameras = node.scene.renderScene.cameras;
            for (var i = 0; i < cameras.length; i++) {
              var camera = cameras[i];
              if (camera.visibility & node.layer) {
                return camera;
              }
            }
          }
          return null;
        };
        _proto.update = function update() {
          var screens = this._screens;
          var offset = 0;
          for (var i = 0; i < screens.length; ++i) {
            var screen = screens[i];
            var _scene = screen._getRenderScene();
            if (!screen.enabledInHierarchy || !_scene) {
              continue;
            }
            this._opacityDirty = 0;
            this._pOpacity = 1;
            this.walk(screen.node);
            this.autoMergeBatches(this._currComponent);
            this.resetRenderStates();
            var batchPriority = 0;
            if (this._batches.length > offset) {
              for (; offset < this._batches.length; ++offset) {
                var batch = this._batches.array[offset];
                if (batch.model) {
                  var subModels = batch.model.subModels;
                  for (var j = 0; j < subModels.length; j++) {
                    subModels[j].priority = batchPriority++;
                  }
                } else {
                  batch.descriptorSet = this._descriptorSetCache.getDescriptorSet(batch);
                }
                _scene.addBatch(batch);
              }
            }
          }
        };
        _proto.uploadBuffers = function uploadBuffers() {
          if (this._batches.length > 0) {
            var length = this._meshDataArray.length;
            for (var i = 0; i < length; i++) {
              this._meshDataArray[i].uploadBuffers();
            }
            for (var _iterator3 = _createForOfIteratorHelperLoose(this._bufferAccessors.values()), _step3; !(_step3 = _iterator3()).done;) {
              var accessor = _step3.value;
              accessor.uploadBuffers();
              accessor.reset();
            }
            this._descriptorSetCache.update();
          }
        };
        _proto.reset = function reset() {
          {
            for (var i = 0; i < this._batches.length; ++i) {
              var batch = this._batches.array[i];
              if (batch.isStatic) {
                continue;
              }
              batch.clear();
              this._drawBatchPool.free(batch);
            }
            for (var _iterator4 = _createForOfIteratorHelperLoose(this._bufferAccessors.values()), _step4; !(_step4 = _iterator4()).done;) {
              var accessor = _step4.value;
              accessor.reset();
            }
            var length = this._meshDataArray.length;
            for (var _i = 0; _i < length; _i++) {
              this._meshDataArray[_i].freeIAPool();
            }
            this._meshDataArray.length = 0;
            this._staticVBBuffer = null;
            this._currBID = -1;
            this._indexStart = 0;
            this._currHash = 0;
            this._currLayer = 0;
            this._currRenderData = null;
            this._currMaterial = this._emptyMaterial;
            this._currTexture = null;
            this._currSampler = null;
            this._currComponent = null;
            this._currTransform = null;
            this._batches.clear();
            StencilManager.sharedManager.reset();
          }
        };
        _proto.switchBufferAccessor = function switchBufferAccessor(attributes) {
          if (attributes === void 0) {
            attributes = vfmtPosUvColor;
          }
          var strideBytes = attributes === vfmtPosUvColor ? 36 : getAttributeStride(attributes);
          if (!this._staticVBBuffer || this._staticVBBuffer.vertexFormatBytes !== strideBytes) {
            var accessor = this._bufferAccessors.get(strideBytes);
            if (!accessor) {
              accessor = new StaticVBAccessor(this.device, attributes);
              this._bufferAccessors.set(strideBytes, accessor);
            }
            this._staticVBBuffer = accessor;
            this._currBID = -1;
          }
          return this._staticVBBuffer;
        };
        _proto.registerBufferAccessor = function registerBufferAccessor(key, accessor) {
          this._bufferAccessors.set(key, accessor);
        };
        _proto.updateBuffer = function updateBuffer(attributes, bid) {
          var accessor = this.switchBufferAccessor(attributes);
          if (this._currBID !== bid) {
            this._currBID = bid;
            this._indexStart = accessor.getMeshBuffer(bid).indexOffset;
          }
        };
        _proto.commitComp = function commitComp(comp, renderData, frame, assembler, transform) {
          var dataHash = 0;
          var mat;
          var bufferID = -1;
          if (renderData && renderData.chunk) {
            if (!renderData.isValid()) return;
            dataHash = renderData.dataHash;
            mat = renderData.material;
            bufferID = renderData.chunk.bufferId;
          }
          if (comp.stencilStage === Stage.ENTER_LEVEL || comp.stencilStage === Stage.ENTER_LEVEL_INVERTED) {
            this._insertMaskBatch(comp);
          } else {
            comp.stencilStage = StencilManager.sharedManager.stage;
          }
          var depthStencilStateStage = comp.stencilStage;
          if (this._currHash !== dataHash || dataHash === 0 || this._currMaterial !== mat || this._currDepthStencilStateStage !== depthStencilStateStage) {
            this.autoMergeBatches(this._currComponent);
            if (renderData && !renderData._isMeshBuffer) {
              this.updateBuffer(renderData.vertexFormat, bufferID);
            }
            this._currRenderData = renderData;
            this._currHash = renderData ? renderData.dataHash : 0;
            this._currComponent = comp;
            this._currTransform = transform;
            this._currMaterial = comp.getRenderMaterial(0);
            this._currDepthStencilStateStage = depthStencilStateStage;
            this._currLayer = comp.node.layer;
            if (frame) {
              {
                assert(frame.isValid, 'frame should not be invalid, it may have been released');
              }
              this._currTexture = frame.getGFXTexture();
              this._currSampler = frame.getGFXSampler();
              this._currTextureHash = frame.getHash();
              this._currSamplerHash = this._currSampler.hash;
            } else {
              this._currTexture = null;
              this._currSampler = null;
              this._currTextureHash = 0;
              this._currSamplerHash = 0;
            }
          }
          assembler.fillBuffers(comp, this);
        };
        _proto.commitIA = function commitIA(renderComp, ia, tex, mat, transform) {
          if (this._currMaterial !== this._emptyMaterial) {
            this.autoMergeBatches(this._currComponent);
            this.resetRenderStates();
          }
          var depthStencil;
          var dssHash = 0;
          if (renderComp) {
            renderComp.stencilStage = StencilManager.sharedManager.stage;
            if (renderComp.customMaterial !== null) {
              depthStencil = StencilManager.sharedManager.getStencilStage(renderComp.stencilStage, mat);
            } else {
              depthStencil = StencilManager.sharedManager.getStencilStage(renderComp.stencilStage);
            }
            dssHash = StencilManager.sharedManager.getStencilHash(renderComp.stencilStage);
          }
          var curDrawBatch = this._currStaticRoot ? this._currStaticRoot._requireDrawBatch() : this._drawBatchPool.alloc();
          curDrawBatch.visFlags = renderComp.node.layer;
          curDrawBatch.inputAssembler = ia;
          curDrawBatch.useLocalData = transform || null;
          if (tex) {
            curDrawBatch.texture = tex.getGFXTexture();
            curDrawBatch.sampler = tex.getGFXSampler();
            curDrawBatch.textureHash = tex.getHash();
            curDrawBatch.samplerHash = curDrawBatch.sampler.hash;
          }
          curDrawBatch.fillPasses(mat || null, depthStencil, dssHash, null);
          this._batches.push(curDrawBatch);
        };
        _proto.commitMiddleware = function commitMiddleware(comp, meshBuffer, indexOffset, indexCount, tex, mat, enableBatch) {
          var texture = tex.getGFXTexture();
          if (enableBatch && this._middlewareEnableBatch && this._middlewareBuffer === meshBuffer && this._currTexture === texture && this._currMaterial.hash === mat.hash && this._middlewareIndexStart + this._middlewareIndexCount === indexOffset && this._currLayer === comp.node.layer) {
            this._middlewareIndexCount += indexCount;
          } else {
            this.autoMergeBatches(this._currComponent);
            this.resetRenderStates();
            this._currComponent = comp;
            this._currTexture = texture;
            this._currSampler = tex.getGFXSampler();
            this._currTextureHash = tex.getHash();
            this._currLayer = comp.node.layer;
            this._currSamplerHash = this._currSampler.hash;
            this._currHash = 0;
            this._currTransform = enableBatch ? null : comp.node;
            this._middlewareEnableBatch = enableBatch;
            this._middlewareBuffer = meshBuffer;
            this._currMaterial = mat;
            this._middlewareIndexStart = indexOffset;
            this._middlewareIndexCount = indexCount;
          }
          this._currIsMiddleware = true;
        };
        _proto.commitModel = function commitModel(comp, model, mat) {
          if (this._currMaterial !== this._emptyMaterial) {
            this.autoMergeBatches(this._currComponent);
            this.resetRenderStates();
          }
          var depthStencil;
          var dssHash = 0;
          if (mat) {
            if (comp.stencilStage === Stage.ENTER_LEVEL || comp.stencilStage === Stage.ENTER_LEVEL_INVERTED) {
              this._insertMaskBatch(comp);
            } else {
              comp.stencilStage = StencilManager.sharedManager.stage;
            }
            depthStencil = StencilManager.sharedManager.getStencilStage(comp.stencilStage, mat);
            dssHash = StencilManager.sharedManager.getStencilHash(comp.stencilStage);
          }
          var stamp = legacyCC.director.getTotalFrames();
          if (model) {
            model.updateTransform(stamp);
            model.updateUBOs(stamp);
          }
          for (var i = 0; i < model.subModels.length; i++) {
            var curDrawBatch = this._drawBatchPool.alloc();
            var subModel = model.subModels[i];
            curDrawBatch.visFlags = comp.node.layer;
            curDrawBatch.model = model;
            curDrawBatch.texture = null;
            curDrawBatch.sampler = null;
            curDrawBatch.useLocalData = null;
            if (!depthStencil) {
              depthStencil = null;
            }
            curDrawBatch.fillPasses(mat, depthStencil, dssHash, subModel.patches);
            curDrawBatch.inputAssembler = subModel.inputAssembler;
            curDrawBatch.model.visFlags = curDrawBatch.visFlags;
            curDrawBatch.descriptorSet = subModel.descriptorSet;
            this._batches.push(curDrawBatch);
          }
        };
        _proto.setupStaticBatch = function setupStaticBatch(staticComp, bufferAccessor) {
          this.finishMergeBatches();
          this._staticVBBuffer = bufferAccessor;
          this.currStaticRoot = staticComp;
        };
        _proto.endStaticBatch = function endStaticBatch() {
          this.finishMergeBatches();
          this.currStaticRoot = null;
          this._staticVBBuffer = null;
          this.switchBufferAccessor();
        };
        _proto.commitStaticBatch = function commitStaticBatch(comp) {
          this._batches.concat(comp.drawBatchList);
          this.finishMergeBatches();
        };
        _proto.autoMergeBatches = function autoMergeBatches(renderComp) {
          if (this._currIsMiddleware) {
            this.mergeBatchesForMiddleware(renderComp);
            return;
          }
          var mat = this._currMaterial;
          if (!mat) {
            return;
          }
          var ia;
          var rd = this._currRenderData;
          var accessor = this._staticVBBuffer;
          if (rd && rd._isMeshBuffer) {
            ia = rd.requestIA(this.device);
            if (this._meshDataArray.indexOf(rd) === -1) {
              this._meshDataArray.push(rd);
            }
          } else if (accessor) {
            var bid = this._currBID;
            var buf = accessor.getMeshBuffer(bid);
            if (!buf) {
              return;
            }
            var indexCount = buf.indexOffset - this._indexStart;
            if (indexCount <= 0) return;
            assertIsTrue(this._indexStart < buf.indexOffset);
            buf.setDirty();
            ia = buf.requireFreeIA(this.device);
            ia.firstIndex = this._indexStart;
            ia.indexCount = indexCount;
            this._indexStart = buf.indexOffset;
          }
          this._currBID = -1;
          if (!ia) {
            return;
          }
          var depthStencil;
          var dssHash = 0;
          if (renderComp) {
            if (renderComp.customMaterial !== null) {
              depthStencil = StencilManager.sharedManager.getStencilStage(renderComp.stencilStage, mat);
            } else {
              depthStencil = StencilManager.sharedManager.getStencilStage(renderComp.stencilStage);
            }
            dssHash = StencilManager.sharedManager.getStencilHash(renderComp.stencilStage);
          }
          var curDrawBatch = this._currStaticRoot ? this._currStaticRoot._requireDrawBatch() : this._drawBatchPool.alloc();
          curDrawBatch.visFlags = this._currLayer;
          curDrawBatch.texture = this._currTexture;
          curDrawBatch.sampler = this._currSampler;
          curDrawBatch.inputAssembler = ia;
          curDrawBatch.useLocalData = this._currTransform;
          curDrawBatch.textureHash = this._currTextureHash;
          curDrawBatch.samplerHash = this._currSamplerHash;
          curDrawBatch.fillPasses(mat, depthStencil, dssHash, null);
          this._batches.push(curDrawBatch);
        };
        _proto.mergeBatchesForMiddleware = function mergeBatchesForMiddleware(renderComp) {
          var depthStencil;
          var dssHash = 0;
          renderComp.stencilStage = StencilManager.sharedManager.stage;
          if (renderComp.customMaterial !== null) {
            depthStencil = StencilManager.sharedManager.getStencilStage(renderComp.stencilStage, this._currMaterial);
          } else {
            depthStencil = StencilManager.sharedManager.getStencilStage(renderComp.stencilStage);
          }
          dssHash = StencilManager.sharedManager.getStencilHash(renderComp.stencilStage);
          var curDrawBatch = this._currStaticRoot ? this._currStaticRoot._requireDrawBatch() : this._drawBatchPool.alloc();
          curDrawBatch.visFlags = renderComp.node.layer;
          var ia = this._middlewareBuffer.requireFreeIA(this.device);
          ia.firstIndex = this._middlewareIndexStart;
          ia.indexCount = this._middlewareIndexCount;
          curDrawBatch.inputAssembler = ia;
          curDrawBatch.useLocalData = this._currTransform;
          curDrawBatch.texture = this._currTexture;
          curDrawBatch.sampler = this._currSampler;
          curDrawBatch.textureHash = this._currTextureHash;
          curDrawBatch.samplerHash = this._currSamplerHash;
          curDrawBatch.fillPasses(this._currMaterial || null, depthStencil, dssHash, null);
          this._batches.push(curDrawBatch);
          this._currIsMiddleware = false;
          this._middlewareBuffer = null;
        };
        _proto.forceMergeBatches = function forceMergeBatches(material, frame, renderComp) {
          this._currMaterial = material;
          if (frame) {
            this._currTexture = frame.getGFXTexture();
            this._currSampler = frame.getGFXSampler();
            this._currTextureHash = frame.getHash();
            this._currSamplerHash = this._currSampler.hash;
          } else {
            this._currTexture = this._currSampler = null;
            this._currTextureHash = this._currSamplerHash = 0;
          }
          this._currLayer = renderComp.node.layer;
          this.autoMergeBatches(renderComp);
        };
        _proto.resetRenderStates = function resetRenderStates() {
          this._currMaterial = this._emptyMaterial;
          this._currRenderData = null;
          this._currTexture = null;
          this._currComponent = null;
          this._currTransform = null;
          this._currTextureHash = 0;
          this._currSamplerHash = 0;
          this._currLayer = 0;
        };
        _proto.finishMergeBatches = function finishMergeBatches() {
          this.autoMergeBatches();
          this.resetRenderStates();
        };
        _proto.flushMaterial = function flushMaterial(mat) {
          this._currMaterial = mat;
        };
        _proto.walk = function walk(node, level) {
          if (level === void 0) {
            level = 0;
          }
          if (!node.activeInHierarchy) {
            return;
          }
          var children = node.children;
          var uiProps = node._uiProps;
          var render = uiProps.uiComp;
          var parentOpacity = this._pOpacity;
          var opacity = parentOpacity;
          var selfOpacity = render && render.color ? render.color.a / 255 : 1;
          this._pOpacity = opacity *= selfOpacity * uiProps.localOpacity;
          uiProps.setOpacity(opacity);
          if (!approx(opacity, 0, EPSILON$3)) {
            if (uiProps.colorDirty) {
              this._opacityDirty++;
            }
            if (render && render.enabledInHierarchy) {
              render.fillBuffers(this);
            }
            if (this._opacityDirty && render && !render.useVertexOpacity && render.renderData && render.renderData.vertexCount > 0) {
              updateOpacity(render.renderData, opacity);
              var buffer = render.renderData.getMeshBuffer();
              if (buffer) {
                buffer.setDirty();
              }
            }
            if (children.length > 0 && !node._static) {
              for (var i = 0; i < children.length; ++i) {
                var child = children[i];
                this.walk(child, level);
              }
            }
            if (uiProps.colorDirty) {
              this._opacityDirty--;
              uiProps.colorDirty = false;
            }
          }
          this._pOpacity = parentOpacity;
          if (render && render.enabledInHierarchy) {
            render.postUpdateAssembler(this);
            if ((render.stencilStage === Stage.ENTER_LEVEL || render.stencilStage === Stage.ENTER_LEVEL_INVERTED) && StencilManager.sharedManager.getMaskStackSize() > 0) {
              this.autoMergeBatches(this._currComponent);
              this.resetRenderStates();
              StencilManager.sharedManager.exitMask();
            }
          }
          level += 1;
        };
        _proto._screenSort = function _screenSort(a, b) {
          return a.node.getSiblingIndex() - b.node.getSiblingIndex();
        };
        _proto._releaseDescriptorSetCache = function _releaseDescriptorSetCache(textureHash, sampler) {
          {
            this._descriptorSetCache.releaseDescriptorSetCache(textureHash);
          }
        };
        _proto._createClearModel = function _createClearModel() {
          if (!this._maskClearModel) {
            this._maskClearMtl = builtinResMgr.get('default-clear-stencil');
            this._maskClearModel = legacyCC.director.root.createModel(Model);
            var stride = getAttributeStride(vfmt);
            var gfxDevice = deviceManager.gfxDevice;
            var vertexBuffer = gfxDevice.createBuffer(new BufferInfo(BufferUsageBit.VERTEX | BufferUsageBit.TRANSFER_DST, MemoryUsageBit.DEVICE, 4 * stride, stride));
            var vb = new Float32Array([-1, -1, 0, 1, -1, 0, -1, 1, 0, 1, 1, 0]);
            vertexBuffer.update(vb);
            var indexBuffer = gfxDevice.createBuffer(new BufferInfo(BufferUsageBit.INDEX | BufferUsageBit.TRANSFER_DST, MemoryUsageBit.DEVICE, 6 * Uint16Array.BYTES_PER_ELEMENT, Uint16Array.BYTES_PER_ELEMENT));
            var ib = new Uint16Array([0, 1, 2, 2, 1, 3]);
            indexBuffer.update(ib);
            this._maskModelMesh = new RenderingSubMesh([vertexBuffer], vfmt, PrimitiveMode.TRIANGLE_LIST, indexBuffer);
            this._maskModelMesh.subMeshIdx = 0;
            this._maskClearModel.initSubModel(0, this._maskModelMesh, this._maskClearMtl);
          }
        };
        _proto._insertMaskBatch = function _insertMaskBatch(comp) {
          this.autoMergeBatches(this._currComponent);
          this.resetRenderStates();
          this._createClearModel();
          this._maskClearModel.node = this._maskClearModel.transform = comp.node;
          var _stencilManager = StencilManager.sharedManager;
          _stencilManager.pushMask(1);
          var stage = _stencilManager.clear(comp);
          var depthStencil;
          var dssHash = 0;
          var mat = this._maskClearMtl;
          if (mat) {
            depthStencil = _stencilManager.getStencilStage(stage, mat);
            dssHash = _stencilManager.getStencilHash(stage);
          }
          var model = this._maskClearModel;
          var stamp = legacyCC.director.getTotalFrames();
          if (model) {
            model.updateTransform(stamp);
            model.updateUBOs(stamp);
          }
          for (var i = 0; i < model.subModels.length; i++) {
            var curDrawBatch = this._drawBatchPool.alloc();
            var subModel = model.subModels[i];
            curDrawBatch.visFlags = comp.node.layer;
            curDrawBatch.model = model;
            curDrawBatch.texture = null;
            curDrawBatch.sampler = null;
            curDrawBatch.useLocalData = null;
            if (!depthStencil) {
              depthStencil = null;
            }
            curDrawBatch.fillPasses(mat, depthStencil, dssHash, subModel.patches);
            curDrawBatch.inputAssembler = subModel.inputAssembler;
            curDrawBatch.model.visFlags = curDrawBatch.visFlags;
            curDrawBatch.descriptorSet = subModel.descriptorSet;
            this._batches.push(curDrawBatch);
          }
          _stencilManager.enableMask();
        };
        _proto.syncMeshBuffersToNative = function syncMeshBuffersToNative(accId, buffers) {
        };
        _createClass(Batcher2D, [{
          key: "nativeObj",
          get: function get() {
            return this._nativeObj;
          }
        }, {
          key: "currBufferAccessor",
          get: function get() {
            if (this._staticVBBuffer) return this._staticVBBuffer;
            this._staticVBBuffer = this.switchBufferAccessor();
            return this._staticVBBuffer;
          }
        }, {
          key: "batches",
          get: function get() {
            return this._batches;
          }
        }, {
          key: "currStaticRoot",
          set: function set(value) {
            this._currStaticRoot = value;
          }
        }, {
          key: "currIsStatic",
          set: function set(value) {
            this._currIsStatic = value;
          }
        }]);
        return Batcher2D;
      }();
      var LocalDescriptorSet = function () {
        function LocalDescriptorSet() {
          this._descriptorSet = null;
          this._transform = null;
          this._textureHash = 0;
          this._samplerHash = 0;
          this._localBuffer = null;
          this._transformUpdate = true;
          var device = deviceManager.gfxDevice;
          this._localData = new Float32Array(UBOLocal.COUNT);
          this._localBuffer = device.createBuffer(new BufferInfo(BufferUsageBit.UNIFORM | BufferUsageBit.TRANSFER_DST, MemoryUsageBit.HOST | MemoryUsageBit.DEVICE, UBOLocal.SIZE, UBOLocal.SIZE));
        }
        var _proto2 = LocalDescriptorSet.prototype;
        _proto2.initialize = function initialize(batch) {
          var device = deviceManager.gfxDevice;
          this._transform = batch.useLocalData;
          this._textureHash = batch.textureHash;
          this._samplerHash = batch.samplerHash;
          _dsInfo.layout = batch.passes[0].localSetLayout;
          this._descriptorSet = device.createDescriptorSet(_dsInfo);
          this._descriptorSet.bindBuffer(UBOLocal.BINDING, this._localBuffer);
          var binding = ModelLocalBindings.SAMPLER_SPRITE;
          this._descriptorSet.bindTexture(binding, batch.texture);
          this._descriptorSet.bindSampler(binding, batch.sampler);
          this._descriptorSet.update();
          this._transformUpdate = true;
        };
        _proto2.updateTransform = function updateTransform(transform) {
          if (transform === this._transform) return;
          this._transform = transform;
          this._transformUpdate = true;
          this.uploadLocalData();
        };
        _proto2.equals = function equals(transform, textureHash, samplerHash) {
          return this._transform === transform && this._textureHash === textureHash && this._samplerHash === samplerHash;
        };
        _proto2.reset = function reset() {
          this._transform = null;
          this._textureHash = 0;
          this._samplerHash = 0;
        };
        _proto2.destroy = function destroy() {
          if (this._localBuffer) {
            this._localBuffer.destroy();
            this._localBuffer = null;
          }
          if (this._descriptorSet) {
            this._descriptorSet.destroy();
            this._descriptorSet = null;
          }
          this._localData = null;
        };
        _proto2.isValid = function isValid() {
          return this._transform && this._transform.isValid;
        };
        _proto2.uploadLocalData = function uploadLocalData() {
          var node = this._transform;
          if (node.hasChangedFlags || node.isTransformDirty()) {
            node.updateWorldTransform();
            this._transformUpdate = true;
          }
          if (this._transformUpdate) {
            var worldMatrix = node.worldMatrix;
            Mat4.toArray(this._localData, worldMatrix, UBOLocal.MAT_WORLD_OFFSET);
            Mat4.invert(m4_1$5, worldMatrix);
            Mat4.transpose(m4_1$5, m4_1$5);
            {
              var det = Mat4.determinant(m4_1$5);
              var factor = 1.0 / Math.sqrt(det);
              Mat4.multiplyScalar(m4_1$5, m4_1$5, factor);
            }
            Mat4.toArray(this._localData, m4_1$5, UBOLocal.MAT_WORLD_IT_OFFSET);
            this._localBuffer.update(this._localData);
            this._transformUpdate = false;
          }
        };
        _createClass(LocalDescriptorSet, [{
          key: "descriptorSet",
          get: function get() {
            return this._descriptorSet;
          }
        }]);
        return LocalDescriptorSet;
      }();
      var DescriptorSetCache = function () {
        function DescriptorSetCache() {
          this._descriptorSetCache = new Map();
          this._dsCacheHashByTexture = new Map();
          this._localDescriptorSetCache = [];
          this._localCachePool = void 0;
          this._localCachePool = new Pool(function () {
            return new LocalDescriptorSet();
          }, 16, function (obj) {
            return obj.destroy();
          });
        }
        var _proto3 = DescriptorSetCache.prototype;
        _proto3.getDescriptorSet = function getDescriptorSet(batch) {
          legacyCC.director.root;
          var hash;
          if (batch.useLocalData) {
            var caches = this._localDescriptorSetCache;
            for (var i = 0, len = caches.length; i < len; i++) {
              var cache = caches[i];
              if (cache.equals(batch.useLocalData, batch.textureHash, batch.samplerHash)) {
                return cache.descriptorSet;
              }
            }
            var localDs = this._localCachePool.alloc();
            localDs.initialize(batch);
            this._localDescriptorSetCache.push(localDs);
            return localDs.descriptorSet;
          } else {
            hash = batch.textureHash ^ batch.samplerHash;
            if (this._descriptorSetCache.has(hash)) {
              return this._descriptorSetCache.get(hash);
            } else {
              _dsInfo.layout = batch.passes[0].localSetLayout;
              var descriptorSet = deviceManager.gfxDevice.createDescriptorSet(_dsInfo);
              var binding = ModelLocalBindings.SAMPLER_SPRITE;
              descriptorSet.bindTexture(binding, batch.texture);
              descriptorSet.bindSampler(binding, batch.sampler);
              descriptorSet.update();
              this._descriptorSetCache.set(hash, descriptorSet);
              this._dsCacheHashByTexture.set(batch.textureHash, hash);
              return descriptorSet;
            }
          }
        };
        _proto3.update = function update() {
          var caches = this._localDescriptorSetCache;
          var length = caches.length;
          if (length === 0) {
            return;
          }
          var uselessArray = [];
          for (var i = 0; i < length; i++) {
            var value = caches[i];
            if (value.isValid()) {
              value.uploadLocalData();
            } else {
              value.reset();
              var pos = caches.indexOf(value);
              uselessArray.push(pos);
            }
          }
          for (var _i2 = uselessArray.length - 1; _i2 >= 0; _i2--) {
            var index = uselessArray[_i2];
            var localDs = caches[index];
            caches.splice(index, 1);
            this._localCachePool.free(localDs);
          }
        };
        _proto3.reset = function reset() {
          var caches = this._localDescriptorSetCache;
          var length = caches.length;
          for (var i = 0; i < length; i++) {
            var value = caches[i];
            this._localCachePool.free(value);
          }
          this._localDescriptorSetCache.length = 0;
        };
        _proto3.releaseDescriptorSetCache = function releaseDescriptorSetCache(textureHash) {
          var key = this._dsCacheHashByTexture.get(textureHash);
          if (key && this._descriptorSetCache.has(key)) {
            this._descriptorSetCache.get(key).destroy();
            this._descriptorSetCache["delete"](key);
            this._dsCacheHashByTexture["delete"](textureHash);
          }
        };
        _proto3.destroy = function destroy() {
          for (var _iterator5 = _createForOfIteratorHelperLoose(this._descriptorSetCache.values()), _step5; !(_step5 = _iterator5()).done;) {
            var value = _step5.value;
            value.destroy();
          }
          this._descriptorSetCache.clear();
          this._dsCacheHashByTexture.clear();
          this._localDescriptorSetCache.length = 0;
          this._localCachePool.destroy();
        };
        return DescriptorSetCache;
      }();
      legacyCC.internal.Batcher2D = Batcher2D;

      var ccdocument$1 = ccwindow.document;
      var _canvasContext = null;
      var _intervalId = -1;
      var _testString = "BES bswy:->@123\u4E01\u3041\u1101";
      var _fontFaces = Object.create(null);
      var _loadingFonts = [];
      var _timeout = 3000;
      var useNativeCheck = function () {
        var nativeCheck;
        return function () {
          if (nativeCheck === undefined) {
            if ('FontFace' in ccwindow) {
              var match = /Gecko.*Firefox\/(\d+)/.exec(ccwindow.navigator.userAgent);
              var safari10Match = /OS X.*Version\/10\..*Safari/.exec(ccwindow.navigator.userAgent) && /Apple/.exec(ccwindow.navigator.vendor);
              if (match) {
                nativeCheck = parseInt(match[1], 10) > 42;
              } else if (safari10Match) {
                nativeCheck = false;
              } else {
                nativeCheck = true;
              }
            } else {
              nativeCheck = false;
            }
          }
          return nativeCheck;
        };
      }();
      function checkFontLoaded() {
        var allFontsLoaded = true;
        var now = Date.now();
        for (var i = _loadingFonts.length - 1; i >= 0; i--) {
          var fontLoadHandle = _loadingFonts[i];
          var fontFamily = fontLoadHandle.fontFamilyName;
          if (now - fontLoadHandle.startTime > _timeout) {
            warnID(4933, fontFamily);
            fontLoadHandle.onComplete(null, fontFamily);
            _loadingFonts.splice(i, 1);
            continue;
          }
          var oldWidth = fontLoadHandle.refWidth;
          var fontDesc = "40px " + fontFamily;
          _canvasContext.font = fontDesc;
          var newWidth = safeMeasureText(_canvasContext, _testString, fontDesc);
          if (oldWidth !== newWidth) {
            _loadingFonts.splice(i, 1);
            fontLoadHandle.onComplete(null, fontFamily);
          } else {
            allFontsLoaded = false;
          }
        }
        if (allFontsLoaded) {
          clearInterval(_intervalId);
          _intervalId = -1;
        }
      }
      function nativeCheckFontLoaded(start, font, callback) {
        var loader = new Promise(function (resolve, reject) {
          var check = function check() {
            var now = Date.now();
            if (now - start >= _timeout) {
              reject();
            } else {
              ccdocument$1.fonts.load("40px " + font).then(function (fonts) {
                if (fonts.length >= 1) {
                  resolve();
                } else {
                  setTimeout(check, 100);
                }
              }, function () {
                reject();
              });
            }
          };
          check();
        });
        var timeoutId = null;
        var timer = new Promise(function (resolve, reject) {
          timeoutId = setTimeout(reject, _timeout);
        });
        Promise.race([timer, loader]).then(function () {
          if (timeoutId) {
            clearTimeout(timeoutId);
            timeoutId = null;
          }
          callback(null, font);
        }, function () {
          warnID(4933, font);
          callback(null, font);
        });
      }
      function loadFont(url, options, onComplete) {
        var fontFamilyName = getFontFamily(url);
        if (_fontFaces[fontFamilyName]) {
          onComplete(null, fontFamilyName);
          return;
        }
        if (!_canvasContext) {
          var labelCanvas = ccdocument$1.createElement('canvas');
          labelCanvas.width = 100;
          labelCanvas.height = 100;
          _canvasContext = labelCanvas.getContext('2d');
        }
        var fontDesc = "40px " + fontFamilyName;
        var fontStyle = ccdocument$1.createElement('style');
        fontStyle.type = 'text/css';
        var fontStr = '';
        if (Number.isNaN(fontFamilyName)) {
          fontStr += "@font-face { font-family:" + fontFamilyName + "; src:";
        } else {
          fontStr += "@font-face { font-family:\"" + fontFamilyName + "\"; src:";
        }
        fontStr += "url(\"" + url + "\");";
        fontStyle.textContent = fontStr + "}";
        ccdocument$1.body.appendChild(fontStyle);
        var preloadDiv = ccdocument$1.createElement('div');
        var divStyle = preloadDiv.style;
        divStyle.fontFamily = fontFamilyName;
        preloadDiv.innerHTML = '.';
        divStyle.position = 'absolute';
        divStyle.left = '-100px';
        divStyle.top = '-100px';
        ccdocument$1.body.appendChild(preloadDiv);
        if (useNativeCheck()) {
          nativeCheckFontLoaded(Date.now(), fontFamilyName, onComplete);
        } else {
          var refWidth = safeMeasureText(_canvasContext, _testString, fontDesc);
          var fontLoadHandle = {
            fontFamilyName: fontFamilyName,
            refWidth: refWidth,
            onComplete: onComplete,
            startTime: Date.now()
          };
          _loadingFonts.push(fontLoadHandle);
          if (_intervalId === -1) {
            _intervalId = setInterval(checkFontLoaded, 100);
          }
        }
        _fontFaces[fontFamilyName] = fontStyle;
      }
      function getFontFamily(fontHandle) {
        var ttfIndex = fontHandle.lastIndexOf('.ttf');
        if (ttfIndex === -1) {
          return fontHandle;
        }
        var slashPos = fontHandle.lastIndexOf('/');
        var fontFamilyName;
        if (slashPos === -1) {
          fontFamilyName = fontHandle.substring(0, ttfIndex) + "_LABEL";
        } else {
          fontFamilyName = fontHandle.substring(slashPos + 1, ttfIndex) + "_LABEL";
        }
        if (fontFamilyName.indexOf(' ') !== -1) {
          fontFamilyName = "\"" + fontFamilyName + "\"";
        }
        return fontFamilyName;
      }
      function createFont(id, data, options, onComplete) {
        var out = new TTFFont();
        out._nativeUrl = id;
        out._nativeAsset = data;
        onComplete(null, out);
      }
      downloader$1.register({
        '.font': loadFont,
        '.eot': loadFont,
        '.ttf': loadFont,
        '.woff': loadFont,
        '.svg': loadFont,
        '.ttc': loadFont
      });
      factory.register({
        '.font': createFont,
        '.eot': createFont,
        '.ttf': createFont,
        '.woff': createFont,
        '.svg': createFont,
        '.ttc': createFont
      });

      legacyCC.UI = {
        MeshBuffer: MeshBuffer,
        spriteAssembler: spriteAssembler,
        graphicsAssembler: graphicsAssemblerManager,
        labelAssembler: labelAssembler,
        RenderData: RenderData,
        MeshRenderData: MeshRenderData
      };

      var SortingLayer = {
        "default": 0
      };
      game.on(Game.EVENT_POST_SUBSYSTEM_INIT, function () {
        SortingLayers.init();
      });
      var SortingLayers = exports('Z', function () {
        function SortingLayers() {}
        SortingLayers.getSortingPriority = function getSortingPriority(layer, order) {
          if (layer === void 0) {
            layer = 0;
          }
          if (order === void 0) {
            order = 0;
          }
          return (layer + (1 << 15) << 16 | order + (1 << 15)) >>> 0;
        };
        SortingLayers.getLayerIndex = function getLayerIndex(layer) {
          if (layer === void 0) {
            layer = 0;
          }
          var index = 0;
          if (this.indexMap.has(layer)) {
            index = this.indexMap.get(layer);
          } else {
            errorID(2105);
          }
          return index;
        };
        SortingLayers.getLayerIndexByName = function getLayerIndexByName(name) {
          var id = this.getLayerByName(name);
          return this.getLayerIndex(id);
        };
        SortingLayers.getLayerName = function getLayerName(layer) {
          if (layer === void 0) {
            layer = 0;
          }
          var name = '';
          if (this.nameMap.has(layer)) {
            name = this.nameMap.get(layer);
          } else {
            errorID(2105);
          }
          return name;
        };
        SortingLayers.getLayerByName = function getLayerByName(name) {
          var count = this.nameMap.size;
          var keyIterator = this.nameMap.keys();
          var key = 0;
          for (var i = 0; i < count; i++) {
            key = keyIterator.next().value;
            if (this.nameMap.get(key) === name) return key;
          }
          errorID(2106);
          return 0;
        };
        SortingLayers.isLayerValid = function isLayerValid(id) {
          if (this.indexMap.has(id)) {
            return true;
          } else {
            errorID(2105);
            return false;
          }
        };
        SortingLayers.getBuiltinLayers = function getBuiltinLayers() {
          return [{
            id: 0,
            name: 'default',
            value: 0
          }];
        };
        SortingLayers.init = function init() {
          var sortingLayers = settings.querySettings(Settings.Category.ENGINE, 'sortingLayers');
          if (!sortingLayers || sortingLayers.length === 0) {
            sortingLayers = this.getBuiltinLayers();
          }
          SortingLayers.resetState();
          for (var i = 0; i < sortingLayers.length; i++) {
            var layer = sortingLayers[i];
            SortingLayers.setLayer(layer.id, layer.name, layer.value);
            SortingLayers.Enum[layer.name] = layer.id;
          }
          Enum.update(SortingLayers.Enum);
          Enum.sortList(SortingLayers.Enum, function (a, b) {
            return SortingLayers.getLayerIndex(a.value) - SortingLayers.getLayerIndex(b.value);
          });
        };
        SortingLayers.setLayer = function setLayer(layer, layerName, layerIndex) {
          this.nameMap.set(layer, layerName);
          this.indexMap.set(layer, layerIndex);
        };
        SortingLayers.resetState = function resetState() {
          var oldItem = Object.keys(SortingLayers.Enum);
          for (var i = 0; i < oldItem.length; i++) {
            delete SortingLayers.Enum[SortingLayers.Enum[oldItem[i]]];
            delete SortingLayers.Enum[oldItem[i]];
          }
          SortingLayers.indexMap.clear();
          SortingLayers.nameMap.clear();
        };
        return SortingLayers;
      }());
      SortingLayers.nameMap = new Map();
      SortingLayers.indexMap = new Map();
      SortingLayers.Enum = Enum(SortingLayer);

      var _dec$1$, _dec2$1x, _class$1_, _class2$1O, _initializer$1F, _initializer2$1l;
      var MAX_INT16 = (1 << 15) - 1;
      var MIN_INT16 = -1 << 15;
      var Sorting = exports('_', (_dec$1$ = ccclass$n('cc.Sorting'), _dec2$1x = type$7(SortingLayers.Enum), _dec$1$(_class$1_ = disallowMultiple$1(_class$1_ = (_class2$1O = function (_Component) {
        _inheritsLoose(Sorting, _Component);
        function Sorting() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Component.call.apply(_Component, [this].concat(args)) || this;
          _this._sortingLayer = _initializer$1F && _initializer$1F();
          _this._sortingOrder = _initializer2$1l && _initializer2$1l();
          _this._modelRenderer = null;
          return _this;
        }
        var _proto = Sorting.prototype;
        _proto.__preload = function __preload() {
          this._modelRenderer = this.getComponent('cc.ModelRenderer');
          if (!this._modelRenderer) {
            warnID(16301, this.node.name);
          }
          this._updateSortingPriority();
        };
        _proto._updateSortingPriority = function _updateSortingPriority() {
          var sortingLayerValue = SortingLayers.getLayerIndex(this._sortingLayer);
          var sortingPriority = SortingLayers.getSortingPriority(sortingLayerValue, this._sortingOrder);
          if (this._modelRenderer && this._modelRenderer.isValid) {
            this._modelRenderer.priority = sortingPriority;
          }
        };
        _createClass(Sorting, [{
          key: "sortingLayer",
          get: function get() {
            return this._sortingLayer;
          },
          set: function set(val) {
            if (val === this._sortingLayer || !SortingLayers.isLayerValid(val)) return;
            this._sortingLayer = val;
            this._updateSortingPriority();
          }
        }, {
          key: "sortingOrder",
          get: function get() {
            return this._sortingOrder;
          },
          set: function set(val) {
            if (val === this._sortingOrder) return;
            this._sortingOrder = clamp$1(val, MIN_INT16, MAX_INT16);
            this._updateSortingPriority();
          }
        }]);
        return Sorting;
      }(Component), (_applyDecoratedDescriptor(_class2$1O.prototype, "sortingLayer", [_dec2$1x], Object.getOwnPropertyDescriptor(_class2$1O.prototype, "sortingLayer"), _class2$1O.prototype), _initializer$1F = applyDecoratedInitializer(_class2$1O.prototype, "_sortingLayer", [serializable$j], function () {
        return SortingLayers.Enum["default"];
      }), _initializer2$1l = applyDecoratedInitializer(_class2$1O.prototype, "_sortingOrder", [serializable$j], function () {
        return 0;
      })), _class2$1O)) || _class$1_) || _class$1_));

      var MorphModel = function (_Model) {
        _inheritsLoose(MorphModel, _Model);
        function MorphModel() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Model.call.apply(_Model, [this].concat(args)) || this;
          _this._morphRenderingInstance = null;
          _this._usedMaterials = new Set();
          return _this;
        }
        var _proto = MorphModel.prototype;
        _proto.getMacroPatches = function getMacroPatches(subModelIndex) {
          var superMacroPatches = _Model.prototype.getMacroPatches.call(this, subModelIndex);
          if (this._morphRenderingInstance) {
            var morphInstanceMacroPatches = this._morphRenderingInstance.requiredPatches(subModelIndex);
            if (morphInstanceMacroPatches) {
              return morphInstanceMacroPatches.concat(superMacroPatches !== null && superMacroPatches !== void 0 ? superMacroPatches : []);
            }
          }
          return superMacroPatches;
        };
        _proto.initSubModel = function initSubModel(subModelIndex, subMeshData, material) {
          return _Model.prototype.initSubModel.call(this, subModelIndex, subMeshData, this._launderMaterial(material));
        };
        _proto.destroy = function destroy() {
          _Model.prototype.destroy.call(this);
          this._morphRenderingInstance = null;
        };
        _proto.setSubModelMaterial = function setSubModelMaterial(subModelIndex, material) {
          return _Model.prototype.setSubModelMaterial.call(this, subModelIndex, this._launderMaterial(material));
        };
        _proto.setMorphRendering = function setMorphRendering(morphRendering) {
          this._morphRenderingInstance = morphRendering;
        };
        _proto._updateLocalDescriptors = function _updateLocalDescriptors(submodelIdx, descriptorSet) {
          _Model.prototype._updateLocalDescriptors.call(this, submodelIdx, descriptorSet);
          if (this._morphRenderingInstance) {
            this._morphRenderingInstance.adaptPipelineState(submodelIdx, descriptorSet);
          }
        };
        _proto._launderMaterial = function _launderMaterial(material) {
          return material;
        };
        return MorphModel;
      }(Model);

      var _dec$1_, _dec2$1w, _dec3$15, _dec4$Q, _dec5$I, _dec6$s, _dec7$l, _class$1Z, _class2$1N, _initializer$1E, _initializer2$1k, _initializer3$T, _initializer4$H, _initializer5$v, _initializer6$n, _initializer7$j, _initializer8$i, _initializer9$g, _initializer10$e, _class3$r, _dec8$f, _dec9$d, _dec10$8, _dec11$7, _dec12$7, _dec13$5, _dec14$4, _dec15$4, _class4$q, _class5$s, _initializer11$c, _initializer12$a, _initializer13$9, _initializer14$7, _initializer15$5, _initializer16$5, _initializer17$4, _initializer18$4, _initializer19$3, _initializer20$2, _initializer21$2, _class6$7;
      var ccclass$j = ccclass$n,
        executionOrder = executionOrder$1,
        type$4 = type$7,
        formerlySerializedAs$3 = formerlySerializedAs$4,
        serializable$g = serializable$j;
      var _phaseID = getPhaseID('specular-pass');
      function getSkinPassIndex(subModel) {
        var passes = subModel.passes;
        var r = legacyCC.rendering;
        if (isEnableEffect()) _phaseID = r.getPhaseID(r.getPassID('specular-pass'), 'default');
        for (var k = 0; k < passes.length; k++) {
          if ((!r || !r.enableEffectImport) && passes[k].phase === _phaseID || isEnableEffect() && passes[k].phaseID === _phaseID) {
            return k;
          }
        }
        return -1;
      }
      var ModelShadowCastingMode = Enum({
        OFF: 0,
        ON: 1
      });
      var ModelShadowReceivingMode = Enum({
        OFF: 0,
        ON: 1
      });
      var ModelBakeSettings = (_dec$1_ = ccclass$j('cc.ModelBakeSettings'), _dec2$1w = formerlySerializedAs$3('_recieveShadow'), _dec3$15 = type$4(CCInteger), _dec4$Q = type$4(CCBoolean), _dec5$I = type$4(CCBoolean), _dec6$s = type$4(Enum(ReflectionProbeType)), _dec7$l = type$4(CCBoolean), _dec$1_(_class$1Z = (_class2$1N = (_class3$r = function (_EventTarget) {
        _inheritsLoose(ModelBakeSettings, _EventTarget);
        function ModelBakeSettings() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _EventTarget.call.apply(_EventTarget, [this].concat(args)) || this;
          _this.texture = _initializer$1E && _initializer$1E();
          _this.uvParam = _initializer2$1k && _initializer2$1k();
          _this._bakeable = _initializer3$T && _initializer3$T();
          _this._castShadow = _initializer4$H && _initializer4$H();
          _this._receiveShadow = _initializer5$v && _initializer5$v();
          _this._lightmapSize = _initializer6$n && _initializer6$n();
          _this._useLightProbe = _initializer7$j && _initializer7$j();
          _this._bakeToLightProbe = _initializer8$i && _initializer8$i();
          _this._reflectionProbeType = _initializer9$g && _initializer9$g();
          _this._bakeToReflectionProbe = _initializer10$e && _initializer10$e();
          _this.probeCubemap = null;
          _this.probeBlendCubemap = null;
          _this.probePlanarmap = null;
          return _this;
        }
        _createClass(ModelBakeSettings, [{
          key: "bakeable",
          get: function get() {
            return this._bakeable;
          },
          set: function set(val) {
            this._bakeable = val;
          }
        }, {
          key: "castShadow",
          get: function get() {
            return this._castShadow;
          },
          set: function set(val) {
            this._castShadow = val;
          }
        }, {
          key: "receiveShadow",
          get: function get() {
            return this._receiveShadow;
          },
          set: function set(val) {
            this._receiveShadow = val;
          }
        }, {
          key: "lightmapSize",
          get: function get() {
            return this._lightmapSize;
          },
          set: function set(val) {
            this._lightmapSize = val;
          }
        }, {
          key: "useLightProbe",
          get: function get() {
            return this._useLightProbe;
          },
          set: function set(val) {
            this._useLightProbe = val;
            this.emit(ModelBakeSettings.USE_LIGHT_PROBE_CHANGED);
          }
        }, {
          key: "bakeToLightProbe",
          get: function get() {
            return this._bakeToLightProbe;
          },
          set: function set(val) {
            this._bakeToLightProbe = val;
          }
        }, {
          key: "reflectionProbe",
          get: function get() {
            return this._reflectionProbeType;
          },
          set: function set(val) {
            this._reflectionProbeType = val;
            this.emit(ModelBakeSettings.REFLECTION_PROBE_CHANGED);
          }
        }, {
          key: "bakeToReflectionProbe",
          get: function get() {
            return this._bakeToReflectionProbe;
          },
          set: function set(val) {
            this._bakeToReflectionProbe = val;
            this.emit(ModelBakeSettings.BAKE_TO_REFLECTION_PROBE_CHANGED);
          }
        }]);
        return ModelBakeSettings;
      }(EventTarget), _class3$r.USE_LIGHT_PROBE_CHANGED = 'use_light_probe_changed', _class3$r.REFLECTION_PROBE_CHANGED = 'reflection_probe_changed', _class3$r.BAKE_TO_REFLECTION_PROBE_CHANGED = 'bake_to_reflection_probe_changed', _class3$r), (_initializer$1E = applyDecoratedInitializer(_class2$1N.prototype, "texture", [serializable$g], function () {
        return null;
      }), _initializer2$1k = applyDecoratedInitializer(_class2$1N.prototype, "uvParam", [serializable$g], function () {
        return new Vec4();
      }), _initializer3$T = applyDecoratedInitializer(_class2$1N.prototype, "_bakeable", [serializable$g], function () {
        return false;
      }), _initializer4$H = applyDecoratedInitializer(_class2$1N.prototype, "_castShadow", [serializable$g], function () {
        return false;
      }), _initializer5$v = applyDecoratedInitializer(_class2$1N.prototype, "_receiveShadow", [_dec2$1w], function () {
        return false;
      }), _initializer6$n = applyDecoratedInitializer(_class2$1N.prototype, "_lightmapSize", [serializable$g], function () {
        return 64;
      }), _initializer7$j = applyDecoratedInitializer(_class2$1N.prototype, "_useLightProbe", [serializable$g], function () {
        return false;
      }), _initializer8$i = applyDecoratedInitializer(_class2$1N.prototype, "_bakeToLightProbe", [serializable$g], function () {
        return true;
      }), _initializer9$g = applyDecoratedInitializer(_class2$1N.prototype, "_reflectionProbeType", [serializable$g], function () {
        return ReflectionProbeType.NONE;
      }), _initializer10$e = applyDecoratedInitializer(_class2$1N.prototype, "_bakeToReflectionProbe", [serializable$g], function () {
        return true;
      }), _applyDecoratedDescriptor(_class2$1N.prototype, "lightmapSize", [_dec3$15], Object.getOwnPropertyDescriptor(_class2$1N.prototype, "lightmapSize"), _class2$1N.prototype), _applyDecoratedDescriptor(_class2$1N.prototype, "useLightProbe", [_dec4$Q], Object.getOwnPropertyDescriptor(_class2$1N.prototype, "useLightProbe"), _class2$1N.prototype), _applyDecoratedDescriptor(_class2$1N.prototype, "bakeToLightProbe", [_dec5$I], Object.getOwnPropertyDescriptor(_class2$1N.prototype, "bakeToLightProbe"), _class2$1N.prototype), _applyDecoratedDescriptor(_class2$1N.prototype, "reflectionProbe", [_dec6$s], Object.getOwnPropertyDescriptor(_class2$1N.prototype, "reflectionProbe"), _class2$1N.prototype), _applyDecoratedDescriptor(_class2$1N.prototype, "bakeToReflectionProbe", [_dec7$l], Object.getOwnPropertyDescriptor(_class2$1N.prototype, "bakeToReflectionProbe"), _class2$1N.prototype)), _class2$1N)) || _class$1Z);
      var MeshRenderer = exports('a3', (_dec8$f = ccclass$j('cc.MeshRenderer'), _dec9$d = executionOrder(100), _dec10$8 = type$4(CCFloat), _dec11$7 = type$4(CCFloat), _dec12$7 = type$4(ModelShadowCastingMode), _dec13$5 = type$4(ModelShadowReceivingMode), _dec14$4 = type$4(Mesh), _dec15$4 = type$4(CCBoolean), _dec8$f(_class4$q = _dec9$d(_class4$q = (_class5$s = (_class6$7 = function (_ModelRenderer) {
        _inheritsLoose(MeshRenderer, _ModelRenderer);
        var _proto = MeshRenderer.prototype;
        _proto.onUpdateReceiveDirLight = function onUpdateReceiveDirLight(visibility, forceClose) {
          if (forceClose === void 0) {
            forceClose = false;
          }
          if (!this._model) {
            return;
          }
          if (forceClose) {
            this._model.receiveDirLight = false;
            return;
          }
          if (this.node && (visibility & this.node.layer) === this.node.layer || visibility & this._model.visFlags) {
            this._model.receiveDirLight = true;
          } else {
            this._model.receiveDirLight = false;
          }
        };
        _proto.clearGlobalStandardSkinObjectFlag = function clearGlobalStandardSkinObjectFlag() {
          this._enabledGlobalStandardSkinObject = false;
        };
        function MeshRenderer() {
          var _this2;
          _this2 = _ModelRenderer.call(this) || this;
          _this2.bakeSettings = _initializer11$c && _initializer11$c();
          _this2._mesh = _initializer12$a && _initializer12$a();
          _this2._shadowCastingMode = _initializer13$9 && _initializer13$9();
          _this2._shadowReceivingMode = _initializer14$7 && _initializer14$7();
          _this2._shadowBias = _initializer15$5 && _initializer15$5();
          _this2._shadowNormalBias = _initializer16$5 && _initializer16$5();
          _this2._reflectionProbeId = _initializer17$4 && _initializer17$4();
          _this2._reflectionProbeBlendId = _initializer18$4 && _initializer18$4();
          _this2._reflectionProbeBlendWeight = _initializer19$3 && _initializer19$3();
          _this2._enabledGlobalStandardSkinObject = _initializer20$2 && _initializer20$2();
          _this2._reflectionProbeDataMap = null;
          _this2._subMeshShapesWeights = [];
          _this2._modelType = void 0;
          _this2._model = null;
          _this2._morphInstance = null;
          _this2._enableMorph = _initializer21$2 && _initializer21$2();
          _this2._modelType = Model;
          var highQualityMode = settings.querySettings(Settings.Category.RENDERING, 'highQualityMode');
          if (highQualityMode) {
            _this2._shadowCastingMode = ModelShadowCastingMode.ON;
            _this2.bakeSettings.castShadow = true;
            _this2.bakeSettings.receiveShadow = true;
          }
          return _this2;
        }
        _proto.onLoad = function onLoad() {
          if (this._mesh) {
            this._mesh.initialize();
          }
          if (!this._validateShapeWeights()) {
            this._initSubMeshShapesWeights();
          }
          this._watchMorphInMesh();
          this._updateModels();
          this._updateCastShadow();
          this._updateReceiveShadow();
          this._updateShadowBias();
          this._updateShadowNormalBias();
          this._updateUseLightProbe();
          this._updateBakeToReflectionProbe();
          this._updateUseReflectionProbe();
          this._updateReceiveDirLight();
          this._updateStandardSkin();
        };
        _proto.onRestore = function onRestore() {
          this._updateModels();
          if (this.enabledInHierarchy) {
            this._attachToScene();
          }
          this._updateCastShadow();
          this._updateReceiveShadow();
          this._updateShadowBias();
          this._updateShadowNormalBias();
          this._updateUseLightProbe();
          this._updateBakeToReflectionProbe();
          this._updateUseReflectionProbe();
          this._updateReceiveDirLight();
          this._updateStandardSkin();
        };
        _proto.onEnable = function onEnable() {
          _ModelRenderer.prototype.onEnable.call(this);
          this.node.on(NodeEventType.MOBILITY_CHANGED, this.onMobilityChanged, this);
          this.node.on(NodeEventType.LIGHT_PROBE_BAKING_CHANGED, this.onLightProbeBakingChanged, this);
          this.bakeSettings.on(ModelBakeSettings.USE_LIGHT_PROBE_CHANGED, this.onUseLightProbeChanged, this);
          this.bakeSettings.on(ModelBakeSettings.REFLECTION_PROBE_CHANGED, this.onReflectionProbeChanged, this);
          this.bakeSettings.on(ModelBakeSettings.BAKE_TO_REFLECTION_PROBE_CHANGED, this.onBakeToReflectionProbeChanged, this);
          if (!this._model) {
            this._updateModels();
          }
          this._model.onGlobalPipelineStateChanged();
          this._updateCastShadow();
          this._updateReceiveShadow();
          this._updateShadowBias();
          this._updateShadowNormalBias();
          this._updateBakeToReflectionProbe();
          this._updateUseReflectionProbe();
          this._onUpdateLocalShadowBiasAndProbeId();
          this._updateUseLightProbe();
          this._updateReceiveDirLight();
          this._onUpdateReflectionProbeDataMap();
          this._onUpdateLocalReflectionProbeData();
          this._updateStandardSkin();
          this._attachToScene();
        };
        _proto.onDisable = function onDisable() {
          if (this._model) {
            this._detachFromScene();
          }
          this.node.off(NodeEventType.MOBILITY_CHANGED, this.onMobilityChanged, this);
          this.node.off(NodeEventType.LIGHT_PROBE_BAKING_CHANGED, this.onLightProbeBakingChanged, this);
          this.bakeSettings.off(ModelBakeSettings.USE_LIGHT_PROBE_CHANGED, this.onUseLightProbeChanged, this);
          this.bakeSettings.off(ModelBakeSettings.REFLECTION_PROBE_CHANGED, this.onReflectionProbeChanged, this);
          this.bakeSettings.off(ModelBakeSettings.BAKE_TO_REFLECTION_PROBE_CHANGED, this.onBakeToReflectionProbeChanged, this);
        };
        _proto.onDestroy = function onDestroy() {
          if (this._model) {
            legacyCC.director.root.destroyModel(this._model);
            this._model = null;
            this._models.length = 0;
          }
          if (this._morphInstance) {
            this._morphInstance.destroy();
          }
        };
        _proto.onGeometryChanged = function onGeometryChanged() {
          if (this._model && this._mesh) {
            var meshStruct = this._mesh.struct;
            this._model.createBoundingShape(meshStruct.minPosition, meshStruct.maxPosition);
            this._model.updateWorldBound();
            this._model.onGeometryChanged();
          }
        };
        _proto.getWeight = function getWeight(subMeshIndex, shapeIndex) {
          var subMeshShapesWeights = this._subMeshShapesWeights;
          assertIsTrue(subMeshIndex < subMeshShapesWeights.length);
          var shapeWeights = this._subMeshShapesWeights[subMeshIndex];
          assertIsTrue(shapeIndex < shapeWeights.length);
          return shapeWeights[shapeIndex];
        };
        _proto.setWeights = function setWeights(weights, subMeshIndex) {
          var subMeshShapesWeights = this._subMeshShapesWeights;
          if (subMeshIndex >= subMeshShapesWeights.length) {
            return;
          }
          var shapeWeights = subMeshShapesWeights[subMeshIndex];
          if (shapeWeights.length !== weights.length) {
            return;
          }
          subMeshShapesWeights[subMeshIndex] = weights.slice(0);
          this._uploadSubMeshShapesWeights(subMeshIndex);
        };
        _proto.setWeight = function setWeight(weight, subMeshIndex, shapeIndex) {
          var subMeshShapesWeights = this._subMeshShapesWeights;
          if (subMeshIndex >= subMeshShapesWeights.length) {
            return;
          }
          var shapeWeights = subMeshShapesWeights[subMeshIndex];
          if (shapeIndex >= shapeWeights.length) {
            return;
          }
          shapeWeights[shapeIndex] = weight;
          this._uploadSubMeshShapesWeights(subMeshIndex);
        };
        _proto.setInstancedAttribute = function setInstancedAttribute(name, value) {
          if (!this.model) {
            return;
          }
          {
            var subModels = this.model.subModels;
            for (var i = 0; i < subModels.length; i++) {
              var subModel = subModels[i];
              var _subModel$instancedAt = subModel.instancedAttributeBlock,
                attributes = _subModel$instancedAt.attributes,
                views = _subModel$instancedAt.views;
              for (var _i = 0; _i < attributes.length; _i++) {
                if (attributes[_i].name === name) {
                  views[_i].set(value);
                  break;
                }
              }
            }
          }
        };
        _proto._updateLightmap = function _updateLightmap(lightmap, uOff, vOff, scale, lum) {
          this.bakeSettings.texture = lightmap;
          this.bakeSettings.uvParam.x = uOff;
          this.bakeSettings.uvParam.y = vOff;
          this.bakeSettings.uvParam.z = scale;
          this.bakeSettings.uvParam.w = lum;
          this._onUpdateLightingmap();
          this._updateReceiveDirLight();
        };
        _proto.updateProbeCubemap = function updateProbeCubemap(cubeMap) {
          if (this.bakeSettings.probeCubemap && this.bakeSettings.probeCubemap === cubeMap) {
            return;
          }
          this.bakeSettings.probeCubemap = cubeMap;
          if (this.model !== null) {
            this.model.updateReflectionProbeCubemap(this.bakeSettings.probeCubemap);
          }
        };
        _proto.updateProbeBlendCubemap = function updateProbeBlendCubemap(cubeMap) {
          if (this.bakeSettings.probeBlendCubemap && this.bakeSettings.probeBlendCubemap === cubeMap) {
            return;
          }
          this.bakeSettings.probeBlendCubemap = cubeMap;
          if (this.model !== null) {
            this.model.updateReflectionProbeBlendCubemap(this.bakeSettings.probeBlendCubemap);
          }
        };
        _proto.updateProbePlanarMap = function updateProbePlanarMap(planarMap) {
          if (this.bakeSettings.probePlanarmap === planarMap) {
            return;
          }
          this.bakeSettings.probePlanarmap = planarMap;
          if (this.model !== null) {
            this.model.updateReflectionProbePlanarMap(this.bakeSettings.probePlanarmap);
          }
        };
        _proto.updateReflectionProbeDataMap = function updateReflectionProbeDataMap(dataMap) {
          this._reflectionProbeDataMap = dataMap;
          if (this.model !== null) {
            this.model.updateReflectionProbeDataMap(dataMap);
          }
        };
        _proto.updateReflectionProbeId = function updateReflectionProbeId(probeId) {
          this._reflectionProbeId = probeId;
          if (this.model) {
            this.model.reflectionProbeId = probeId;
          }
          this._onUpdateLocalShadowBiasAndProbeId();
        };
        _proto.updateReflectionProbeBlendId = function updateReflectionProbeBlendId(blendProbeId) {
          this._reflectionProbeBlendId = blendProbeId;
          if (this.model) {
            this.model.reflectionProbeBlendId = blendProbeId;
          }
          this._onUpdateLocalShadowBiasAndProbeId();
        };
        _proto.updateReflectionProbeBlendWeight = function updateReflectionProbeBlendWeight(weight) {
          this._reflectionProbeBlendWeight = weight;
          if (this.model) {
            this.model.reflectionProbeBlendWeight = weight;
          }
          this._onUpdateLocalReflectionProbeData();
        };
        _proto._updateReflectionProbeTexture = function _updateReflectionProbeTexture() {
          if (!this.model) return;
          var bakeSettings = this.bakeSettings;
          var reflectionProbe = bakeSettings.reflectionProbe;
          var probeBlendCubemap = bakeSettings.probeBlendCubemap;
          var probePlanarMap = bakeSettings.probePlanarmap;
          var probeCubeMap = bakeSettings.probeCubemap;
          if (reflectionProbe === ReflectionProbeType.BAKED_CUBEMAP) {
            this.model.updateReflectionProbeCubemap(probeCubeMap);
            this.model.updateReflectionProbePlanarMap(null);
            this.model.updateReflectionProbeBlendCubemap(null);
          } else if (reflectionProbe === ReflectionProbeType.BLEND_PROBES || reflectionProbe === ReflectionProbeType.BLEND_PROBES_AND_SKYBOX) {
            this.model.updateReflectionProbeCubemap(probeCubeMap);
            this.model.updateReflectionProbeBlendCubemap(probeBlendCubemap);
            this.model.updateReflectionProbePlanarMap(null);
          } else if (reflectionProbe === ReflectionProbeType.PLANAR_REFLECTION) {
            this.model.updateReflectionProbePlanarMap(probePlanarMap);
            this.model.updateReflectionProbeCubemap(null);
            this.model.updateReflectionProbeBlendCubemap(null);
          } else {
            this.model.updateReflectionProbeCubemap(null);
            this.model.updateReflectionProbePlanarMap(null);
            this.model.updateReflectionProbeBlendCubemap(null);
          }
        };
        _proto._updateModels = function _updateModels() {
          if (!this.enabledInHierarchy) {
            return;
          }
          var model = this._model;
          if (model) {
            model.destroy();
            model.initialize();
            model.node = model.transform = this.node;
          } else {
            this._createModel();
          }
          if (this._model) {
            if (this._mesh) {
              var meshStruct = this._mesh.struct;
              this._model.createBoundingShape(meshStruct.minPosition, meshStruct.maxPosition);
              this._model.updateWorldBound();
            }
            this._model.initLightingmap(this.bakeSettings.texture, this.bakeSettings.uvParam);
            this._updateUseLightProbe();
            this._updateUseReflectionProbeType();
            this._updateModelParams();
            this._onUpdateLightingmap();
            this._onUpdateLocalShadowBiasAndProbeId();
            this._updateUseReflectionProbe();
            this._updateReceiveDirLight();
            this._onUpdateReflectionProbeDataMap();
            this._onUpdateLocalReflectionProbeData();
          }
        };
        _proto._updateReceiveDirLight = function _updateReceiveDirLight() {
          if (!this._model) {
            return;
          }
          var scene = this.node.scene;
          if (!scene || !scene.renderScene) {
            return;
          }
          var mainLight = scene.renderScene.mainLight;
          if (!mainLight) {
            return;
          }
          var visibility = mainLight.visibility;
          if (!mainLight.node) {
            return;
          }
          if (mainLight.node.mobility === MobilityMode.Static) {
            var forceClose = false;
            if (this.bakeSettings.texture && !this.node.scene.globals.disableLightmap) {
              forceClose = true;
            }
            if (this.node.scene.globals.lightProbeInfo.data && this.node.scene.globals.lightProbeInfo.data.hasCoefficients() && this._model.useLightProbe) {
              forceClose = true;
            }
            this.onUpdateReceiveDirLight(visibility, forceClose);
          } else {
            this.onUpdateReceiveDirLight(visibility);
          }
        };
        _proto._createModel = function _createModel() {
          var preferMorphOverPlain = !!this._morphInstance;
          var modelType = preferMorphOverPlain && this._modelType === Model ? MorphModel : this._modelType;
          var model = this._model = legacyCC.director.root.createModel(modelType);
          model.visFlags = this.visibility;
          model.node = model.transform = this.node;
          this._models.length = 0;
          this._models.push(this._model);
          if (this._morphInstance && model instanceof MorphModel) {
            model.setMorphRendering(this._morphInstance);
          }
        };
        _proto._attachToScene = function _attachToScene() {
          if (!this.node.scene || !this._model) {
            return;
          }
          var renderScene = this._getRenderScene();
          if (this._model.scene !== null) {
            this._detachFromScene();
          }
          renderScene.addModel(this._model);
        };
        _proto._detachFromScene = function _detachFromScene() {
          if (this._model && this._model.scene) {
            this._model.scene.removeModel(this._model);
          }
        };
        _proto._updateModelParams = function _updateModelParams() {
          if (!this._mesh || !this._model) {
            return;
          }
          this.node.hasChangedFlags |= TransformBit.POSITION;
          this._model.transform.hasChangedFlags |= TransformBit.POSITION;
          this._model.isDynamicBatching = this._isBatchingEnabled();
          var meshCount = this._mesh ? this._mesh.renderingSubMeshes.length : 0;
          var renderingMesh = this._mesh.renderingSubMeshes;
          if (renderingMesh) {
            for (var i = 0; i < meshCount; ++i) {
              var material = this.getRenderMaterial(i);
              if (material && !material.isValid) {
                material = null;
              }
              var subMeshData = renderingMesh[i];
              if (subMeshData) {
                this._model.initSubModel(i, subMeshData, material || this._getBuiltinMaterial());
              }
            }
          }
          this._model.enabled = true;
        };
        _proto._onUpdateLightingmap = function _onUpdateLightingmap() {
          if (this.model !== null) {
            this.model.updateLightingmap(this.bakeSettings.texture, this.bakeSettings.uvParam);
          }
          this.setInstancedAttribute('a_lightingMapUVParam', [this.bakeSettings.uvParam.x, this.bakeSettings.uvParam.y, this.bakeSettings.uvParam.z, this.bakeSettings.uvParam.w]);
        };
        _proto._onUpdateLocalShadowBiasAndProbeId = function _onUpdateLocalShadowBiasAndProbeId() {
          if (this.model !== null) {
            this.model.updateLocalShadowBias();
            this.model.updateReflectionProbeId();
          }
          this.setInstancedAttribute('a_localShadowBiasAndProbeId', [this._shadowBias, this._shadowNormalBias, this._reflectionProbeId, this._reflectionProbeBlendId]);
        };
        _proto._onUpdateLocalReflectionProbeData = function _onUpdateLocalReflectionProbeData() {
          if (this.bakeSettings.reflectionProbe === ReflectionProbeType.BAKED_CUBEMAP || this.bakeSettings.reflectionProbe === ReflectionProbeType.BLEND_PROBES || this.bakeSettings.reflectionProbe === ReflectionProbeType.BLEND_PROBES_AND_SKYBOX) {
            if (this.model !== null) {
              this.model.updateReflectionProbeId();
            }
            this.setInstancedAttribute('a_reflectionProbeData', [this._reflectionProbeBlendWeight, 0.0, 0.0, 0.0]);
          }
        };
        _proto._onUpdateReflectionProbeDataMap = function _onUpdateReflectionProbeDataMap() {
          if (this.model !== null) {
            this.model.updateReflectionProbeDataMap(this._reflectionProbeDataMap);
          }
        };
        _proto._onMaterialModified = function _onMaterialModified(idx, material) {
          if (!this._model || !this._model.inited) {
            return;
          }
          this._onRebuildPSO(idx, material || this._getBuiltinMaterial());
          this._updateStandardSkin();
        };
        _proto._onRebuildPSO = function _onRebuildPSO(idx, material) {
          if (!this._model || !this._model.inited) {
            return;
          }
          this._model.isDynamicBatching = this._isBatchingEnabled();
          this._model.setSubModelMaterial(idx, material);
          this._onUpdateLightingmap();
          this._onUpdateLocalShadowBiasAndProbeId();
          this._updateReflectionProbeTexture();
          this._onUpdateReflectionProbeDataMap();
          this._onUpdateLocalReflectionProbeData();
        };
        _proto._onMeshChanged = function _onMeshChanged(old) {};
        _proto._clearMaterials = function _clearMaterials() {
          if (!this._model) {
            return;
          }
          var subModels = this._model.subModels;
          for (var i = 0; i < subModels.length; ++i) {
            this._onMaterialModified(i, null);
          }
        };
        _proto._getBuiltinMaterial = function _getBuiltinMaterial() {
          return builtinResMgr.get('missing-material');
        };
        _proto._onVisibilityChange = function _onVisibilityChange(val) {
          if (!this._model) {
            return;
          }
          this._model.visFlags = val;
        };
        _proto._updateShadowBias = function _updateShadowBias() {
          if (!this._model) {
            return;
          }
          this._model.shadowBias = this._shadowBias;
        };
        _proto._updateShadowNormalBias = function _updateShadowNormalBias() {
          if (!this._model) {
            return;
          }
          this._model.shadowNormalBias = this._shadowNormalBias;
        };
        _proto._updateCastShadow = function _updateCastShadow() {
          if (!this._model) {
            return;
          }
          if (this._shadowCastingMode === ModelShadowCastingMode.OFF) {
            this._model.castShadow = false;
          } else {
            assertIsTrue(this._shadowCastingMode === ModelShadowCastingMode.ON, "ShadowCastingMode " + this._shadowCastingMode + " is not supported.");
            this._model.castShadow = true;
          }
        };
        _proto._updateReceiveShadow = function _updateReceiveShadow() {
          if (!this._model) {
            return;
          }
          if (this._shadowReceivingMode === ModelShadowReceivingMode.OFF) {
            this._model.receiveShadow = false;
          } else {
            this._model.receiveShadow = true;
          }
        };
        _proto.onMobilityChanged = function onMobilityChanged() {
          this._updateUseLightProbe();
          this._updateReceiveDirLight();
        };
        _proto.onLightProbeBakingChanged = function onLightProbeBakingChanged() {
          this._updateReceiveDirLight();
        };
        _proto.onUseLightProbeChanged = function onUseLightProbeChanged() {
          this._updateUseLightProbe();
        };
        _proto.onReflectionProbeChanged = function onReflectionProbeChanged() {
          this._updateUseReflectionProbe();
          this._onUpdateLocalShadowBiasAndProbeId();
          if (this.bakeSettings.reflectionProbe === ReflectionProbeType.BAKED_CUBEMAP || this.bakeSettings.reflectionProbe === ReflectionProbeType.BLEND_PROBES || this.bakeSettings.reflectionProbe === ReflectionProbeType.BLEND_PROBES_AND_SKYBOX) {
            legacyCC.internal.reflectionProbeManager.selectReflectionProbe(this._model);
            if (!legacyCC.internal.reflectionProbeManager.getUsedReflectionProbe(this._model, false)) {
              warnID(16302);
            }
          } else if (this.bakeSettings.reflectionProbe === ReflectionProbeType.PLANAR_REFLECTION) {
            legacyCC.internal.reflectionProbeManager.selectPlanarReflectionProbe(this._model);
            if (!legacyCC.internal.reflectionProbeManager.getUsedReflectionProbe(this._model, true)) {
              warnID(16302);
            }
          }
        };
        _proto.onBakeToReflectionProbeChanged = function onBakeToReflectionProbeChanged() {
          this._updateBakeToReflectionProbe();
        };
        _proto._updateUseLightProbe = function _updateUseLightProbe() {
          if (!this._model) {
            return;
          }
          var node = this.node;
          if (this._mesh && node && node.mobility === MobilityMode.Movable && this.bakeSettings.useLightProbe) {
            this._model.useLightProbe = true;
          } else {
            this._model.useLightProbe = false;
          }
        };
        _proto._isBatchingEnabled = function _isBatchingEnabled() {
          for (var i = 0; i < this._materials.length; ++i) {
            var mat = this._materials[i];
            if (!mat) {
              continue;
            }
            for (var p = 0; p < mat.passes.length; ++p) {
              var pass = mat.passes[p];
              if (pass.batchingScheme) {
                return true;
              }
            }
          }
          return false;
        };
        _proto._updateUseReflectionProbe = function _updateUseReflectionProbe() {
          if (!this._model) return;
          this._model.reflectionProbeType = this.bakeSettings.reflectionProbe;
          this._updateReflectionProbeTexture();
        };
        _proto._updateUseReflectionProbeType = function _updateUseReflectionProbeType() {
          if (!this._model) return;
          this._model.reflectionProbeType = this.bakeSettings.reflectionProbe;
        };
        _proto._updateBakeToReflectionProbe = function _updateBakeToReflectionProbe() {
          if (!this._model) {
            return;
          }
          this._model.bakeToReflectionProbe = this.bakeSettings.bakeToReflectionProbe;
        };
        _proto._watchMorphInMesh = function _watchMorphInMesh() {
          if (this._morphInstance) {
            this._morphInstance.destroy();
            this._morphInstance = null;
          }
          if (!this._enableMorph) {
            return;
          }
          if (!this._mesh || !this._mesh.struct.morph || !this._mesh.morphRendering) {
            return;
          }
          this._morphInstance = this._mesh.morphRendering.createInstance();
          var nSubMeshes = this._mesh.struct.primitives.length;
          for (var iSubMesh = 0; iSubMesh < nSubMeshes; ++iSubMesh) {
            this._uploadSubMeshShapesWeights(iSubMesh);
          }
          if (this._model && this._model instanceof MorphModel) {
            this._model.setMorphRendering(this._morphInstance);
          }
        };
        _proto._initSubMeshShapesWeights = function _initSubMeshShapesWeights() {
          var mesh = this._mesh;
          this._subMeshShapesWeights.length = 0;
          if (!mesh) {
            return;
          }
          var morph = mesh.struct.morph;
          if (!morph) {
            return;
          }
          var commonWeights = morph.weights;
          this._subMeshShapesWeights = morph.subMeshMorphs.map(function (subMeshMorph) {
            if (!subMeshMorph) {
              return [];
            } else if (subMeshMorph.weights) {
              return subMeshMorph.weights.slice(0);
            } else if (commonWeights) {
              assertIsTrue(commonWeights.length === subMeshMorph.targets.length);
              return commonWeights.slice(0);
            } else {
              return new Array(subMeshMorph.targets.length).fill(0.0);
            }
          });
        };
        _proto._validateShapeWeights = function _validateShapeWeights() {
          var mesh = this._mesh,
            subMeshShapesWeights = this._subMeshShapesWeights;
          if (!mesh || !mesh.struct.morph) {
            return subMeshShapesWeights.length === 0;
          }
          var morph = mesh.struct.morph;
          if (morph.subMeshMorphs.length !== subMeshShapesWeights.length) {
            return false;
          }
          return subMeshShapesWeights.every(function (_ref, subMeshIndex) {
            var _morph$subMeshMorphs$, _morph$subMeshMorphs$2;
            var shapeCount = _ref.length;
            return ((_morph$subMeshMorphs$ = (_morph$subMeshMorphs$2 = morph.subMeshMorphs[subMeshIndex]) === null || _morph$subMeshMorphs$2 === void 0 ? void 0 : _morph$subMeshMorphs$2.targets.length) !== null && _morph$subMeshMorphs$ !== void 0 ? _morph$subMeshMorphs$ : 0) === shapeCount;
          });
        };
        _proto._uploadSubMeshShapesWeights = function _uploadSubMeshShapesWeights(subMeshIndex) {
          var _this$_morphInstance;
          (_this$_morphInstance = this._morphInstance) === null || _this$_morphInstance === void 0 ? void 0 : _this$_morphInstance.setWeights(subMeshIndex, this._subMeshShapesWeights[subMeshIndex]);
        };
        _proto._updateStandardSkin = function _updateStandardSkin() {
          var pipelineSceneData = legacyCC.director.root.pipeline.pipelineSceneData;
          if (this._enabledGlobalStandardSkinObject) {
            pipelineSceneData.standardSkinMeshRenderer = this;
            pipelineSceneData.standardSkinModel = this.model;
          }
          if (!pipelineSceneData.skinMaterialModel && this._model) {
            var subModels = this._model.subModels;
            for (var j = 0; j < subModels.length; j++) {
              var subModel = subModels[j];
              var skinPassIdx = getSkinPassIndex(subModel);
              if (skinPassIdx < 0) {
                continue;
              }
              pipelineSceneData.skinMaterialModel = this._model;
              return;
            }
          }
        };
        _createClass(MeshRenderer, [{
          key: "shadowBias",
          get: function get() {
            return this._shadowBias;
          },
          set: function set(val) {
            this._shadowBias = val;
            this._updateShadowBias();
            this._onUpdateLocalShadowBiasAndProbeId();
          }
        }, {
          key: "shadowNormalBias",
          get: function get() {
            return this._shadowNormalBias;
          },
          set: function set(val) {
            this._shadowNormalBias = val;
            this._updateShadowNormalBias();
            this._onUpdateLocalShadowBiasAndProbeId();
          }
        }, {
          key: "shadowCastingMode",
          get: function get() {
            return this._shadowCastingMode;
          },
          set: function set(val) {
            this._shadowCastingMode = val;
            this._updateCastShadow();
          }
        }, {
          key: "shadowCastingModeForInspector",
          get: function get() {
            return this.shadowCastingMode === ModelShadowCastingMode.ON;
          },
          set: function set(val) {
            this.shadowCastingMode = val === true ? ModelShadowCastingMode.ON : ModelShadowCastingMode.OFF;
          }
        }, {
          key: "receiveShadow",
          get: function get() {
            return this._shadowReceivingMode;
          },
          set: function set(val) {
            this._shadowReceivingMode = val;
            this._updateReceiveShadow();
          }
        }, {
          key: "receiveShadowForInspector",
          get: function get() {
            return this._shadowReceivingMode === ModelShadowReceivingMode.ON;
          },
          set: function set(val) {
            this._shadowReceivingMode = val === true ? ModelShadowReceivingMode.ON : ModelShadowReceivingMode.OFF;
            this._updateReceiveShadow();
          }
        }, {
          key: "mesh",
          get: function get() {
            return this._mesh;
          },
          set: function set(val) {
            var old = this._mesh;
            var mesh = this._mesh = val;
            mesh === null || mesh === void 0 ? void 0 : mesh.initialize();
            this._initSubMeshShapesWeights();
            this._watchMorphInMesh();
            this._onMeshChanged(old);
            this._updateModels();
            if (this.enabledInHierarchy) {
              this._attachToScene();
            }
            this._updateCastShadow();
            this._updateReceiveShadow();
            this._updateUseLightProbe();
            this._updateUseReflectionProbe();
            this._updateReceiveDirLight();
          }
        }, {
          key: "model",
          get: function get() {
            return this._model;
          }
        }, {
          key: "enableMorph",
          get: function get() {
            return this._enableMorph;
          },
          set: function set(value) {
            this._enableMorph = value;
          }
        }, {
          key: "isGlobalStandardSkinObject",
          get: function get() {
            return this._enabledGlobalStandardSkinObject;
          },
          set: function set(val) {
            legacyCC.director.root.pipeline.pipelineSceneData.standardSkinMeshRenderer = val ? this : null;
            this._enabledGlobalStandardSkinObject = val;
          }
        }]);
        return MeshRenderer;
      }(ModelRenderer), _class6$7.ShadowCastingMode = ModelShadowCastingMode, _class6$7.ShadowReceivingMode = ModelShadowReceivingMode, _class6$7), (_initializer11$c = applyDecoratedInitializer(_class5$s.prototype, "bakeSettings", [serializable$g], function () {
        return new ModelBakeSettings(this);
      }), _initializer12$a = applyDecoratedInitializer(_class5$s.prototype, "_mesh", [serializable$g], function () {
        return null;
      }), _initializer13$9 = applyDecoratedInitializer(_class5$s.prototype, "_shadowCastingMode", [serializable$g], function () {
        return ModelShadowCastingMode.OFF;
      }), _initializer14$7 = applyDecoratedInitializer(_class5$s.prototype, "_shadowReceivingMode", [serializable$g], function () {
        return ModelShadowReceivingMode.ON;
      }), _initializer15$5 = applyDecoratedInitializer(_class5$s.prototype, "_shadowBias", [serializable$g], function () {
        return 0;
      }), _initializer16$5 = applyDecoratedInitializer(_class5$s.prototype, "_shadowNormalBias", [serializable$g], function () {
        return 0;
      }), _initializer17$4 = applyDecoratedInitializer(_class5$s.prototype, "_reflectionProbeId", [serializable$g], function () {
        return -1;
      }), _initializer18$4 = applyDecoratedInitializer(_class5$s.prototype, "_reflectionProbeBlendId", [serializable$g], function () {
        return -1;
      }), _initializer19$3 = applyDecoratedInitializer(_class5$s.prototype, "_reflectionProbeBlendWeight", [serializable$g], function () {
        return 0;
      }), _initializer20$2 = applyDecoratedInitializer(_class5$s.prototype, "_enabledGlobalStandardSkinObject", [serializable$g], function () {
        return false;
      }), _applyDecoratedDescriptor(_class5$s.prototype, "shadowBias", [_dec10$8], Object.getOwnPropertyDescriptor(_class5$s.prototype, "shadowBias"), _class5$s.prototype), _applyDecoratedDescriptor(_class5$s.prototype, "shadowNormalBias", [_dec11$7], Object.getOwnPropertyDescriptor(_class5$s.prototype, "shadowNormalBias"), _class5$s.prototype), _applyDecoratedDescriptor(_class5$s.prototype, "shadowCastingMode", [_dec12$7], Object.getOwnPropertyDescriptor(_class5$s.prototype, "shadowCastingMode"), _class5$s.prototype), _applyDecoratedDescriptor(_class5$s.prototype, "receiveShadow", [_dec13$5], Object.getOwnPropertyDescriptor(_class5$s.prototype, "receiveShadow"), _class5$s.prototype), _applyDecoratedDescriptor(_class5$s.prototype, "mesh", [_dec14$4], Object.getOwnPropertyDescriptor(_class5$s.prototype, "mesh"), _class5$s.prototype), _applyDecoratedDescriptor(_class5$s.prototype, "isGlobalStandardSkinObject", [_dec15$4], Object.getOwnPropertyDescriptor(_class5$s.prototype, "isGlobalStandardSkinObject"), _class5$s.prototype), _initializer21$2 = applyDecoratedInitializer(_class5$s.prototype, "_enableMorph", [serializable$g], function () {
        return true;
      })), _class5$s)) || _class4$q) || _class4$q));

      function checkMaterialisSame(comp1, comp2) {
        var matNum = comp1.sharedMaterials.length;
        if (matNum !== comp2.sharedMaterials.length) {
          return false;
        }
        for (var i = 0; i < matNum; i++) {
          if (comp1.getRenderMaterial(i) !== comp2.getRenderMaterial(i)) {
            return false;
          }
        }
        return true;
      }
      var BatchingUtility = exports('a0', function () {
        function BatchingUtility() {}
        BatchingUtility.batchStaticModel = function batchStaticModel(staticModelRoot, batchedRoot) {
          var models = staticModelRoot.getComponentsInChildren(MeshRenderer);
          if (models.length < 2) {
            console.error('the number of static models to batch is less than 2,it needn\'t batch.');
            return false;
          }
          for (var i = 1; i < models.length; i++) {
            if (!models[0].mesh.validateMergingMesh(models[i].mesh)) {
              console.error("the meshes of " + models[0].node.name + " and " + models[i].node.name + " can't be merged");
              return false;
            }
            if (!checkMaterialisSame(models[0], models[i])) {
              console.error("the materials of " + models[0].node.name + " and " + models[i].node.name + " can't be merged");
              return false;
            }
          }
          var batchedMesh = new Mesh();
          var worldMat = new Mat4();
          var rootWorldMatInv = new Mat4();
          staticModelRoot.getWorldMatrix(rootWorldMatInv);
          Mat4.invert(rootWorldMatInv, rootWorldMatInv);
          for (var _i = 0; _i < models.length; _i++) {
            var comp = models[_i];
            comp.node.getWorldMatrix(worldMat);
            Mat4.multiply(worldMat, rootWorldMatInv, worldMat);
            batchedMesh.merge(models[_i].mesh, worldMat);
            comp.enabled = false;
          }
          var batchedModel = batchedRoot.addComponent(MeshRenderer);
          batchedModel.mesh = batchedMesh;
          batchedModel.sharedMaterials = models[0].sharedMaterials;
          return true;
        };
        BatchingUtility.unbatchStaticModel = function unbatchStaticModel(staticModelRoot, batchedRoot) {
          var models = staticModelRoot.getComponentsInChildren(MeshRenderer);
          for (var i = 0; i < models.length; i++) {
            var comp = models[i];
            comp.enabled = true;
          }
          var batchedModel = batchedRoot.getComponent(MeshRenderer);
          if (batchedModel) {
            if (batchedModel.mesh) {
              batchedModel.mesh.destroyRenderingMesh();
            }
            batchedModel.destroy();
          }
          return true;
        };
        return BatchingUtility;
      }());

      var _dec$1Z, _dec2$1v, _dec3$14, _class$1Y, _class2$1M, _initializer$1D, _initializer2$1j, _initializer3$S;
      var Skeleton = exports('a2', (_dec$1Z = ccclass$n('cc.Skeleton'), _dec2$1v = type$7([CCString]), _dec3$14 = type$7([Mat4]), _dec$1Z(_class$1Y = (_class2$1M = function (_Asset) {
        _inheritsLoose(Skeleton, _Asset);
        function Skeleton() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Asset.call.apply(_Asset, [this].concat(args)) || this;
          _this._joints = _initializer$1D && _initializer$1D();
          _this._bindposes = _initializer2$1j && _initializer2$1j();
          _this._hash = _initializer3$S && _initializer3$S();
          _this._invBindposes = null;
          return _this;
        }
        var _proto = Skeleton.prototype;
        _proto.destroy = function destroy() {
          var _cclegacy$director$ro, _cclegacy$director$ro2;
          (_cclegacy$director$ro = legacyCC.director.root) === null || _cclegacy$director$ro === void 0 ? void 0 : (_cclegacy$director$ro2 = _cclegacy$director$ro.dataPoolManager) === null || _cclegacy$director$ro2 === void 0 ? void 0 : _cclegacy$director$ro2.releaseSkeleton(this);
          return _Asset.prototype.destroy.call(this);
        };
        _proto.validate = function validate() {
          return this.joints.length > 0 && this.bindposes.length > 0;
        };
        _createClass(Skeleton, [{
          key: "joints",
          get: function get() {
            return this._joints;
          },
          set: function set(value) {
            this._joints = value;
          }
        }, {
          key: "bindposes",
          get: function get() {
            return this._bindposes;
          },
          set: function set(value) {
            this._bindposes = value;
          }
        }, {
          key: "inverseBindposes",
          get: function get() {
            if (!this._invBindposes) {
              this._invBindposes = [];
              for (var i = 0; i < this._bindposes.length; i++) {
                var inv = new Mat4();
                Mat4.invert(inv, this._bindposes[i]);
                this._invBindposes.push(inv);
              }
            }
            return this._invBindposes;
          }
        }, {
          key: "hash",
          get: function get() {
            if (!this._hash) {
              var str = '';
              for (var i = 0; i < this._bindposes.length; i++) {
                var ibm = this._bindposes[i];
                str += ibm.m00.toPrecision(2) + " " + ibm.m01.toPrecision(2) + " " + ibm.m02.toPrecision(2) + " " + ibm.m03.toPrecision(2) + " " + ibm.m04.toPrecision(2) + " " + ibm.m05.toPrecision(2) + " " + ibm.m06.toPrecision(2) + " " + ibm.m07.toPrecision(2) + " " + ibm.m08.toPrecision(2) + " " + ibm.m09.toPrecision(2) + " " + ibm.m10.toPrecision(2) + " " + ibm.m11.toPrecision(2) + " " + ibm.m12.toPrecision(2) + " " + ibm.m13.toPrecision(2) + " " + ibm.m14.toPrecision(2) + " " + ibm.m15.toPrecision(2) + "\n";
              }
              this._hash = murmurhash2_32_gc(str, 666);
            }
            return this._hash;
          }
        }]);
        return Skeleton;
      }(Asset), (_initializer$1D = applyDecoratedInitializer(_class2$1M.prototype, "_joints", [_dec2$1v], function () {
        return [];
      }), _initializer2$1j = applyDecoratedInitializer(_class2$1M.prototype, "_bindposes", [_dec3$14], function () {
        return [];
      }), _initializer3$S = applyDecoratedInitializer(_class2$1M.prototype, "_hash", [serializable$j], function () {
        return 0;
      })), _class2$1M)) || _class$1Y));
      legacyCC.Skeleton = Skeleton;

      var _dec$1Y, _class$1X, _class2$1L, _initializer$1C, _initializer2$1i, _initializer3$R, _dec2$1u, _dec3$13, _dec4$P, _class4$p, _class5$r, _initializer4$G, _initializer5$u, _initializer6$m, _initializer7$i, _initializer8$h, _class6$6;
      var _color_tmp = new Vec3();
      var PhotometricTerm = Enum({
        LUMINOUS_FLUX: 0,
        LUMINANCE: 1
      });
      var StaticLightSettings = (_dec$1Y = ccclass$n('cc.StaticLightSettings'), _dec$1Y(_class$1X = (_class2$1L = function () {
        function StaticLightSettings() {
          this._baked = _initializer$1C && _initializer$1C();
          this._editorOnly = _initializer2$1i && _initializer2$1i();
          this._castShadow = _initializer3$R && _initializer3$R();
        }
        _createClass(StaticLightSettings, [{
          key: "editorOnly",
          get: function get() {
            return this._editorOnly;
          },
          set: function set(val) {
            this._editorOnly = val;
          }
        }, {
          key: "baked",
          get: function get() {
            return this._baked;
          },
          set: function set(val) {
            this._baked = val;
          }
        }, {
          key: "castShadow",
          get: function get() {
            return this._castShadow;
          },
          set: function set(val) {
            this._castShadow = val;
          }
        }]);
        return StaticLightSettings;
      }(), (_initializer$1C = applyDecoratedInitializer(_class2$1L.prototype, "_baked", [serializable$j], function () {
        return false;
      }), _initializer2$1i = applyDecoratedInitializer(_class2$1L.prototype, "_editorOnly", [serializable$j], function () {
        return false;
      }), _initializer3$R = applyDecoratedInitializer(_class2$1L.prototype, "_castShadow", [serializable$j], function () {
        return false;
      })), _class2$1L)) || _class$1X);
      var Light = exports('a5', (_dec2$1u = ccclass$n('cc.Light'), _dec3$13 = type$7(StaticLightSettings), _dec4$P = type$7(Layers.BitMask), _dec2$1u(_class4$p = (_class5$r = (_class6$6 = function (_Component) {
        _inheritsLoose(Light, _Component);
        function Light() {
          var _this;
          _this = _Component.call(this) || this;
          _this._color = _initializer4$G && _initializer4$G();
          _this._useColorTemperature = _initializer5$u && _initializer5$u();
          _this._colorTemperature = _initializer6$m && _initializer6$m();
          _this._staticSettings = _initializer7$i && _initializer7$i();
          _this._visibility = _initializer8$h && _initializer8$h();
          _this._type = LightType.UNKNOWN;
          _this._lightType = void 0;
          _this._light = null;
          _this._lightType = Light$1;
          return _this;
        }
        var _proto = Light.prototype;
        _proto.onLoad = function onLoad() {
          this._createLight();
        };
        _proto.onEnable = function onEnable() {
          this._attachToScene();
        };
        _proto.onDisable = function onDisable() {
          this._detachFromScene();
        };
        _proto.onDestroy = function onDestroy() {
          this._destroyLight();
        };
        _proto._createLight = function _createLight() {
          if (!this._light) {
            this._light = legacyCC.director.root.createLight(this._lightType);
          }
          this.color = this._color;
          this.useColorTemperature = this._useColorTemperature;
          this.colorTemperature = this._colorTemperature;
          this._light.node = this.node;
          this._light.baked = this.baked;
          this._light.visibility = this.visibility;
        };
        _proto._destroyLight = function _destroyLight() {
          if (this._light) {
            legacyCC.director.root.recycleLight(this._light);
            this._light = null;
          }
        };
        _proto._attachToScene = function _attachToScene() {
          this._detachFromScene();
          if (this._light && !this._light.scene && this.node.scene) {
            var renderScene = this._getRenderScene();
            switch (this._type) {
              case LightType.DIRECTIONAL:
                renderScene.addDirectionalLight(this._light);
                renderScene.setMainLight(this._light);
                break;
              case LightType.SPHERE:
                renderScene.addSphereLight(this._light);
                break;
              case LightType.SPOT:
                renderScene.addSpotLight(this._light);
                break;
              case LightType.POINT:
                renderScene.addPointLight(this._light);
                break;
              case LightType.RANGED_DIRECTIONAL:
                renderScene.addRangedDirLight(this._light);
                break;
            }
          }
        };
        _proto._detachFromScene = function _detachFromScene() {
          if (this._light && this._light.scene) {
            var renderScene = this._light.scene;
            switch (this._type) {
              case LightType.DIRECTIONAL:
                renderScene.removeDirectionalLight(this._light);
                renderScene.unsetMainLight(this._light);
                break;
              case LightType.SPHERE:
                renderScene.removeSphereLight(this._light);
                break;
              case LightType.SPOT:
                renderScene.removeSpotLight(this._light);
                break;
              case LightType.POINT:
                renderScene.removePointLight(this._light);
                break;
              case LightType.RANGED_DIRECTIONAL:
                renderScene.removeRangedDirLight(this._light);
                break;
            }
          }
        };
        _proto._onUpdateReceiveDirLight = function _onUpdateReceiveDirLight() {};
        _createClass(Light, [{
          key: "color",
          get: function get() {
            return this._color;
          },
          set: function set(val) {
            this._color = val;
            if (this._light) {
              _color_tmp.x = val.r / 255.0;
              _color_tmp.y = val.g / 255.0;
              _color_tmp.z = val.b / 255.0;
              this._light.color = _color_tmp;
            }
          }
        }, {
          key: "useColorTemperature",
          get: function get() {
            return this._useColorTemperature;
          },
          set: function set(enable) {
            this._useColorTemperature = enable;
            if (this._light) {
              this._light.useColorTemperature = enable;
            }
          }
        }, {
          key: "colorTemperature",
          get: function get() {
            return this._colorTemperature;
          },
          set: function set(val) {
            this._colorTemperature = val;
            if (this._light) {
              this._light.colorTemperature = val;
            }
          }
        }, {
          key: "staticSettings",
          get: function get() {
            return this._staticSettings;
          },
          set: function set(val) {
            this._staticSettings = val;
          }
        }, {
          key: "type",
          get: function get() {
            return this._type;
          }
        }, {
          key: "baked",
          get: function get() {
            return this.staticSettings.baked;
          },
          set: function set(val) {
            this.staticSettings.baked = val;
            if (this._light !== null) {
              this._light.baked = val;
            }
          }
        }, {
          key: "visibility",
          get: function get() {
            return this._visibility;
          },
          set: function set(vis) {
            this._visibility = vis;
            if (this._light) {
              this._light.visibility = vis;
            }
            this._onUpdateReceiveDirLight();
          }
        }]);
        return Light;
      }(Component), _class6$6.Type = LightType, _class6$6.PhotometricTerm = PhotometricTerm, _class6$6), (_initializer4$G = applyDecoratedInitializer(_class5$r.prototype, "_color", [serializable$j], function () {
        return Color$1.WHITE.clone();
      }), _initializer5$u = applyDecoratedInitializer(_class5$r.prototype, "_useColorTemperature", [serializable$j], function () {
        return false;
      }), _initializer6$m = applyDecoratedInitializer(_class5$r.prototype, "_colorTemperature", [serializable$j], function () {
        return 6550;
      }), _initializer7$i = applyDecoratedInitializer(_class5$r.prototype, "_staticSettings", [serializable$j], function () {
        return new StaticLightSettings();
      }), _initializer8$h = applyDecoratedInitializer(_class5$r.prototype, "_visibility", [serializable$j], function () {
        return CAMERA_DEFAULT_MASK;
      }), _applyDecoratedDescriptor(_class5$r.prototype, "staticSettings", [_dec3$13], Object.getOwnPropertyDescriptor(_class5$r.prototype, "staticSettings"), _class5$r.prototype), _applyDecoratedDescriptor(_class5$r.prototype, "visibility", [_dec4$P], Object.getOwnPropertyDescriptor(_class5$r.prototype, "visibility"), _class5$r.prototype)), _class5$r)) || _class4$p));

      var _dec$1X, _dec2$1t, _dec3$12, _dec4$O, _dec5$H, _dec6$r, _dec7$k, _dec8$e, _dec9$c, _dec10$7, _dec11$6, _dec12$6, _dec13$4, _dec14$3, _dec15$3, _dec16$3, _dec17$3, _dec18$2, _dec19$2, _dec20$2, _dec21$2, _dec22$2, _dec23$2, _dec24$2, _dec25$2, _dec26$2, _dec27$2, _dec28$2, _dec29$2, _dec30$1, _dec31$1, _dec32$1, _dec33$1, _dec34$1, _dec35$1, _dec36$1, _dec37$1, _dec38$1, _dec39$1, _class$1W, _class2$1K, _initializer$1B, _initializer2$1h, _initializer3$Q, _initializer4$F, _initializer5$t, _initializer6$l, _initializer7$h, _initializer8$g, _initializer9$f, _initializer10$d, _initializer11$b, _initializer12$9, _initializer13$8, _initializer14$6, _initializer15$4, _initializer16$4, _initializer17$3, _initializer18$3, _initializer19$2;
      var ccclass$i = ccclass$n,
        property$1 = property$3,
        serializable$f = serializable$j,
        formerlySerializedAs$2 = formerlySerializedAs$4,
        type$3 = type$7;
      var DirectionalLight = exports('a4', (_dec$1X = ccclass$i('cc.DirectionalLight'), _dec2$1t = formerlySerializedAs$2('_illuminance'), _dec3$12 = type$3(CCInteger), _dec4$O = property$1({
        group: {
          name: 'DynamicShadowSettings',
          displayOrder: 1
        }
      }), _dec5$H = type$3(CCBoolean), _dec6$r = property$1({
        group: {
          name: 'DynamicShadowSettings',
          displayOrder: 5
        }
      }), _dec7$k = type$3(PCFType), _dec8$e = property$1({
        group: {
          name: 'DynamicShadowSettings',
          displayOrder: 6
        }
      }), _dec9$c = type$3(CCFloat), _dec10$7 = property$1({
        group: {
          name: 'DynamicShadowSettings',
          displayOrder: 7
        }
      }), _dec11$6 = type$3(CCFloat), _dec12$6 = property$1({
        group: {
          name: 'DynamicShadowSettings',
          displayOrder: 8
        }
      }), _dec13$4 = type$3(CCFloat), _dec14$3 = property$1({
        group: {
          name: 'DynamicShadowSettings',
          displayOrder: 9
        }
      }), _dec15$3 = type$3(CCFloat), _dec16$3 = property$1({
        group: {
          name: 'DynamicShadowSettings',
          displayOrder: 22
        }
      }), _dec17$3 = type$3(CCFloat), _dec18$2 = property$1({
        group: {
          name: 'DynamicShadowSettings',
          displayOrder: 10
        }
      }), _dec19$2 = type$3(CSMLevel), _dec20$2 = property$1({
        group: {
          name: 'DynamicShadowSettings',
          displayOrder: 11
        }
      }), _dec21$2 = type$3(CCBoolean), _dec22$2 = property$1({
        group: {
          name: 'DynamicShadowSettings',
          displayOrder: 12
        }
      }), _dec23$2 = type$3(CCFloat), _dec24$2 = property$1({
        group: {
          name: 'DynamicShadowSettings',
          displayOrder: 13
        }
      }), _dec25$2 = type$3(CSMOptimizationMode), _dec26$2 = property$1({
        group: {
          name: 'DynamicShadowSettings',
          displayOrder: 14
        }
      }), _dec27$2 = type$3(CCBoolean), _dec28$2 = property$1({
        group: {
          name: 'DynamicShadowSettings',
          displayOrder: 15
        }
      }), _dec29$2 = type$3(CCFloat), _dec30$1 = property$1({
        group: {
          name: 'DynamicShadowSettings',
          displayOrder: 16
        }
      }), _dec31$1 = type$3(CCFloat), _dec32$1 = property$1({
        group: {
          name: 'DynamicShadowSettings',
          displayOrder: 17
        }
      }), _dec33$1 = type$3(CCFloat), _dec34$1 = property$1({
        group: {
          name: 'DynamicShadowSettings',
          displayOrder: 19
        }
      }), _dec35$1 = type$3(CCBoolean), _dec36$1 = property$1({
        group: {
          name: 'DynamicShadowSettings',
          displayOrder: 20
        }
      }), _dec37$1 = type$3(CCBoolean), _dec38$1 = property$1({
        group: {
          name: 'DynamicShadowSettings',
          displayOrder: 21
        }
      }), _dec39$1 = type$3(CCFloat), _dec$1X(_class$1W = (_class2$1K = function (_Light) {
        _inheritsLoose(DirectionalLight, _Light);
        function DirectionalLight() {
          var _this;
          _this = _Light.call(this) || this;
          _this._illuminanceHDR = _initializer$1B && _initializer$1B();
          _this._illuminanceLDR = _initializer2$1h && _initializer2$1h();
          _this._shadowEnabled = _initializer3$Q && _initializer3$Q();
          _this._shadowPcf = _initializer4$F && _initializer4$F();
          _this._shadowBias = _initializer5$t && _initializer5$t();
          _this._shadowNormalBias = _initializer6$l && _initializer6$l();
          _this._shadowSaturation = _initializer7$h && _initializer7$h();
          _this._shadowDistance = _initializer8$g && _initializer8$g();
          _this._shadowInvisibleOcclusionRange = _initializer9$f && _initializer9$f();
          _this._csmLevel = _initializer10$d && _initializer10$d();
          _this._csmLayerLambda = _initializer11$b && _initializer11$b();
          _this._csmOptimizationMode = _initializer12$9 && _initializer12$9();
          _this._csmAdvancedOptions = _initializer13$8 && _initializer13$8();
          _this._csmLayersTransition = _initializer14$6 && _initializer14$6();
          _this._csmTransitionRange = _initializer15$4 && _initializer15$4();
          _this._shadowFixedArea = _initializer16$4 && _initializer16$4();
          _this._shadowNear = _initializer17$3 && _initializer17$3();
          _this._shadowFar = _initializer18$3 && _initializer18$3();
          _this._shadowOrthoSize = _initializer19$2 && _initializer19$2();
          _this._lightType = DirectionalLight$1;
          var highQualityMode = settings.querySettings(Settings.Category.RENDERING, 'highQualityMode');
          if (highQualityMode) {
            _this._shadowPcf = PCFType.SOFT_2X;
            _this._shadowDistance = 50;
            _this.enableCSM = true;
            _this.staticSettings.castShadow = true;
          }
          return _this;
        }
        var _proto = DirectionalLight.prototype;
        _proto._createLight = function _createLight() {
          _Light.prototype._createLight.call(this);
          this._type = LightType.DIRECTIONAL;
          if (this._light) {
            var dirLight = this._light;
            dirLight.illuminanceHDR = this._illuminanceHDR;
            dirLight.illuminanceLDR = this._illuminanceLDR;
            dirLight.shadowEnabled = this._shadowEnabled;
            dirLight.shadowPcf = this._shadowPcf;
            dirLight.shadowBias = this._shadowBias;
            dirLight.shadowNormalBias = this._shadowNormalBias;
            dirLight.shadowSaturation = this._shadowSaturation;
            dirLight.shadowDistance = this._shadowDistance;
            dirLight.shadowInvisibleOcclusionRange = this._shadowInvisibleOcclusionRange;
            dirLight.shadowFixedArea = this._shadowFixedArea;
            dirLight.shadowNear = this._shadowNear;
            dirLight.shadowFar = this._shadowFar;
            dirLight.shadowOrthoSize = this._shadowOrthoSize;
            dirLight.csmLevel = this._csmLevel;
            dirLight.csmLayerLambda = this._csmLayerLambda;
            dirLight.csmOptimizationMode = this._csmOptimizationMode;
            dirLight.csmLayersTransition = this._csmLayersTransition;
            dirLight.csmTransitionRange = this._csmTransitionRange;
          }
        };
        _proto._onUpdateReceiveDirLight = function _onUpdateReceiveDirLight() {
          if (!this._light) {
            return;
          }
          _Light.prototype._onUpdateReceiveDirLight.call(this);
          var scene = this.node.scene;
          if (!scene || !scene.renderScene) {
            return;
          }
          if (scene.renderScene.mainLight !== this._light) {
            return;
          }
          var models = scene.renderScene.models;
          for (var i = 0; i < models.length; i++) {
            var model = models[i];
            if (!model.node) continue;
            var meshRender = model.node.getComponent(MeshRenderer);
            if (!meshRender) continue;
            meshRender.onUpdateReceiveDirLight(this._visibility);
          }
        };
        _createClass(DirectionalLight, [{
          key: "illuminance",
          get: function get() {
            var isHDR = legacyCC.director.root.pipeline.pipelineSceneData.isHDR;
            if (isHDR) {
              return this._illuminanceHDR;
            } else {
              return this._illuminanceLDR;
            }
          },
          set: function set(val) {
            var isHDR = legacyCC.director.root.pipeline.pipelineSceneData.isHDR;
            if (isHDR) {
              this._illuminanceHDR = val;
              this._light && (this._light.illuminanceHDR = this._illuminanceHDR);
            } else {
              this._illuminanceLDR = val;
              this._light && (this._light.illuminanceLDR = this._illuminanceLDR);
            }
          }
        }, {
          key: "shadowEnabled",
          get: function get() {
            return this._shadowEnabled;
          },
          set: function set(val) {
            this._shadowEnabled = val;
            if (this._light) {
              this._light.shadowEnabled = this._shadowEnabled;
            }
          }
        }, {
          key: "shadowPcf",
          get: function get() {
            return this._shadowPcf;
          },
          set: function set(val) {
            this._shadowPcf = val;
            if (this._light) {
              this._light.shadowPcf = this._shadowPcf;
            }
          }
        }, {
          key: "shadowBias",
          get: function get() {
            return this._shadowBias;
          },
          set: function set(val) {
            this._shadowBias = val;
            if (this._light) {
              this._light.shadowBias = this._shadowBias;
            }
          }
        }, {
          key: "shadowNormalBias",
          get: function get() {
            return this._shadowNormalBias;
          },
          set: function set(val) {
            this._shadowNormalBias = val;
            if (this._light) {
              this._light.shadowNormalBias = this._shadowNormalBias;
            }
          }
        }, {
          key: "shadowSaturation",
          get: function get() {
            return this._shadowSaturation;
          },
          set: function set(val) {
            this._shadowSaturation = clamp$1(val, 0.0, 1.0);
            if (this._light) {
              this._light.shadowSaturation = this._shadowSaturation;
            }
          }
        }, {
          key: "shadowDistance",
          get: function get() {
            return this._shadowDistance;
          },
          set: function set(val) {
            this._shadowDistance = Math.min(val, Shadows.MAX_FAR);
            if (this._shadowDistance / 0.1 < 10.0) {
              warnID(15003, this._shadowDistance);
            }
            if (this._light) {
              this._light.shadowDistance = this._shadowDistance;
              this._light.csmNeedUpdate = true;
            }
          }
        }, {
          key: "shadowInvisibleOcclusionRange",
          get: function get() {
            return this._shadowInvisibleOcclusionRange;
          },
          set: function set(val) {
            this._shadowInvisibleOcclusionRange = Math.min(val, Shadows.MAX_FAR);
            if (this._light) {
              this._light.shadowInvisibleOcclusionRange = this._shadowInvisibleOcclusionRange;
            }
          }
        }, {
          key: "csmLevel",
          get: function get() {
            return this._csmLevel;
          },
          set: function set(val) {
            this._csmLevel = val;
            if (this._light) {
              this._light.csmLevel = this._csmLevel;
              this._light.csmNeedUpdate = true;
            }
          }
        }, {
          key: "enableCSM",
          get: function get() {
            return this._csmLevel > CSMLevel.LEVEL_1;
          },
          set: function set(val) {
            this._csmLevel = val ? CSMLevel.LEVEL_4 : CSMLevel.LEVEL_1;
            if (this._light) {
              this._light.csmLevel = this._csmLevel;
              this._light.csmNeedUpdate = true;
            }
          }
        }, {
          key: "csmLayerLambda",
          get: function get() {
            return this._csmLayerLambda;
          },
          set: function set(val) {
            this._csmLayerLambda = val;
            if (this._light) {
              this._light.csmLayerLambda = this._csmLayerLambda;
              this._light.csmNeedUpdate = true;
            }
          }
        }, {
          key: "csmOptimizationMode",
          get: function get() {
            return this._csmOptimizationMode;
          },
          set: function set(val) {
            this._csmOptimizationMode = val;
            if (this._light) {
              this._light.csmOptimizationMode = this._csmOptimizationMode;
            }
          }
        }, {
          key: "shadowFixedArea",
          get: function get() {
            return this._shadowFixedArea;
          },
          set: function set(val) {
            this._shadowFixedArea = val;
            if (this._light) {
              this._light.shadowFixedArea = this._shadowFixedArea;
            }
          }
        }, {
          key: "shadowNear",
          get: function get() {
            return this._shadowNear;
          },
          set: function set(val) {
            this._shadowNear = val;
            if (this._light) {
              this._light.shadowNear = this._shadowNear;
            }
          }
        }, {
          key: "shadowFar",
          get: function get() {
            return this._shadowFar;
          },
          set: function set(val) {
            this._shadowFar = Math.min(val, Shadows.MAX_FAR);
            if (this._light) {
              this._light.shadowFar = this._shadowFar;
            }
          }
        }, {
          key: "shadowOrthoSize",
          get: function get() {
            return this._shadowOrthoSize;
          },
          set: function set(val) {
            this._shadowOrthoSize = val;
            if (this._light) {
              this._light.shadowOrthoSize = this._shadowOrthoSize;
            }
          }
        }, {
          key: "csmAdvancedOptions",
          get: function get() {
            return this._csmAdvancedOptions;
          },
          set: function set(val) {
            this._csmAdvancedOptions = val;
          }
        }, {
          key: "csmLayersTransition",
          get: function get() {
            return this._csmLayersTransition;
          },
          set: function set(val) {
            this._csmLayersTransition = val;
            if (this._light) {
              this._light.csmLayersTransition = val;
            }
          }
        }, {
          key: "csmTransitionRange",
          get: function get() {
            return this._csmTransitionRange;
          },
          set: function set(val) {
            this._csmTransitionRange = val;
            if (this._light) {
              this._light.csmTransitionRange = val;
            }
          }
        }]);
        return DirectionalLight;
      }(Light), (_initializer$1B = applyDecoratedInitializer(_class2$1K.prototype, "_illuminanceHDR", [property$1, _dec2$1t], function () {
        return 65000;
      }), _initializer2$1h = applyDecoratedInitializer(_class2$1K.prototype, "_illuminanceLDR", [serializable$f], function () {
        return 65000 * Camera$1.standardExposureValue;
      }), _initializer3$Q = applyDecoratedInitializer(_class2$1K.prototype, "_shadowEnabled", [serializable$f], function () {
        return false;
      }), _initializer4$F = applyDecoratedInitializer(_class2$1K.prototype, "_shadowPcf", [serializable$f], function () {
        return PCFType.HARD;
      }), _initializer5$t = applyDecoratedInitializer(_class2$1K.prototype, "_shadowBias", [serializable$f], function () {
        return 0.00001;
      }), _initializer6$l = applyDecoratedInitializer(_class2$1K.prototype, "_shadowNormalBias", [serializable$f], function () {
        return 0.0;
      }), _initializer7$h = applyDecoratedInitializer(_class2$1K.prototype, "_shadowSaturation", [serializable$f], function () {
        return 1.0;
      }), _initializer8$g = applyDecoratedInitializer(_class2$1K.prototype, "_shadowDistance", [serializable$f], function () {
        return 50;
      }), _initializer9$f = applyDecoratedInitializer(_class2$1K.prototype, "_shadowInvisibleOcclusionRange", [serializable$f], function () {
        return 200;
      }), _initializer10$d = applyDecoratedInitializer(_class2$1K.prototype, "_csmLevel", [serializable$f], function () {
        return CSMLevel.LEVEL_4;
      }), _initializer11$b = applyDecoratedInitializer(_class2$1K.prototype, "_csmLayerLambda", [serializable$f], function () {
        return 0.75;
      }), _initializer12$9 = applyDecoratedInitializer(_class2$1K.prototype, "_csmOptimizationMode", [serializable$f], function () {
        return CSMOptimizationMode.RemoveDuplicates;
      }), _initializer13$8 = applyDecoratedInitializer(_class2$1K.prototype, "_csmAdvancedOptions", [serializable$f], function () {
        return false;
      }), _initializer14$6 = applyDecoratedInitializer(_class2$1K.prototype, "_csmLayersTransition", [serializable$f], function () {
        return false;
      }), _initializer15$4 = applyDecoratedInitializer(_class2$1K.prototype, "_csmTransitionRange", [serializable$f], function () {
        return 0.05;
      }), _initializer16$4 = applyDecoratedInitializer(_class2$1K.prototype, "_shadowFixedArea", [serializable$f], function () {
        return false;
      }), _initializer17$3 = applyDecoratedInitializer(_class2$1K.prototype, "_shadowNear", [serializable$f], function () {
        return 0.1;
      }), _initializer18$3 = applyDecoratedInitializer(_class2$1K.prototype, "_shadowFar", [serializable$f], function () {
        return 10.0;
      }), _initializer19$2 = applyDecoratedInitializer(_class2$1K.prototype, "_shadowOrthoSize", [serializable$f], function () {
        return 5;
      }), _applyDecoratedDescriptor(_class2$1K.prototype, "illuminance", [_dec3$12], Object.getOwnPropertyDescriptor(_class2$1K.prototype, "illuminance"), _class2$1K.prototype), _applyDecoratedDescriptor(_class2$1K.prototype, "shadowEnabled", [_dec4$O, _dec5$H], Object.getOwnPropertyDescriptor(_class2$1K.prototype, "shadowEnabled"), _class2$1K.prototype), _applyDecoratedDescriptor(_class2$1K.prototype, "shadowPcf", [_dec6$r, _dec7$k], Object.getOwnPropertyDescriptor(_class2$1K.prototype, "shadowPcf"), _class2$1K.prototype), _applyDecoratedDescriptor(_class2$1K.prototype, "shadowBias", [_dec8$e, _dec9$c], Object.getOwnPropertyDescriptor(_class2$1K.prototype, "shadowBias"), _class2$1K.prototype), _applyDecoratedDescriptor(_class2$1K.prototype, "shadowNormalBias", [_dec10$7, _dec11$6], Object.getOwnPropertyDescriptor(_class2$1K.prototype, "shadowNormalBias"), _class2$1K.prototype), _applyDecoratedDescriptor(_class2$1K.prototype, "shadowSaturation", [_dec12$6, _dec13$4], Object.getOwnPropertyDescriptor(_class2$1K.prototype, "shadowSaturation"), _class2$1K.prototype), _applyDecoratedDescriptor(_class2$1K.prototype, "shadowDistance", [_dec14$3, _dec15$3], Object.getOwnPropertyDescriptor(_class2$1K.prototype, "shadowDistance"), _class2$1K.prototype), _applyDecoratedDescriptor(_class2$1K.prototype, "shadowInvisibleOcclusionRange", [_dec16$3, _dec17$3], Object.getOwnPropertyDescriptor(_class2$1K.prototype, "shadowInvisibleOcclusionRange"), _class2$1K.prototype), _applyDecoratedDescriptor(_class2$1K.prototype, "csmLevel", [_dec18$2, _dec19$2], Object.getOwnPropertyDescriptor(_class2$1K.prototype, "csmLevel"), _class2$1K.prototype), _applyDecoratedDescriptor(_class2$1K.prototype, "enableCSM", [_dec20$2, _dec21$2], Object.getOwnPropertyDescriptor(_class2$1K.prototype, "enableCSM"), _class2$1K.prototype), _applyDecoratedDescriptor(_class2$1K.prototype, "csmLayerLambda", [_dec22$2, _dec23$2], Object.getOwnPropertyDescriptor(_class2$1K.prototype, "csmLayerLambda"), _class2$1K.prototype), _applyDecoratedDescriptor(_class2$1K.prototype, "csmOptimizationMode", [_dec24$2, _dec25$2], Object.getOwnPropertyDescriptor(_class2$1K.prototype, "csmOptimizationMode"), _class2$1K.prototype), _applyDecoratedDescriptor(_class2$1K.prototype, "shadowFixedArea", [_dec26$2, _dec27$2], Object.getOwnPropertyDescriptor(_class2$1K.prototype, "shadowFixedArea"), _class2$1K.prototype), _applyDecoratedDescriptor(_class2$1K.prototype, "shadowNear", [_dec28$2, _dec29$2], Object.getOwnPropertyDescriptor(_class2$1K.prototype, "shadowNear"), _class2$1K.prototype), _applyDecoratedDescriptor(_class2$1K.prototype, "shadowFar", [_dec30$1, _dec31$1], Object.getOwnPropertyDescriptor(_class2$1K.prototype, "shadowFar"), _class2$1K.prototype), _applyDecoratedDescriptor(_class2$1K.prototype, "shadowOrthoSize", [_dec32$1, _dec33$1], Object.getOwnPropertyDescriptor(_class2$1K.prototype, "shadowOrthoSize"), _class2$1K.prototype), _applyDecoratedDescriptor(_class2$1K.prototype, "csmAdvancedOptions", [_dec34$1, _dec35$1], Object.getOwnPropertyDescriptor(_class2$1K.prototype, "csmAdvancedOptions"), _class2$1K.prototype), _applyDecoratedDescriptor(_class2$1K.prototype, "csmLayersTransition", [_dec36$1, _dec37$1], Object.getOwnPropertyDescriptor(_class2$1K.prototype, "csmLayersTransition"), _class2$1K.prototype), _applyDecoratedDescriptor(_class2$1K.prototype, "csmTransitionRange", [_dec38$1, _dec39$1], Object.getOwnPropertyDescriptor(_class2$1K.prototype, "csmTransitionRange"), _class2$1K.prototype)), _class2$1K)) || _class$1W));

      var _dec$1W, _dec2$1s, _dec3$11, _dec4$N, _dec5$G, _dec6$q, _dec7$j, _class$1V, _class2$1J, _initializer$1A, _initializer2$1g, _initializer3$P, _initializer4$E, _initializer5$s;
      var SphereLight = exports('a6', (_dec$1W = ccclass$n('cc.SphereLight'), _dec2$1s = formerlySerializedAs$4('_luminance'), _dec3$11 = type$7(CCInteger), _dec4$N = type$7(CCInteger), _dec5$G = type$7(PhotometricTerm), _dec6$q = type$7(CCFloat), _dec7$j = type$7(CCFloat), _dec$1W(_class$1V = (_class2$1J = function (_Light) {
        _inheritsLoose(SphereLight, _Light);
        function SphereLight() {
          var _this;
          _this = _Light.call(this) || this;
          _this._size = _initializer$1A && _initializer$1A();
          _this._luminanceHDR = _initializer2$1g && _initializer2$1g();
          _this._luminanceLDR = _initializer3$P && _initializer3$P();
          _this._term = _initializer4$E && _initializer4$E();
          _this._range = _initializer5$s && _initializer5$s();
          _this._lightType = SphereLight$1;
          return _this;
        }
        var _proto = SphereLight.prototype;
        _proto._createLight = function _createLight() {
          _Light.prototype._createLight.call(this);
          this._type = LightType.SPHERE;
          this.size = this._size;
          this.range = this._range;
          if (this._light) {
            this._light.luminanceHDR = this._luminanceHDR;
            this._light.luminanceLDR = this._luminanceLDR;
          }
        };
        _createClass(SphereLight, [{
          key: "luminousFlux",
          get: function get() {
            var isHDR = legacyCC.director.root.pipeline.pipelineSceneData.isHDR;
            if (isHDR) {
              return this._luminanceHDR * nt2lm(this._size);
            } else {
              return this._luminanceLDR;
            }
          },
          set: function set(val) {
            var isHDR = legacyCC.director.root.pipeline.pipelineSceneData.isHDR;
            var result = 0;
            if (isHDR) {
              this._luminanceHDR = val / nt2lm(this._size);
              result = this._luminanceHDR;
            } else {
              this._luminanceLDR = val;
              result = this._luminanceLDR;
            }
            this._light && (this._light.luminance = result);
          }
        }, {
          key: "luminance",
          get: function get() {
            var isHDR = legacyCC.director.root.pipeline.pipelineSceneData.isHDR;
            if (isHDR) {
              return this._luminanceHDR;
            } else {
              return this._luminanceLDR;
            }
          },
          set: function set(val) {
            var isHDR = legacyCC.director.root.pipeline.pipelineSceneData.isHDR;
            if (isHDR) {
              this._luminanceHDR = val;
              this._light && (this._light.luminanceHDR = this._luminanceHDR);
            } else {
              this._luminanceLDR = val;
              this._light && (this._light.luminanceLDR = this._luminanceLDR);
            }
          }
        }, {
          key: "term",
          get: function get() {
            return this._term;
          },
          set: function set(val) {
            this._term = val;
          }
        }, {
          key: "size",
          get: function get() {
            return this._size;
          },
          set: function set(val) {
            this._size = val;
            if (this._light) {
              this._light.size = val;
            }
          }
        }, {
          key: "range",
          get: function get() {
            return this._range;
          },
          set: function set(val) {
            this._range = val;
            if (this._light) {
              this._light.range = val;
            }
          }
        }]);
        return SphereLight;
      }(Light), (_initializer$1A = applyDecoratedInitializer(_class2$1J.prototype, "_size", [serializable$j], function () {
        return 0.15;
      }), _initializer2$1g = applyDecoratedInitializer(_class2$1J.prototype, "_luminanceHDR", [serializable$j, _dec2$1s], function () {
        return 1700 / nt2lm(0.15);
      }), _initializer3$P = applyDecoratedInitializer(_class2$1J.prototype, "_luminanceLDR", [serializable$j], function () {
        return 1700 / nt2lm(0.15) * Camera$1.standardExposureValue * Camera$1.standardLightMeterScale;
      }), _initializer4$E = applyDecoratedInitializer(_class2$1J.prototype, "_term", [serializable$j], function () {
        return PhotometricTerm.LUMINOUS_FLUX;
      }), _initializer5$s = applyDecoratedInitializer(_class2$1J.prototype, "_range", [serializable$j], function () {
        return 1;
      }), _applyDecoratedDescriptor(_class2$1J.prototype, "luminousFlux", [_dec3$11], Object.getOwnPropertyDescriptor(_class2$1J.prototype, "luminousFlux"), _class2$1J.prototype), _applyDecoratedDescriptor(_class2$1J.prototype, "luminance", [_dec4$N], Object.getOwnPropertyDescriptor(_class2$1J.prototype, "luminance"), _class2$1J.prototype), _applyDecoratedDescriptor(_class2$1J.prototype, "term", [_dec5$G], Object.getOwnPropertyDescriptor(_class2$1J.prototype, "term"), _class2$1J.prototype), _applyDecoratedDescriptor(_class2$1J.prototype, "size", [_dec6$q], Object.getOwnPropertyDescriptor(_class2$1J.prototype, "size"), _class2$1J.prototype), _applyDecoratedDescriptor(_class2$1J.prototype, "range", [_dec7$j], Object.getOwnPropertyDescriptor(_class2$1J.prototype, "range"), _class2$1J.prototype)), _class2$1J)) || _class$1V));

      var _dec$1V, _dec2$1r, _dec3$10, _dec4$M, _dec5$F, _dec6$p, _dec7$i, _dec8$d, _dec9$b, _dec10$6, _dec11$5, _dec12$5, _class$1U, _class2$1I, _initializer$1z, _initializer2$1f, _initializer3$O, _initializer4$D, _initializer5$r, _initializer6$k, _initializer7$g, _initializer8$f, _initializer9$e, _initializer10$c;
      var ccclass$h = ccclass$n,
        type$2 = type$7,
        serializable$e = serializable$j,
        formerlySerializedAs$1 = formerlySerializedAs$4,
        property = property$3;
      var SpotLight = exports('a7', (_dec$1V = ccclass$h('cc.SpotLight'), _dec2$1r = formerlySerializedAs$1('_luminance'), _dec3$10 = type$2(PhotometricTerm), _dec4$M = type$2(CCFloat), _dec5$F = property({
        group: {
          name: 'DynamicShadowSettings',
          displayOrder: 1
        }
      }), _dec6$p = type$2(CCBoolean), _dec7$i = property({
        group: {
          name: 'DynamicShadowSettings',
          displayOrder: 2
        }
      }), _dec8$d = type$2(PCFType), _dec9$b = property({
        group: {
          name: 'DynamicShadowSettings',
          displayOrder: 3
        }
      }), _dec10$6 = type$2(CCFloat), _dec11$5 = property({
        group: {
          name: 'DynamicShadowSettings',
          displayOrder: 4
        }
      }), _dec12$5 = type$2(CCFloat), _dec$1V(_class$1U = (_class2$1I = function (_Light) {
        _inheritsLoose(SpotLight, _Light);
        function SpotLight() {
          var _this;
          _this = _Light.call(this) || this;
          _this._size = _initializer$1z && _initializer$1z();
          _this._luminanceHDR = _initializer2$1f && _initializer2$1f();
          _this._luminanceLDR = _initializer3$O && _initializer3$O();
          _this._term = _initializer4$D && _initializer4$D();
          _this._range = _initializer5$r && _initializer5$r();
          _this._spotAngle = _initializer6$k && _initializer6$k();
          _this._shadowEnabled = _initializer7$g && _initializer7$g();
          _this._shadowPcf = _initializer8$f && _initializer8$f();
          _this._shadowBias = _initializer9$e && _initializer9$e();
          _this._shadowNormalBias = _initializer10$c && _initializer10$c();
          _this._lightType = SpotLight$1;
          return _this;
        }
        var _proto = SpotLight.prototype;
        _proto._createLight = function _createLight() {
          _Light.prototype._createLight.call(this);
          this._type = LightType.SPOT;
          this.size = this._size;
          this.range = this._range;
          this.spotAngle = this._spotAngle;
          if (this._light) {
            var spotLight = this._light;
            spotLight.luminanceHDR = this._luminanceHDR;
            spotLight.luminanceLDR = this._luminanceLDR;
            spotLight.shadowEnabled = this._shadowEnabled;
            spotLight.shadowPcf = this._shadowPcf;
            spotLight.shadowBias = this._shadowBias;
            spotLight.shadowNormalBias = this._shadowNormalBias;
          }
        };
        _createClass(SpotLight, [{
          key: "luminousFlux",
          get: function get() {
            var isHDR = legacyCC.director.root.pipeline.pipelineSceneData.isHDR;
            if (isHDR) {
              return this._luminanceHDR * nt2lm(this._size);
            } else {
              return this._luminanceLDR;
            }
          },
          set: function set(val) {
            var isHDR = legacyCC.director.root.pipeline.pipelineSceneData.isHDR;
            var result = 0;
            if (isHDR) {
              this._luminanceHDR = val / nt2lm(this._size);
              result = this._luminanceHDR;
            } else {
              this._luminanceLDR = val;
              result = this._luminanceLDR;
            }
            this._light && (this._light.luminance = result);
          }
        }, {
          key: "luminance",
          get: function get() {
            var isHDR = legacyCC.director.root.pipeline.pipelineSceneData.isHDR;
            if (isHDR) {
              return this._luminanceHDR;
            } else {
              return this._luminanceLDR;
            }
          },
          set: function set(val) {
            var isHDR = legacyCC.director.root.pipeline.pipelineSceneData.isHDR;
            if (isHDR) {
              this._luminanceHDR = val;
              this._light && (this._light.luminanceHDR = this._luminanceHDR);
            } else {
              this._luminanceLDR = val;
              this._light && (this._light.luminanceLDR = this._luminanceLDR);
            }
          }
        }, {
          key: "term",
          get: function get() {
            return this._term;
          },
          set: function set(val) {
            this._term = val;
          }
        }, {
          key: "size",
          get: function get() {
            return this._size;
          },
          set: function set(val) {
            this._size = val;
            if (this._light) {
              this._light.size = val;
            }
          }
        }, {
          key: "range",
          get: function get() {
            return this._range;
          },
          set: function set(val) {
            this._range = val;
            if (this._light) {
              this._light.range = val;
            }
          }
        }, {
          key: "spotAngle",
          get: function get() {
            return this._spotAngle;
          },
          set: function set(val) {
            this._spotAngle = val;
            if (this._light) {
              this._light.spotAngle = toRadian(val);
            }
          }
        }, {
          key: "shadowEnabled",
          get: function get() {
            return this._shadowEnabled;
          },
          set: function set(val) {
            this._shadowEnabled = val;
            if (this._light) {
              this._light.shadowEnabled = val;
            }
          }
        }, {
          key: "shadowPcf",
          get: function get() {
            return this._shadowPcf;
          },
          set: function set(val) {
            this._shadowPcf = val;
            if (this._light) {
              this._light.shadowPcf = val;
            }
          }
        }, {
          key: "shadowBias",
          get: function get() {
            return this._shadowBias;
          },
          set: function set(val) {
            this._shadowBias = val;
            if (this._light) {
              this._light.shadowBias = val;
            }
          }
        }, {
          key: "shadowNormalBias",
          get: function get() {
            return this._shadowNormalBias;
          },
          set: function set(val) {
            this._shadowNormalBias = val;
            if (this._light) {
              this._light.shadowNormalBias = val;
            }
          }
        }]);
        return SpotLight;
      }(Light), (_initializer$1z = applyDecoratedInitializer(_class2$1I.prototype, "_size", [serializable$e], function () {
        return 0.15;
      }), _initializer2$1f = applyDecoratedInitializer(_class2$1I.prototype, "_luminanceHDR", [serializable$e, _dec2$1r], function () {
        return 1700 / nt2lm(0.15);
      }), _initializer3$O = applyDecoratedInitializer(_class2$1I.prototype, "_luminanceLDR", [serializable$e], function () {
        return 1700 / nt2lm(0.15) * Camera$1.standardExposureValue * Camera$1.standardLightMeterScale;
      }), _initializer4$D = applyDecoratedInitializer(_class2$1I.prototype, "_term", [serializable$e], function () {
        return PhotometricTerm.LUMINOUS_FLUX;
      }), _initializer5$r = applyDecoratedInitializer(_class2$1I.prototype, "_range", [serializable$e], function () {
        return 1;
      }), _initializer6$k = applyDecoratedInitializer(_class2$1I.prototype, "_spotAngle", [serializable$e], function () {
        return 60;
      }), _initializer7$g = applyDecoratedInitializer(_class2$1I.prototype, "_shadowEnabled", [serializable$e], function () {
        return false;
      }), _initializer8$f = applyDecoratedInitializer(_class2$1I.prototype, "_shadowPcf", [serializable$e], function () {
        return PCFType.HARD;
      }), _initializer9$e = applyDecoratedInitializer(_class2$1I.prototype, "_shadowBias", [serializable$e], function () {
        return 0.00001;
      }), _initializer10$c = applyDecoratedInitializer(_class2$1I.prototype, "_shadowNormalBias", [serializable$e], function () {
        return 0.0;
      }), _applyDecoratedDescriptor(_class2$1I.prototype, "term", [_dec3$10], Object.getOwnPropertyDescriptor(_class2$1I.prototype, "term"), _class2$1I.prototype), _applyDecoratedDescriptor(_class2$1I.prototype, "size", [_dec4$M], Object.getOwnPropertyDescriptor(_class2$1I.prototype, "size"), _class2$1I.prototype), _applyDecoratedDescriptor(_class2$1I.prototype, "shadowEnabled", [_dec5$F, _dec6$p], Object.getOwnPropertyDescriptor(_class2$1I.prototype, "shadowEnabled"), _class2$1I.prototype), _applyDecoratedDescriptor(_class2$1I.prototype, "shadowPcf", [_dec7$i, _dec8$d], Object.getOwnPropertyDescriptor(_class2$1I.prototype, "shadowPcf"), _class2$1I.prototype), _applyDecoratedDescriptor(_class2$1I.prototype, "shadowBias", [_dec9$b, _dec10$6], Object.getOwnPropertyDescriptor(_class2$1I.prototype, "shadowBias"), _class2$1I.prototype), _applyDecoratedDescriptor(_class2$1I.prototype, "shadowNormalBias", [_dec11$5, _dec12$5], Object.getOwnPropertyDescriptor(_class2$1I.prototype, "shadowNormalBias"), _class2$1I.prototype)), _class2$1I)) || _class$1U));

      var _dec$1U, _dec2$1q, _dec3$$, _dec4$L, _dec5$E, _dec6$o, _class$1T, _class2$1H, _initializer$1y, _initializer2$1e, _initializer3$N, _initializer4$C;
      var PointLight = exports('a8', (_dec$1U = ccclass$n('cc.PointLight'), _dec2$1q = formerlySerializedAs$4('_luminance'), _dec3$$ = type$7(CCInteger), _dec4$L = type$7(CCInteger), _dec5$E = type$7(PhotometricTerm), _dec6$o = type$7(CCFloat), _dec$1U(_class$1T = (_class2$1H = function (_Light) {
        _inheritsLoose(PointLight, _Light);
        function PointLight() {
          var _this;
          _this = _Light.call(this) || this;
          _this._luminanceHDR = _initializer$1y && _initializer$1y();
          _this._luminanceLDR = _initializer2$1e && _initializer2$1e();
          _this._term = _initializer3$N && _initializer3$N();
          _this._range = _initializer4$C && _initializer4$C();
          _this._lightType = PointLight$1;
          return _this;
        }
        var _proto = PointLight.prototype;
        _proto._createLight = function _createLight() {
          _Light.prototype._createLight.call(this);
          this._type = LightType.POINT;
          this.range = this._range;
          if (this._light) {
            this._light.luminanceHDR = this._luminanceHDR;
            this._light.luminanceLDR = this._luminanceLDR;
          }
        };
        _createClass(PointLight, [{
          key: "luminousFlux",
          get: function get() {
            var isHDR = legacyCC.director.root.pipeline.pipelineSceneData.isHDR;
            if (isHDR) {
              return this._luminanceHDR * nt2lm(1.0);
            } else {
              return this._luminanceLDR;
            }
          },
          set: function set(val) {
            var isHDR = legacyCC.director.root.pipeline.pipelineSceneData.isHDR;
            var result = 0;
            if (isHDR) {
              this._luminanceHDR = val / nt2lm(1.0);
              result = this._luminanceHDR;
            } else {
              this._luminanceLDR = val;
              result = this._luminanceLDR;
            }
            this._light && (this._light.luminance = result);
          }
        }, {
          key: "luminance",
          get: function get() {
            var isHDR = legacyCC.director.root.pipeline.pipelineSceneData.isHDR;
            if (isHDR) {
              return this._luminanceHDR;
            } else {
              return this._luminanceLDR;
            }
          },
          set: function set(val) {
            var isHDR = legacyCC.director.root.pipeline.pipelineSceneData.isHDR;
            if (isHDR) {
              this._luminanceHDR = val;
              this._light && (this._light.luminanceHDR = this._luminanceHDR);
            } else {
              this._luminanceLDR = val;
              this._light && (this._light.luminanceLDR = this._luminanceLDR);
            }
          }
        }, {
          key: "term",
          get: function get() {
            return this._term;
          },
          set: function set(val) {
            this._term = val;
          }
        }, {
          key: "range",
          get: function get() {
            return this._range;
          },
          set: function set(val) {
            this._range = val;
            if (this._light) {
              this._light.range = val;
            }
          }
        }]);
        return PointLight;
      }(Light), (_initializer$1y = applyDecoratedInitializer(_class2$1H.prototype, "_luminanceHDR", [serializable$j, _dec2$1q], function () {
        return 1700 / nt2lm(0.15);
      }), _initializer2$1e = applyDecoratedInitializer(_class2$1H.prototype, "_luminanceLDR", [serializable$j], function () {
        return 1700 / nt2lm(0.15) * Camera$1.standardExposureValue * Camera$1.standardLightMeterScale;
      }), _initializer3$N = applyDecoratedInitializer(_class2$1H.prototype, "_term", [serializable$j], function () {
        return PhotometricTerm.LUMINOUS_FLUX;
      }), _initializer4$C = applyDecoratedInitializer(_class2$1H.prototype, "_range", [serializable$j], function () {
        return 1;
      }), _applyDecoratedDescriptor(_class2$1H.prototype, "luminousFlux", [_dec3$$], Object.getOwnPropertyDescriptor(_class2$1H.prototype, "luminousFlux"), _class2$1H.prototype), _applyDecoratedDescriptor(_class2$1H.prototype, "luminance", [_dec4$L], Object.getOwnPropertyDescriptor(_class2$1H.prototype, "luminance"), _class2$1H.prototype), _applyDecoratedDescriptor(_class2$1H.prototype, "term", [_dec5$E], Object.getOwnPropertyDescriptor(_class2$1H.prototype, "term"), _class2$1H.prototype), _applyDecoratedDescriptor(_class2$1H.prototype, "range", [_dec6$o], Object.getOwnPropertyDescriptor(_class2$1H.prototype, "range"), _class2$1H.prototype)), _class2$1H)) || _class$1T));

      var _dec$1T, _dec2$1p, _dec3$_, _class$1S, _class2$1G, _initializer$1x, _initializer2$1d;
      var RangedDirectionalLight = exports('a9', (_dec$1T = ccclass$n('cc.RangedDirectionalLight'), _dec2$1p = formerlySerializedAs$4('_illuminance'), _dec3$_ = type$7(CCInteger), _dec$1T(_class$1S = (_class2$1G = function (_Light) {
        _inheritsLoose(RangedDirectionalLight, _Light);
        function RangedDirectionalLight() {
          var _this;
          _this = _Light.call(this) || this;
          _this._illuminanceHDR = _initializer$1x && _initializer$1x();
          _this._illuminanceLDR = _initializer2$1d && _initializer2$1d();
          _this._lightType = RangedDirectionalLight$1;
          return _this;
        }
        var _proto = RangedDirectionalLight.prototype;
        _proto._createLight = function _createLight() {
          _Light.prototype._createLight.call(this);
          this._type = LightType.RANGED_DIRECTIONAL;
          if (this._light) {
            this._light.illuminanceHDR = this._illuminanceHDR;
            this._light.illuminanceLDR = this._illuminanceLDR;
          }
        };
        _createClass(RangedDirectionalLight, [{
          key: "illuminance",
          get: function get() {
            var isHDR = legacyCC.director.root.pipeline.pipelineSceneData.isHDR;
            if (isHDR) {
              return this._illuminanceHDR;
            } else {
              return this._illuminanceLDR;
            }
          },
          set: function set(val) {
            var isHDR = legacyCC.director.root.pipeline.pipelineSceneData.isHDR;
            if (isHDR) {
              this._illuminanceHDR = val;
              this._light && (this._light.illuminanceHDR = this._illuminanceHDR);
            } else {
              this._illuminanceLDR = val;
              this._light && (this._light.illuminanceLDR = this._illuminanceLDR);
            }
          }
        }]);
        return RangedDirectionalLight;
      }(Light), (_initializer$1x = applyDecoratedInitializer(_class2$1G.prototype, "_illuminanceHDR", [property$3, _dec2$1p], function () {
        return 65000;
      }), _initializer2$1d = applyDecoratedInitializer(_class2$1G.prototype, "_illuminanceLDR", [serializable$j], function () {
        return 65000 * Camera$1.standardExposureValue;
      }), _applyDecoratedDescriptor(_class2$1G.prototype, "illuminance", [_dec3$_], Object.getOwnPropertyDescriptor(_class2$1G.prototype, "illuminance"), _class2$1G.prototype)), _class2$1G)) || _class$1S));

      var BAKE_SKELETON_CURVE_SYMBOL = Symbol('BakeNodeCurves');

      var SkelAnimDataHub = exports('fb', function () {
        function SkelAnimDataHub() {}
        SkelAnimDataHub.getOrExtract = function getOrExtract(clip) {
          var data = SkelAnimDataHub.pool.get(clip);
          if (!data || data.samples !== clip.sample) {
            if (data) {
              legacyCC.director.root.dataPoolManager.releaseAnimationClip(clip);
            }
            var frames = Math.ceil(clip.sample * clip.duration) + 1;
            var step = clip.sample;
            data = clip[BAKE_SKELETON_CURVE_SYMBOL](0, step, frames);
            SkelAnimDataHub.pool.set(clip, data);
          }
          return data;
        };
        SkelAnimDataHub.destroy = function destroy(clip) {
          SkelAnimDataHub.pool["delete"](clip);
        };
        return SkelAnimDataHub;
      }());
      SkelAnimDataHub.pool = new Map();

      var m4_1$4 = new Mat4();
      function getPathFromRoot(target, root) {
        var node = target;
        var path = '';
        while (node !== null && node !== root) {
          path = node.name + "/" + path;
          node = node.parent;
        }
        return path.slice(0, -1);
      }
      function getWorldTransformUntilRoot(target, root, outMatrix) {
        Mat4.identity(outMatrix);
        while (target !== root) {
          Mat4.fromRTS(m4_1$4, target.rotation, target.position, target.scale);
          Mat4.multiply(outMatrix, m4_1$4, outMatrix);
          target = target.parent;
        }
        return outMatrix;
      }

      var jointTextureSamplerInfo = new SamplerInfo(Filter$1.POINT, Filter$1.POINT, Filter$1.NONE, Address.CLAMP, Address.CLAMP, Address.CLAMP);

      var uploadJointData = uploadJointDataLBS;
      var MINIMUM_JOINT_TEXTURE_SIZE = 480;
      function selectJointsMediumFormat(device) {
        if (device.getFormatFeatures(Format.RGBA32F) & FormatFeatureBit.SAMPLED_TEXTURE) {
          return Format.RGBA32F;
        }
        return Format.RGBA8;
      }
      function uploadJointDataLBS(out, base, mat, firstBone) {
        out[base + 0] = mat.m00;
        out[base + 1] = mat.m01;
        out[base + 2] = mat.m02;
        out[base + 3] = mat.m12;
        out[base + 4] = mat.m04;
        out[base + 5] = mat.m05;
        out[base + 6] = mat.m06;
        out[base + 7] = mat.m13;
        out[base + 8] = mat.m08;
        out[base + 9] = mat.m09;
        out[base + 10] = mat.m10;
        out[base + 11] = mat.m14;
      }
      new Quat();
      new Quat();
      new Vec3();
      new Quat();
      new Vec3();
      function roundUpTextureSize(targetLength, formatSize) {
        var formatScale = 4 / Math.sqrt(formatSize);
        return Math.ceil(Math.max(MINIMUM_JOINT_TEXTURE_SIZE * formatScale, targetLength) / 12) * 12;
      }
      var v3_3 = new Vec3();
      var v3_4 = new Vec3();
      var v3_min$1 = new Vec3();
      var v3_max$1 = new Vec3();
      var m4_1$3 = new Mat4();
      var m4_2$2 = new Mat4();
      var ab_1$1 = new AABB();
      var Inf = Number.MAX_SAFE_INTEGER;
      var JointTexturePool = function () {
        function JointTexturePool(device) {
          this._device = void 0;
          this._pool = void 0;
          this._textureBuffers = new Map();
          this._formatSize = void 0;
          this._pixelsPerJoint = void 0;
          this._customPool = void 0;
          this._chunkIdxMap = new Map();
          this._device = device;
          var format = selectJointsMediumFormat(this._device);
          this._formatSize = FormatInfos[format].size;
          this._pixelsPerJoint = 48 / this._formatSize;
          this._pool = new TextureBufferPool(device);
          this._pool.initialize({
            format: format,
            roundUpFn: roundUpTextureSize
          });
          this._customPool = new TextureBufferPool(device);
          this._customPool.initialize({
            format: format,
            roundUpFn: roundUpTextureSize
          });
        }
        var _proto = JointTexturePool.prototype;
        _proto.clear = function clear() {
          this._pool.destroy();
          this._textureBuffers.clear();
        };
        _proto.registerCustomTextureLayouts = function registerCustomTextureLayouts(layouts) {
          for (var i = 0; i < layouts.length; i++) {
            var layout = layouts[i];
            var textureLength = layout.textureLength;
            if (!(this._device.getFormatFeatures(Format.RGBA32F) & FormatFeatureBit.SAMPLED_TEXTURE)) {
              textureLength *= 2;
            }
            var chunkIdx = this._customPool.createChunk(textureLength);
            for (var j = 0; j < layout.contents.length; j++) {
              var content = layout.contents[j];
              var skeleton = content.skeleton;
              this._chunkIdxMap.set(skeleton, chunkIdx);
              for (var k = 0; k < content.clips.length; k++) {
                var clip = content.clips[k];
                this._chunkIdxMap.set(skeleton ^ clip, chunkIdx);
              }
            }
          }
        };
        _proto.getDefaultPoseTexture = function getDefaultPoseTexture(skeleton, mesh, skinningRoot) {
          var hash = skeleton.hash ^ 0;
          var texture = this._textureBuffers.get(hash) || null;
          if (texture && texture.bounds.has(mesh.hash)) {
            texture.refCount++;
            return texture;
          }
          var joints = skeleton.joints,
            bindposes = skeleton.bindposes;
          var textureBuffer = null;
          var buildTexture = false;
          var jointCount = joints.length;
          if (!texture) {
            var bufSize = jointCount * 12;
            var customChunkIdx = this._chunkIdxMap.get(hash);
            var handle = customChunkIdx !== undefined ? this._customPool.alloc(bufSize * Float32Array.BYTES_PER_ELEMENT, customChunkIdx) : this._pool.alloc(bufSize * Float32Array.BYTES_PER_ELEMENT);
            if (!handle) {
              return texture;
            }
            texture = {
              pixelOffset: handle.start / this._formatSize,
              refCount: 1,
              bounds: new Map(),
              skeletonHash: skeleton.hash,
              clipHash: 0,
              readyToBeDeleted: false,
              handle: handle
            };
            textureBuffer = new Float32Array(bufSize);
            buildTexture = true;
          } else {
            texture.refCount++;
          }
          Vec3.set(v3_min$1, Inf, Inf, Inf);
          Vec3.set(v3_max$1, -Inf, -Inf, -Inf);
          var boneSpaceBounds = mesh.getBoneSpaceBounds(skeleton);
          for (var j = 0, offset = 0; j < jointCount; j++, offset += 12) {
            var node = skinningRoot.getChildByPath(joints[j]);
            var mat = node ? getWorldTransformUntilRoot(node, skinningRoot, m4_1$3) : skeleton.inverseBindposes[j];
            var bound = boneSpaceBounds[j];
            if (bound) {
              AABB.transform(ab_1$1, bound, mat);
              ab_1$1.getBoundary(v3_3, v3_4);
              Vec3.min(v3_min$1, v3_min$1, v3_3);
              Vec3.max(v3_max$1, v3_max$1, v3_4);
            }
            if (buildTexture) {
              if (node) {
                Mat4.multiply(mat, mat, bindposes[j]);
              }
              uploadJointData(textureBuffer, offset, node ? mat : Mat4.IDENTITY);
            }
          }
          var bounds = [new AABB()];
          texture.bounds.set(mesh.hash, bounds);
          AABB.fromPoints(bounds[0], v3_min$1, v3_max$1);
          if (buildTexture) {
            this._pool.update(texture.handle, textureBuffer.buffer);
            this._textureBuffers.set(hash, texture);
          }
          return texture;
        };
        _proto.getSequencePoseTexture = function getSequencePoseTexture(skeleton, clip, mesh, skinningRoot) {
          var hash = skeleton.hash ^ clip.hash;
          var texture = this._textureBuffers.get(hash) || null;
          if (texture && texture.bounds.has(mesh.hash)) {
            texture.refCount++;
            return texture;
          }
          var joints = skeleton.joints,
            bindposes = skeleton.bindposes;
          var clipData = SkelAnimDataHub.getOrExtract(clip);
          var frames = clipData.frames;
          var textureBuffer = null;
          var buildTexture = false;
          var jointCount = joints.length;
          if (!texture) {
            var bufSize = jointCount * 12 * frames;
            var customChunkIdx = this._chunkIdxMap.get(hash);
            var handle = customChunkIdx !== undefined ? this._customPool.alloc(bufSize * Float32Array.BYTES_PER_ELEMENT, customChunkIdx) : this._pool.alloc(bufSize * Float32Array.BYTES_PER_ELEMENT);
            if (!handle) {
              return null;
            }
            var animInfos = this._createAnimInfos(skeleton, clip, skinningRoot);
            texture = {
              pixelOffset: handle.start / this._formatSize,
              refCount: 1,
              bounds: new Map(),
              skeletonHash: skeleton.hash,
              clipHash: clip.hash,
              readyToBeDeleted: false,
              handle: handle,
              animInfos: animInfos
            };
            textureBuffer = new Float32Array(bufSize);
            buildTexture = true;
          } else {
            texture.refCount++;
          }
          var boneSpaceBounds = mesh.getBoneSpaceBounds(skeleton);
          var bounds = [];
          texture.bounds.set(mesh.hash, bounds);
          for (var f = 0; f < frames; f++) {
            bounds.push(new AABB(Inf, Inf, Inf, -Inf, -Inf, -Inf));
          }
          for (var _f = 0, offset = 0; _f < frames; _f++) {
            var bound = bounds[_f];
            for (var j = 0; j < jointCount; j++, offset += 12) {
              var _j = texture.animInfos[j],
                curveData = _j.curveData,
                downstream = _j.downstream,
                bindposeIdx = _j.bindposeIdx,
                bindposeCorrection = _j.bindposeCorrection;
              var mat = void 0;
              var transformValid = true;
              if (curveData && downstream) {
                mat = Mat4.multiply(m4_1$3, curveData[_f], downstream);
              } else if (curveData) {
                mat = curveData[_f];
              } else if (downstream) {
                mat = downstream;
              } else {
                mat = skeleton.inverseBindposes[bindposeIdx];
                transformValid = false;
              }
              var boneSpaceBound = boneSpaceBounds[j];
              if (boneSpaceBound) {
                var transform = bindposeCorrection ? Mat4.multiply(m4_2$2, mat, bindposeCorrection) : mat;
                AABB.transform(ab_1$1, boneSpaceBound, transform);
                ab_1$1.getBoundary(v3_3, v3_4);
                Vec3.min(bound.center, bound.center, v3_3);
                Vec3.max(bound.halfExtents, bound.halfExtents, v3_4);
              }
              if (buildTexture) {
                if (transformValid) {
                  Mat4.multiply(m4_1$3, mat, bindposes[bindposeIdx]);
                }
                uploadJointData(textureBuffer, offset, transformValid ? m4_1$3 : Mat4.IDENTITY);
              }
            }
            AABB.fromPoints(bound, bound.center, bound.halfExtents);
          }
          if (buildTexture) {
            this._pool.update(texture.handle, textureBuffer.buffer);
            this._textureBuffers.set(hash, texture);
          }
          return texture;
        };
        _proto.releaseHandle = function releaseHandle(handle) {
          if (handle.refCount > 0) {
            handle.refCount--;
          }
          if (!handle.refCount && handle.readyToBeDeleted) {
            var hash = handle.skeletonHash ^ handle.clipHash;
            var customChunkIdx = this._chunkIdxMap.get(hash);
            (customChunkIdx !== undefined ? this._customPool : this._pool).free(handle.handle);
            if (this._textureBuffers.get(hash) === handle) {
              this._textureBuffers["delete"](hash);
            }
          }
        };
        _proto.releaseSkeleton = function releaseSkeleton(skeleton) {
          var it = this._textureBuffers.values();
          var res = it.next();
          while (!res.done) {
            var handle = res.value;
            if (handle.skeletonHash === skeleton.hash) {
              handle.readyToBeDeleted = true;
              if (handle.refCount) {
                this._textureBuffers["delete"](handle.skeletonHash ^ handle.clipHash);
              } else {
                this.releaseHandle(handle);
              }
            }
            res = it.next();
          }
        };
        _proto.releaseAnimationClip = function releaseAnimationClip(clip) {
          var it = this._textureBuffers.values();
          var res = it.next();
          while (!res.done) {
            var handle = res.value;
            if (handle.clipHash === clip.hash) {
              handle.readyToBeDeleted = true;
              if (handle.refCount) {
                this._textureBuffers["delete"](handle.skeletonHash ^ handle.clipHash);
              } else {
                this.releaseHandle(handle);
              }
            }
            res = it.next();
          }
        };
        _proto._createAnimInfos = function _createAnimInfos(skeleton, clip, skinningRoot) {
          var animInfos = [];
          var joints = skeleton.joints,
            bindposes = skeleton.bindposes;
          var jointCount = joints.length;
          var clipData = SkelAnimDataHub.getOrExtract(clip);
          for (var j = 0; j < jointCount; j++) {
            var animPath = joints[j];
            var source = clipData.joints[animPath];
            var animNode = skinningRoot.getChildByPath(animPath);
            var downstream = void 0;
            var correctionPath = void 0;
            while (!source) {
              var idx = animPath.lastIndexOf('/');
              animPath = animPath.substring(0, idx);
              source = clipData.joints[animPath];
              if (animNode) {
                if (!downstream) {
                  downstream = new Mat4();
                }
                Mat4.fromRTS(m4_1$3, animNode.rotation, animNode.position, animNode.scale);
                Mat4.multiply(downstream, m4_1$3, downstream);
                animNode = animNode.parent;
              } else {
                correctionPath = animPath;
              }
              if (idx < 0) {
                break;
              }
            }
            var bindposeIdx = j;
            var bindposeCorrection = void 0;
            if (correctionPath !== undefined && source) {
              bindposeIdx = j - 1;
              for (var t = 0; t < jointCount; t++) {
                if (joints[t] === correctionPath) {
                  bindposeIdx = t;
                  bindposeCorrection = new Mat4();
                  Mat4.multiply(bindposeCorrection, bindposes[t], skeleton.inverseBindposes[j]);
                  break;
                }
              }
            }
            animInfos.push({
              curveData: source && source.transforms,
              downstream: downstream,
              bindposeIdx: bindposeIdx,
              bindposeCorrection: bindposeCorrection
            });
          }
          return animInfos;
        };
        _createClass(JointTexturePool, [{
          key: "pixelsPerJoint",
          get: function get() {
            return this._pixelsPerJoint;
          }
        }]);
        return JointTexturePool;
      }();
      var JointAnimationInfo = function () {
        function JointAnimationInfo(device) {
          this._pool = new Map();
          this._device = void 0;
          this._device = device;
        }
        var _proto2 = JointAnimationInfo.prototype;
        _proto2.getData = function getData(nodeID) {
          if (nodeID === void 0) {
            nodeID = '-1';
          }
          var res = this._pool.get(nodeID);
          if (res) {
            return res;
          }
          var buffer = this._device.createBuffer(new BufferInfo(BufferUsageBit.UNIFORM | BufferUsageBit.TRANSFER_DST, MemoryUsageBit.HOST | MemoryUsageBit.DEVICE, UBOSkinningAnimation.SIZE, UBOSkinningAnimation.SIZE));
          var data = new Float32Array([0, 0, 0, 0]);
          buffer.update(data);
          var info = {
            buffer: buffer,
            data: data,
            dirty: false,
            dirtyForJSB: new Uint8Array([0]),
            currentClip: null
          };
          this._pool.set(nodeID, info);
          return info;
        };
        _proto2.destroy = function destroy(nodeID) {
          var info = this._pool.get(nodeID);
          if (!info) {
            return;
          }
          info.buffer.destroy();
          this._pool["delete"](nodeID);
        };
        _proto2.switchClip = function switchClip(info, clip) {
          info.currentClip = clip;
          info.data[0] = 0;
          info.buffer.update(info.data);
          info.dirty = false;
          return info;
        };
        _proto2.clear = function clear() {
          for (var _iterator = _createForOfIteratorHelperLoose(this._pool.values()), _step; !(_step = _iterator()).done;) {
            var info = _step.value;
            info.buffer.destroy();
          }
          this._pool.clear();
        };
        return JointAnimationInfo;
      }();

      var stack = [];
      var pool = new Map();
      function getWorldMatrix(transform, stamp) {
        var i = 0;
        var res = Mat4.IDENTITY;
        while (transform) {
          if (transform.stamp === stamp || transform.stamp + 1 === stamp && !transform.node.hasChangedFlags) {
            res = transform.world;
            transform.stamp = stamp;
            break;
          }
          transform.stamp = stamp;
          stack[i++] = transform;
          transform = transform.parent;
        }
        while (i > 0) {
          transform = stack[--i];
          stack[i] = null;
          var node = transform.node;
          Mat4.fromRTS(transform.local, node.rotation, node.position, node.scale);
          res = Mat4.multiply(transform.world, res, transform.local);
        }
        return res;
      }
      function getTransform(node, root) {
        var joint = null;
        var i = 0;
        while (node !== root) {
          var id = node.uuid;
          if (pool.has(id)) {
            joint = pool.get(id);
            break;
          } else {
            joint = {
              node: node,
              local: new Mat4(),
              world: new Mat4(),
              stamp: -1,
              parent: null
            };
            pool.set(id, joint);
          }
          stack[i++] = joint;
          node = node.parent;
          joint = null;
        }
        var child;
        while (i > 0) {
          child = stack[--i];
          stack[i] = null;
          child.parent = joint;
          joint = child;
        }
        return joint;
      }
      function deleteTransform(node) {
        var transform = pool.get(node.uuid) || null;
        while (transform) {
          pool["delete"](transform.node.uuid);
          transform = transform.parent;
        }
      }

      var uniformPatches = [{
        name: 'CC_USE_SKINNING',
        value: true
      }, {
        name: 'CC_USE_REAL_TIME_JOINT_TEXTURE',
        value: false
      }];
      var texturePatches = [{
        name: 'CC_USE_SKINNING',
        value: true
      }, {
        name: 'CC_USE_REAL_TIME_JOINT_TEXTURE',
        value: true
      }];
      function getRelevantBuffers(outIndices, outBuffers, jointMaps, targetJoint) {
        for (var i = 0; i < jointMaps.length; i++) {
          var idxMap = jointMaps[i];
          var index = -1;
          for (var j = 0; j < idxMap.length; j++) {
            if (idxMap[j] === targetJoint) {
              index = j;
              break;
            }
          }
          if (index >= 0) {
            outBuffers.push(i);
            outIndices.push(index);
          }
        }
      }
      var v3_min = new Vec3();
      var v3_max = new Vec3();
      var v3_1$2 = new Vec3();
      var v3_2 = new Vec3();
      var m4_1$2 = new Mat4();
      var ab_1 = new AABB();
      var RealTimeJointTexture = function RealTimeJointTexture() {
        this._format = PixelFormat.RGBA32F;
        this._textures = [];
        this._buffers = [];
      };
      RealTimeJointTexture.WIDTH = 256;
      RealTimeJointTexture.HEIGHT = 3;
      var SkinningModel = function (_MorphModel) {
        _inheritsLoose(SkinningModel, _MorphModel);
        function SkinningModel() {
          var _this;
          _this = _MorphModel.call(this) || this;
          _this._buffers = [];
          _this._dataArray = [];
          _this._joints = [];
          _this._bufferIndices = null;
          _this._realTimeJointTexture = new RealTimeJointTexture();
          _this._realTimeTextureMode = false;
          _this.type = ModelType.SKINNING;
          return _this;
        }
        var _proto = SkinningModel.prototype;
        _proto.destroy = function destroy() {
          this.bindSkeleton();
          if (this._buffers.length) {
            for (var i = 0; i < this._buffers.length; i++) {
              this._buffers[i].destroy();
            }
            this._buffers.length = 0;
          }
          this._dataArray.length = 0;
          this._realTimeJointTexture._textures.forEach(function (tex) {
            tex.destroy();
          });
          this._realTimeJointTexture._textures.length = 0;
          this._realTimeJointTexture._buffers.length = 0;
          _MorphModel.prototype.destroy.call(this);
        };
        _proto.uploadAnimation = function uploadAnimation() {};
        _proto.bindSkeleton = function bindSkeleton(skeleton, skinningRoot, mesh) {
          if (skeleton === void 0) {
            skeleton = null;
          }
          if (skinningRoot === void 0) {
            skinningRoot = null;
          }
          if (mesh === void 0) {
            mesh = null;
          }
          for (var i = 0; i < this._joints.length; i++) {
            deleteTransform(this._joints[i].target);
          }
          this._bufferIndices = null;
          this._joints.length = 0;
          if (!skeleton || !skinningRoot || !mesh) {
            return;
          }
          this._realTimeTextureMode = false;
          if (UBOSkinning.JOINT_UNIFORM_CAPACITY < skeleton.joints.length) {
            this._realTimeTextureMode = true;
          }
          this.transform = skinningRoot;
          var boneSpaceBounds = mesh.getBoneSpaceBounds(skeleton);
          var jointMaps = mesh.struct.jointMaps;
          this._ensureEnoughBuffers(jointMaps && jointMaps.length || 1);
          this._bufferIndices = mesh.jointBufferIndices;
          this._initRealTimeJointTexture();
          for (var index = 0; index < skeleton.joints.length; index++) {
            var bound = boneSpaceBounds[index];
            var target = skinningRoot.getChildByPath(skeleton.joints[index]);
            if (!bound || !target) {
              continue;
            }
            var transform = getTransform(target, skinningRoot);
            var bindpose = skeleton.bindposes[index];
            var indices = [];
            var buffers = [];
            if (!jointMaps) {
              indices.push(index);
              buffers.push(0);
            } else {
              getRelevantBuffers(indices, buffers, jointMaps, index);
            }
            this._joints.push({
              indices: indices,
              buffers: buffers,
              bound: bound,
              target: target,
              bindpose: bindpose,
              transform: transform
            });
          }
        };
        _proto.updateTransform = function updateTransform(stamp) {
          var root = this.transform;
          if (root.hasChangedFlags || root.isTransformDirty()) {
            root.updateWorldTransform();
            this._localDataUpdated = true;
          }
          Vec3.set(v3_min, Infinity, Infinity, Infinity);
          Vec3.set(v3_max, -Infinity, -Infinity, -Infinity);
          for (var i = 0; i < this._joints.length; i++) {
            var _this$_joints$i = this._joints[i],
              bound = _this$_joints$i.bound,
              transform = _this$_joints$i.transform;
            var worldMatrix = getWorldMatrix(transform, stamp);
            AABB.transform(ab_1, bound, worldMatrix);
            ab_1.getBoundary(v3_1$2, v3_2);
            Vec3.min(v3_min, v3_min, v3_1$2);
            Vec3.max(v3_max, v3_max, v3_2);
          }
          var worldBounds = this._worldBounds;
          if (this._modelBounds && worldBounds) {
            AABB.fromPoints(this._modelBounds, v3_min, v3_max);
            this._modelBounds.transform(root._mat, root._pos, root._rot, root._scale, this._worldBounds);
          }
        };
        _proto.updateUBOs = function updateUBOs(stamp) {
          _MorphModel.prototype.updateUBOs.call(this, stamp);
          for (var i = 0; i < this._joints.length; i++) {
            var _this$_joints$i2 = this._joints[i],
              indices = _this$_joints$i2.indices,
              buffers = _this$_joints$i2.buffers,
              transform = _this$_joints$i2.transform,
              bindpose = _this$_joints$i2.bindpose;
            Mat4.multiply(m4_1$2, transform.world, bindpose);
            for (var b = 0; b < buffers.length; b++) {
              uploadJointData(this._dataArray[buffers[b]], indices[b] * 12, m4_1$2);
            }
          }
          if (this._realTimeTextureMode) {
            this._updateRealTimeJointTextureBuffer();
          } else {
            for (var _b = 0; _b < this._buffers.length; _b++) {
              this._buffers[_b].update(this._dataArray[_b]);
            }
          }
          return true;
        };
        _proto.initSubModel = function initSubModel(idx, subMeshData, mat) {
          var original = subMeshData.vertexBuffers;
          var iaInfo = subMeshData.iaInfo;
          iaInfo.vertexBuffers = subMeshData.jointMappedBuffers;
          _MorphModel.prototype.initSubModel.call(this, idx, subMeshData, mat);
          iaInfo.vertexBuffers = original;
        };
        _proto.getMacroPatches = function getMacroPatches(subModelIndex) {
          var superMacroPatches = _MorphModel.prototype.getMacroPatches.call(this, subModelIndex);
          var myPatches = uniformPatches;
          if (this._realTimeTextureMode) {
            myPatches = texturePatches;
          }
          if (superMacroPatches) {
            return myPatches.concat(superMacroPatches);
          }
          return myPatches;
        };
        _proto._updateLocalDescriptors = function _updateLocalDescriptors(submodelIdx, descriptorSet) {
          _MorphModel.prototype._updateLocalDescriptors.call(this, submodelIdx, descriptorSet);
          var idx = this._bufferIndices[submodelIdx];
          if (this._realTimeTextureMode) {
            this._bindRealTimeJointTexture(idx, descriptorSet);
          } else {
            var buffer = this._buffers[idx];
            if (buffer) {
              descriptorSet.bindBuffer(UBOSkinning.BINDING, buffer);
            }
          }
        };
        _proto._updateInstancedAttributes = function _updateInstancedAttributes(attributes, subModel) {
          var pass = subModel.passes[0];
          if (pass.batchingScheme !== BatchingSchemes.NONE) {
            warnID(3936, this.node.getPathInHierarchy());
          }
          _MorphModel.prototype._updateInstancedAttributes.call(this, attributes, subModel);
        };
        _proto._ensureEnoughBuffers = function _ensureEnoughBuffers(count) {
          if (this._buffers.length) {
            for (var i = 0; i < this._buffers.length; i++) {
              this._buffers[i].destroy();
            }
            this._buffers.length = 0;
          }
          if (this._dataArray.length) this._dataArray.length = 0;
          if (!this._realTimeTextureMode) {
            for (var _i = 0; _i < count; _i++) {
              this._buffers[_i] = this._device.createBuffer(new BufferInfo(BufferUsageBit.UNIFORM | BufferUsageBit.TRANSFER_DST, MemoryUsageBit.HOST | MemoryUsageBit.DEVICE, UBOSkinning.SIZE, UBOSkinning.SIZE));
              var maxJoints = UBOSkinning.JOINT_UNIFORM_CAPACITY;
              this._dataArray[_i] = new Float32Array(12 * maxJoints);
            }
          } else {
            for (var _i2 = 0; _i2 < count; _i2++) {
              var _maxJoints = RealTimeJointTexture.WIDTH;
              this._dataArray[_i2] = new Float32Array(12 * _maxJoints);
            }
          }
        };
        _proto._initRealTimeJointTexture = function _initRealTimeJointTexture() {
          if (this._realTimeJointTexture._textures.length) {
            this._realTimeJointTexture._textures.forEach(function (tex) {
              tex.destroy();
            });
            this._realTimeJointTexture._textures.length = 0;
          }
          this._realTimeJointTexture._buffers.length = 0;
          if (!this._realTimeTextureMode) return;
          var gfxDevice = director.root.device;
          var width = RealTimeJointTexture.WIDTH;
          var height = RealTimeJointTexture.HEIGHT;
          var hasFeatureFloatTexture = gfxDevice.getFormatFeatures(Format.RGBA32F) & FormatFeatureBit.SAMPLED_TEXTURE;
          if (hasFeatureFloatTexture === 0) {
            this._realTimeJointTexture._format = PixelFormat.RGBA8888;
            width = 4 * RealTimeJointTexture.WIDTH;
          }
          var textures = this._realTimeJointTexture._textures;
          var buffers = this._realTimeJointTexture._buffers;
          var pixelFormat = this._realTimeJointTexture._format;
          for (var i = 0; i < this._dataArray.length; i++) {
            buffers[i] = new Float32Array(4 * RealTimeJointTexture.HEIGHT * RealTimeJointTexture.WIDTH);
            var arrayBuffer = buffers[i];
            var updateView = pixelFormat === PixelFormat.RGBA32F ? arrayBuffer : new Uint8Array(arrayBuffer.buffer);
            var image = new ImageAsset({
              width: width,
              height: height,
              _data: updateView,
              _compressed: false,
              format: pixelFormat
            });
            var texture = new Texture2D();
            texture.setFilters(Texture2D.Filter.NEAREST, Texture2D.Filter.NEAREST);
            texture.setMipFilter(Texture2D.Filter.NONE);
            texture.setWrapMode(Texture2D.WrapMode.CLAMP_TO_EDGE, Texture2D.WrapMode.CLAMP_TO_EDGE, Texture2D.WrapMode.CLAMP_TO_EDGE);
            texture.image = image;
            textures[i] = texture;
          }
        };
        _proto._bindRealTimeJointTexture = function _bindRealTimeJointTexture(idx, descriptorSet) {
          if (!this._realTimeTextureMode) return;
          var jointTexture = this._realTimeJointTexture._textures[idx];
          if (jointTexture) {
            var gfxTexture = jointTexture.getGFXTexture();
            var sampler = jointTexture.getGFXSampler();
            descriptorSet.bindTexture(UNIFORM_REALTIME_JOINT_TEXTURE_BINDING, gfxTexture);
            descriptorSet.bindSampler(UNIFORM_REALTIME_JOINT_TEXTURE_BINDING, sampler);
          }
        };
        _proto._updateRealTimeJointTextureBuffer = function _updateRealTimeJointTextureBuffer() {
          if (!this._realTimeTextureMode) return;
          var textures = this._realTimeJointTexture._textures;
          var buffers = this._realTimeJointTexture._buffers;
          for (var idx = 0; idx < textures.length; idx++) {
            var arrayBuffer = buffers[idx];
            var src = this._dataArray[idx];
            var count = src.length / 12;
            var idxSrc = 0;
            var idxDst = 0;
            for (var i = 0; i < count; i++) {
              idxDst = 4 * i;
              arrayBuffer[idxDst++] = src[idxSrc++];
              arrayBuffer[idxDst++] = src[idxSrc++];
              arrayBuffer[idxDst++] = src[idxSrc++];
              arrayBuffer[idxDst++] = src[idxSrc++];
              idxDst = 4 * (i + RealTimeJointTexture.WIDTH);
              arrayBuffer[idxDst++] = src[idxSrc++];
              arrayBuffer[idxDst++] = src[idxSrc++];
              arrayBuffer[idxDst++] = src[idxSrc++];
              arrayBuffer[idxDst++] = src[idxSrc++];
              idxDst = 4 * (i + 2 * RealTimeJointTexture.WIDTH);
              arrayBuffer[idxDst++] = src[idxSrc++];
              arrayBuffer[idxDst++] = src[idxSrc++];
              arrayBuffer[idxDst++] = src[idxSrc++];
              arrayBuffer[idxDst++] = src[idxSrc++];
            }
            var pixelFormat = this._realTimeJointTexture._format;
            var updateView = pixelFormat === PixelFormat.RGBA32F ? arrayBuffer : new Uint8Array(arrayBuffer.buffer);
            textures[idx].uploadData(updateView);
          }
        };
        return SkinningModel;
      }(MorphModel);

      var myPatches = [{
        name: 'CC_USE_SKINNING',
        value: true
      }, {
        name: 'CC_USE_BAKED_ANIMATION',
        value: true
      }];
      var BakedSkinningModel = function (_MorphModel) {
        _inheritsLoose(BakedSkinningModel, _MorphModel);
        function BakedSkinningModel() {
          var _this;
          _this = _MorphModel.call(this) || this;
          _this.uploadedAnim = undefined;
          _this._jointsMedium = void 0;
          _this._skeleton = null;
          _this._mesh = null;
          _this._dataPoolManager = void 0;
          _this._instAnimInfoIdx = -1;
          _this.type = ModelType.BAKED_SKINNING;
          _this._dataPoolManager = legacyCC.director.root.dataPoolManager;
          var jointTextureInfo = new Float32Array(4);
          var animInfo = _this._dataPoolManager.jointAnimationInfo.getData();
          _this._jointsMedium = {
            buffer: null,
            jointTextureInfo: jointTextureInfo,
            animInfo: animInfo,
            texture: null,
            boundsInfo: null
          };
          return _this;
        }
        var _proto = BakedSkinningModel.prototype;
        _proto.destroy = function destroy() {
          this.uploadedAnim = undefined;
          this._jointsMedium.boundsInfo = null;
          if (this._jointsMedium.buffer) {
            this._jointsMedium.buffer.destroy();
            this._jointsMedium.buffer = null;
          }
          this._applyJointTexture();
          _MorphModel.prototype.destroy.call(this);
        };
        _proto.bindSkeleton = function bindSkeleton(skeleton, skinningRoot, mesh) {
          if (skeleton === void 0) {
            skeleton = null;
          }
          if (skinningRoot === void 0) {
            skinningRoot = null;
          }
          if (mesh === void 0) {
            mesh = null;
          }
          this._skeleton = skeleton;
          this._mesh = mesh;
          if (!skeleton || !skinningRoot || !mesh) {
            return;
          }
          this.transform = skinningRoot;
          var resMgr = this._dataPoolManager;
          this._jointsMedium.animInfo = resMgr.jointAnimationInfo.getData(skinningRoot.uuid);
          if (!this._jointsMedium.buffer) {
            this._jointsMedium.buffer = this._device.createBuffer(new BufferInfo(BufferUsageBit.UNIFORM | BufferUsageBit.TRANSFER_DST, MemoryUsageBit.DEVICE, UBOSkinningTexture.SIZE, UBOSkinningTexture.SIZE));
          }
        };
        _proto.updateTransform = function updateTransform(stamp) {
          _MorphModel.prototype.updateTransform.call(this, stamp);
          if (!this.uploadedAnim) {
            return;
          }
          var _this$_jointsMedium = this._jointsMedium,
            animInfo = _this$_jointsMedium.animInfo,
            boundsInfo = _this$_jointsMedium.boundsInfo;
          var skelBound = boundsInfo[animInfo.data[0]];
          var worldBounds = this._worldBounds;
          if (worldBounds && skelBound) {
            var node = this.transform;
            skelBound.transform(node._mat, node._pos, node._rot, node._scale, worldBounds);
          }
        };
        _proto.updateUBOs = function updateUBOs(stamp) {
          _MorphModel.prototype.updateUBOs.call(this, stamp);
          var info = this._jointsMedium.animInfo;
          var hasNonInstancingPass = false;
          var idx = this._instAnimInfoIdx;
          for (var i = 0; i < this._subModels.length; i++) {
            var subModel = this._subModels[i];
            if (idx >= 0) {
              var view = subModel.instancedAttributeBlock.views[idx];
              view[0] = info.data[0];
            } else {
              hasNonInstancingPass = true;
            }
          }
          if (hasNonInstancingPass && info.dirty) {
            info.buffer.update(info.data);
            info.dirty = false;
          }
          return true;
        };
        _proto.getMacroPatches = function getMacroPatches(subModelIndex) {
          var patches = _MorphModel.prototype.getMacroPatches.call(this, subModelIndex);
          return patches ? patches.concat(myPatches) : myPatches;
        };
        _proto.uploadAnimation = function uploadAnimation(anim) {
          if (!this._skeleton || !this._mesh || this.uploadedAnim === anim) {
            return;
          }
          this.uploadedAnim = anim;
          var resMgr = this._dataPoolManager;
          var texture = null;
          if (anim) {
            texture = resMgr.jointTexturePool.getSequencePoseTexture(this._skeleton, anim, this._mesh, this.transform);
            this._jointsMedium.boundsInfo = texture && texture.bounds.get(this._mesh.hash);
            this._modelBounds = null;
          } else {
            texture = resMgr.jointTexturePool.getDefaultPoseTexture(this._skeleton, this._mesh, this.transform);
            this._jointsMedium.boundsInfo = null;
            this._modelBounds = texture && texture.bounds.get(this._mesh.hash)[0];
          }
          this._applyJointTexture(texture);
        };
        _proto._applyJointTexture = function _applyJointTexture(texture) {
          if (texture === void 0) {
            texture = null;
          }
          var oldTex = this._jointsMedium.texture;
          if (oldTex && oldTex !== texture) {
            this._dataPoolManager.jointTexturePool.releaseHandle(oldTex);
          }
          this._jointsMedium.texture = texture;
          if (!texture) {
            return;
          }
          var _this$_jointsMedium2 = this._jointsMedium,
            buffer = _this$_jointsMedium2.buffer,
            jointTextureInfo = _this$_jointsMedium2.jointTextureInfo;
          jointTextureInfo[0] = texture.handle.texture.width;
          jointTextureInfo[1] = this._skeleton.joints.length;
          jointTextureInfo[2] = texture.pixelOffset + 0.1;
          jointTextureInfo[3] = 1 / jointTextureInfo[0];
          this.updateInstancedJointTextureInfo();
          if (buffer) {
            buffer.update(jointTextureInfo);
          }
          var tex = texture.handle.texture;
          for (var i = 0; i < this._subModels.length; ++i) {
            var descriptorSet = this._subModels[i].descriptorSet;
            descriptorSet.bindTexture(UNIFORM_JOINT_TEXTURE_BINDING, tex);
          }
        };
        _proto._updateLocalDescriptors = function _updateLocalDescriptors(submodelIdx, descriptorSet) {
          _MorphModel.prototype._updateLocalDescriptors.call(this, submodelIdx, descriptorSet);
          var _this$_jointsMedium3 = this._jointsMedium,
            buffer = _this$_jointsMedium3.buffer,
            texture = _this$_jointsMedium3.texture,
            animInfo = _this$_jointsMedium3.animInfo;
          descriptorSet.bindBuffer(UBOSkinningTexture.BINDING, buffer);
          descriptorSet.bindBuffer(UBOSkinningAnimation.BINDING, animInfo.buffer);
          if (texture) {
            var sampler = this._device.getSampler(jointTextureSamplerInfo);
            descriptorSet.bindTexture(UNIFORM_JOINT_TEXTURE_BINDING, texture.handle.texture);
            descriptorSet.bindSampler(UNIFORM_JOINT_TEXTURE_BINDING, sampler);
          }
        };
        _proto._updateInstancedAttributes = function _updateInstancedAttributes(attributes, subModel) {
          _MorphModel.prototype._updateInstancedAttributes.call(this, attributes, subModel);
          this._instAnimInfoIdx = subModel.getInstancedAttributeIndex(INST_JOINT_ANIM_INFO);
          this.updateInstancedJointTextureInfo();
        };
        _proto.updateInstancedJointTextureInfo = function updateInstancedJointTextureInfo() {
          var _this$_jointsMedium4 = this._jointsMedium,
            jointTextureInfo = _this$_jointsMedium4.jointTextureInfo,
            animInfo = _this$_jointsMedium4.animInfo;
          var idx = this._instAnimInfoIdx;
          for (var i = 0; i < this._subModels.length; i++) {
            var subModel = this._subModels[i];
            var views = subModel.instancedAttributeBlock.views;
            if (idx >= 0 && views.length > 0) {
              var view = views[idx];
              view[0] = animInfo.data[0];
              view[1] = jointTextureInfo[1];
              view[2] = jointTextureInfo[2];
            }
          }
        };
        return BakedSkinningModel;
      }(MorphModel);

      var _dec$1S, _dec2$1o, _dec3$Z, _dec4$K, _dec5$D, _dec6$n, _class$1R, _class2$1F, _initializer$1w, _initializer2$1c;
      var SkinnedMeshRenderer = exports('aa', (_dec$1S = ccclass$n('cc.SkinnedMeshRenderer'), _dec2$1o = executionOrder$1(100), _dec3$Z = type$7(Skeleton), _dec4$K = type$7(Node$1), _dec5$D = type$7(Skeleton), _dec6$n = type$7(Node$1), _dec$1S(_class$1R = _dec2$1o(_class$1R = (_class2$1F = function (_MeshRenderer) {
        _inheritsLoose(SkinnedMeshRenderer, _MeshRenderer);
        function SkinnedMeshRenderer() {
          var _this;
          _this = _MeshRenderer.call(this) || this;
          _this._skeleton = _initializer$1w && _initializer$1w();
          _this._skinningRoot = _initializer2$1c && _initializer2$1c();
          _this._clip = null;
          _this.associatedAnimation = null;
          _this._modelType = BakedSkinningModel;
          return _this;
        }
        var _proto = SkinnedMeshRenderer.prototype;
        _proto.onLoad = function onLoad() {
          _MeshRenderer.prototype.onLoad.call(this);
          this._tryBindAnimation();
        };
        _proto.onDestroy = function onDestroy() {
          if (this.associatedAnimation) {
            this.associatedAnimation.notifySkinnedMeshRemoved(this);
            assertIsTrue(this.associatedAnimation === null);
          }
          _MeshRenderer.prototype.onDestroy.call(this);
        };
        _proto.uploadAnimation = function uploadAnimation(clip) {
          this._clip = clip;
          if (this.model && this.model.uploadAnimation) {
            this.model.uploadAnimation(clip);
          }
        };
        _proto.setUseBakedAnimation = function setUseBakedAnimation(val, force) {
          if (val === void 0) {
            val = true;
          }
          if (force === void 0) {
            force = false;
          }
          var modelType = val ? BakedSkinningModel : SkinningModel;
          if (!force && this._modelType === modelType) {
            return;
          }
          this._modelType = modelType;
          if (this._model) {
            legacyCC.director.root.destroyModel(this._model);
            this._model = null;
            this._models.length = 0;
            this._updateModels();
            this._updateCastShadow();
            this._updateReceiveShadow();
            this._updateUseLightProbe();
            if (this.enabledInHierarchy) {
              this._attachToScene();
            }
          }
        };
        _proto.setSharedMaterial = function setSharedMaterial(material, index) {
          _MeshRenderer.prototype.setSharedMaterial.call(this, material, index);
          if (this._modelType === SkinningModel) {
            this.getMaterialInstance(index);
          }
        };
        _proto._updateModelParams = function _updateModelParams() {
          this._update();
          _MeshRenderer.prototype._updateModelParams.call(this);
        };
        _proto._tryBindAnimation = function _tryBindAnimation() {
          var skinningRoot = this._skinningRoot;
          if (!skinningRoot) {
            return;
          }
          var skinningRootIsParent = false;
          for (var current = this.node; current; current = current.parent) {
            if (current === skinningRoot) {
              skinningRootIsParent = true;
              break;
            }
          }
          if (!skinningRootIsParent) {
            return;
          }
          var animation = skinningRoot.getComponent('cc.SkeletalAnimation');
          if (animation && animation.enabledInHierarchy) {
            animation.notifySkinnedMeshAdded(this);
          } else {
            this.setUseBakedAnimation(false);
          }
        };
        _proto._update = function _update() {
          if (this.model) {
            this.model.bindSkeleton(this._skeleton, this._skinningRoot, this._mesh);
            if (this.model.uploadAnimation) {
              this.model.uploadAnimation(this._clip);
            }
          }
        };
        _createClass(SkinnedMeshRenderer, [{
          key: "skeleton",
          get: function get() {
            return this._skeleton;
          },
          set: function set(val) {
            if (val === this._skeleton) {
              return;
            }
            this._skeleton = val;
            this._update();
          }
        }, {
          key: "skinningRoot",
          get: function get() {
            return this._skinningRoot;
          },
          set: function set(value) {
            if (value === this._skinningRoot) {
              return;
            }
            this._skinningRoot = value;
            this._tryBindAnimation();
            this._update();
          }
        }, {
          key: "model",
          get: function get() {
            return this._model;
          }
        }]);
        return SkinnedMeshRenderer;
      }(MeshRenderer), (_initializer$1w = applyDecoratedInitializer(_class2$1F.prototype, "_skeleton", [_dec3$Z], function () {
        return null;
      }), _initializer2$1c = applyDecoratedInitializer(_class2$1F.prototype, "_skinningRoot", [_dec4$K], function () {
        return null;
      }), _applyDecoratedDescriptor(_class2$1F.prototype, "skeleton", [_dec5$D], Object.getOwnPropertyDescriptor(_class2$1F.prototype, "skeleton"), _class2$1F.prototype), _applyDecoratedDescriptor(_class2$1F.prototype, "skinningRoot", [_dec6$n], Object.getOwnPropertyDescriptor(_class2$1F.prototype, "skinningRoot"), _class2$1F.prototype)), _class2$1F)) || _class$1R) || _class$1R));

      var _dec$1R, _dec2$1n, _dec3$Y, _dec4$J, _dec5$C, _class$1Q, _class2$1E, _initializer$1v, _initializer2$1b, _initializer3$M, _initializer4$B, _initializer5$q, _initializer6$j, _dec6$m, _dec7$h, _dec8$c, _dec9$a, _class4$o, _class5$q, _initializer7$f, _initializer8$e, _initializer9$d;
      var repeat$1 = function repeat(n) {
        return n - Math.floor(n);
      };
      var batch_id = new Attribute(AttributeName.ATTR_BATCH_ID, Format.R32F);
      var batch_uv = new Attribute(AttributeName.ATTR_BATCH_UV, Format.RG32F);
      var batch_extras_size = FormatInfos[batch_id.format].size + FormatInfos[batch_uv.format].size;
      var SkinnedMeshUnit = exports('ac', (_dec$1R = ccclass$n('cc.SkinnedMeshUnit'), _dec2$1n = type$7(Mesh), _dec3$Y = type$7(Skeleton), _dec4$J = type$7(Material), _dec5$C = type$7(SkinnedMeshRenderer), _dec$1R(_class$1Q = (_class2$1E = function () {
        function SkinnedMeshUnit() {
          this.mesh = _initializer$1v && _initializer$1v();
          this.skeleton = _initializer2$1b && _initializer2$1b();
          this.material = _initializer3$M && _initializer3$M();
          this._localTransform = _initializer4$B && _initializer4$B();
          this._offset = _initializer5$q && _initializer5$q();
          this._size = _initializer6$j && _initializer6$j();
        }
        _createClass(SkinnedMeshUnit, [{
          key: "offset",
          get: function get() {
            return this._offset;
          },
          set: function set(offset) {
            Vec2.copy(this._offset, offset);
          }
        }, {
          key: "size",
          get: function get() {
            return this._size;
          },
          set: function set(size) {
            Vec2.copy(this._size, size);
          }
        }, {
          key: "copyFrom",
          get: function get() {
            return null;
          },
          set: function set(comp) {
            if (!comp) {
              return;
            }
            this.mesh = comp.mesh;
            this.skeleton = comp.skeleton;
            this.material = comp.getSharedMaterial(0);
            if (comp.skinningRoot) {
              getWorldTransformUntilRoot(comp.node, comp.skinningRoot, this._localTransform);
            }
          }
        }]);
        return SkinnedMeshUnit;
      }(), (_initializer$1v = applyDecoratedInitializer(_class2$1E.prototype, "mesh", [_dec2$1n], function () {
        return null;
      }), _initializer2$1b = applyDecoratedInitializer(_class2$1E.prototype, "skeleton", [_dec3$Y], function () {
        return null;
      }), _initializer3$M = applyDecoratedInitializer(_class2$1E.prototype, "material", [_dec4$J], function () {
        return null;
      }), _initializer4$B = applyDecoratedInitializer(_class2$1E.prototype, "_localTransform", [serializable$j], function () {
        return new Mat4();
      }), _initializer5$q = applyDecoratedInitializer(_class2$1E.prototype, "_offset", [serializable$j], function () {
        return new Vec2(0, 0);
      }), _initializer6$j = applyDecoratedInitializer(_class2$1E.prototype, "_size", [serializable$j], function () {
        return new Vec2(1, 1);
      }), _applyDecoratedDescriptor(_class2$1E.prototype, "copyFrom", [_dec5$C], Object.getOwnPropertyDescriptor(_class2$1E.prototype, "copyFrom"), _class2$1E.prototype)), _class2$1E)) || _class$1Q));
      var m4_local = new Mat4();
      new Mat4();
      var v3_1$1 = new Vec3();
      var SkinnedMeshBatchRenderer = exports('ab', (_dec6$m = ccclass$n('cc.SkinnedMeshBatchRenderer'), _dec7$h = executionOrder$1(100), _dec8$c = type$7([CCString]), _dec9$a = type$7([SkinnedMeshUnit]), _dec6$m(_class4$o = _dec7$h(_class4$o = (_class5$q = function (_SkinnedMeshRenderer) {
        _inheritsLoose(SkinnedMeshBatchRenderer, _SkinnedMeshRenderer);
        function SkinnedMeshBatchRenderer() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _SkinnedMeshRenderer.call.apply(_SkinnedMeshRenderer, [this].concat(args)) || this;
          _this.atlasSize = _initializer7$f && _initializer7$f();
          _this.batchableTextureNames = _initializer8$e && _initializer8$e();
          _this.units = _initializer9$d && _initializer9$d();
          _this._textures = {};
          _this._batchMaterial = null;
          return _this;
        }
        var _proto = SkinnedMeshBatchRenderer.prototype;
        _proto.onLoad = function onLoad() {
          _SkinnedMeshRenderer.prototype.onLoad.call(this);
          this.cook();
        };
        _proto.onDestroy = function onDestroy() {
          for (var tex in this._textures) {
            this._textures[tex].destroy();
          }
          this._textures = {};
          if (this._mesh) {
            this._mesh.destroy();
            this._mesh = null;
          }
          _SkinnedMeshRenderer.prototype.onDestroy.call(this);
        };
        _proto._onMaterialModified = function _onMaterialModified(idx, material) {
          this.cookMaterials();
          _SkinnedMeshRenderer.prototype._onMaterialModified.call(this, idx, this.getMaterialInstance(idx));
        };
        _proto.cook = function cook() {
          this.cookMaterials();
          this.cookSkeletons();
          this.cookMeshes();
        };
        _proto.cookMaterials = function cookMaterials() {
          var _this2 = this;
          if (!this._batchMaterial) {
            this._batchMaterial = this.getSharedMaterial(0);
          }
          var mat = this.getMaterialInstance(0);
          if (!mat || !this._batchMaterial || !this._batchMaterial.effectAsset) {
            console.warn('incomplete batch material!');
            return;
          }
          mat.copy(this._batchMaterial);
          this.resizeAtlases();
          var tech = mat.effectAsset.techniques[mat.technique];
          var _loop = function _loop(i) {
            var pass = tech.passes[i];
            if (!pass.properties) {
              return 1;
            }
            var _loop2 = function _loop2(prop) {
              if (pass.properties[prop].type >= Type$1.SAMPLER1D) {
                var tex = null;
                if (_this2.batchableTextureNames.find(function (n) {
                  return n === prop;
                })) {
                  tex = _this2._textures[prop];
                  if (!tex) {
                    tex = _this2.createTexture(prop);
                  }
                  _this2.cookTextures(tex, prop, i);
                } else {
                  _this2.units.some(function (u) {
                    return tex = u.material && u.material.getProperty(prop, i);
                  });
                }
                if (tex) {
                  mat.setProperty(prop, tex, i);
                }
              } else {
                var value = [];
                for (var u = 0; u < _this2.units.length; u++) {
                  var unit = _this2.units[u];
                  if (!unit.material) {
                    continue;
                  }
                  value.push(unit.material.getProperty(prop.slice(0, -3), i));
                }
                mat.setProperty(prop, value, i);
              }
            };
            for (var prop in pass.properties) {
              _loop2(prop);
            }
          };
          for (var i = 0; i < tech.passes.length; i++) {
            if (_loop(i)) continue;
          }
        };
        _proto.cookSkeletons = function cookSkeletons() {
          if (!this._skinningRoot) {
            console.warn('no skinning root specified!');
            return;
          }
          var joints = [];
          var bindposes = [];
          for (var u = 0; u < this.units.length; u++) {
            var unit = this.units[u];
            if (!unit || !unit.skeleton) {
              continue;
            }
            var partial = unit.skeleton;
            Mat4.invert(m4_local, unit._localTransform);
            var _loop3 = function _loop3() {
              var path = partial.joints[i];
              var idx = joints.findIndex(function (p) {
                return p === path;
              });
              if (idx >= 0) {
                return 1;
              }
              joints.push(path);
              bindposes.push(Mat4.multiply(new Mat4(), partial.bindposes[i] || Mat4.IDENTITY, m4_local));
            };
            for (var i = 0; i < partial.joints.length; i++) {
              if (_loop3()) continue;
            }
          }
          var idxMap = Array.from(Array(joints.length).keys()).sort(function (a, b) {
            if (joints[a] > joints[b]) {
              return 1;
            }
            if (joints[a] < joints[b]) {
              return -1;
            }
            return 0;
          });
          var skeleton = new Skeleton();
          skeleton.joints = joints.map(function (_, idx, arr) {
            return arr[idxMap[idx]];
          });
          skeleton.bindposes = bindposes.map(function (_, idx, arr) {
            return arr[idxMap[idx]];
          });
          if (this._skeleton) {
            this._skeleton.destroy();
          }
          this.skeleton = skeleton;
        };
        _proto.cookMeshes = function cookMeshes() {
          var _this4 = this;
          var isValid = false;
          for (var u = 0; u < this.units.length; u++) {
            var unit = this.units[u];
            if (unit.mesh) {
              isValid = true;
              break;
            }
          }
          if (!isValid || !this._skinningRoot) {
            return;
          }
          if (this._mesh) {
            this._mesh.destroyRenderingMesh();
          } else {
            this._mesh = new Mesh();
          }
          var posOffset = 0;
          var posFormat = Format.UNKNOWN;
          var normalOffset = 0;
          var normalFormat = Format.UNKNOWN;
          var tangentOffset = 0;
          var tangentFormat = Format.UNKNOWN;
          var uvOffset = 0;
          var uvFormat = Format.UNKNOWN;
          var jointOffset = 0;
          var jointFormat = Format.UNKNOWN;
          var jointIndexMap = new Array(this.units.length);
          var unitLen = this.units.length;
          for (var i = 0; i < unitLen; i++) {
            var _unit = this.units[i];
            if (!_unit || !_unit.skeleton) {
              continue;
            }
            jointIndexMap[i] = _unit.skeleton.joints.map(function (j) {
              return _this4._skeleton.joints.findIndex(function (ref) {
                return j === ref;
              });
            });
          }
          var _loop4 = function _loop4() {
            var unit = _this4.units[_i];
            if (!unit || !unit.mesh || !unit.mesh.data) {
              return 1;
            }
            var newMesh = _this4._createUnitMesh(_i, unit.mesh);
            var dataView = new DataView(newMesh.data.buffer);
            Mat4.invert(m4_local, unit._localTransform);
            Mat4.transpose(m4_local, m4_local);
            var offset = unit.offset;
            var size = unit.size;
            var _loop5 = function _loop5() {
              var bundle = newMesh.struct.vertexBundles[b];
              posOffset = bundle.view.offset;
              posFormat = Format.UNKNOWN;
              for (var a = 0; a < bundle.attributes.length; a++) {
                var attr = bundle.attributes[a];
                if (attr.name === AttributeName.ATTR_POSITION) {
                  posFormat = attr.format;
                  break;
                }
                posOffset += FormatInfos[attr.format].size;
              }
              if (posFormat) {
                var pos = readBuffer(dataView, posFormat, posOffset, bundle.view.length, bundle.view.stride);
                for (var j = 0; j < pos.length; j += 3) {
                  Vec3.fromArray(v3_1$1, pos, j);
                  Vec3.transformMat4(v3_1$1, v3_1$1, unit._localTransform);
                  Vec3.toArray(pos, v3_1$1, j);
                }
                writeBuffer(dataView, pos, posFormat, posOffset, bundle.view.stride);
              }
              normalOffset = bundle.view.offset;
              normalFormat = Format.UNKNOWN;
              for (var _a = 0; _a < bundle.attributes.length; _a++) {
                var _attr = bundle.attributes[_a];
                if (_attr.name === AttributeName.ATTR_NORMAL) {
                  normalFormat = _attr.format;
                  break;
                }
                normalOffset += FormatInfos[_attr.format].size;
              }
              if (normalFormat) {
                var normal = readBuffer(dataView, normalFormat, normalOffset, bundle.view.length, bundle.view.stride);
                for (var _j = 0; _j < normal.length; _j += 3) {
                  Vec3.fromArray(v3_1$1, normal, _j);
                  Vec3.transformMat4Normal(v3_1$1, v3_1$1, m4_local);
                  Vec3.toArray(normal, v3_1$1, _j);
                }
                writeBuffer(dataView, normal, normalFormat, normalOffset, bundle.view.stride);
              }
              tangentOffset = bundle.view.offset;
              tangentFormat = Format.UNKNOWN;
              for (var _a2 = 0; _a2 < bundle.attributes.length; _a2++) {
                var _attr2 = bundle.attributes[_a2];
                if (_attr2.name === AttributeName.ATTR_TANGENT) {
                  tangentFormat = _attr2.format;
                  break;
                }
                tangentOffset += FormatInfos[_attr2.format].size;
              }
              if (tangentFormat) {
                var tangent = readBuffer(dataView, tangentFormat, tangentOffset, bundle.view.length, bundle.view.stride);
                for (var _j2 = 0; _j2 < tangent.length; _j2 += 3) {
                  Vec3.fromArray(v3_1$1, tangent, _j2);
                  Vec3.transformMat4Normal(v3_1$1, v3_1$1, m4_local);
                  Vec3.toArray(tangent, v3_1$1, _j2);
                }
                writeBuffer(dataView, tangent, tangentFormat, tangentOffset, bundle.view.stride);
              }
              uvOffset = bundle.view.offset;
              uvFormat = Format.UNKNOWN;
              for (var _a3 = 0; _a3 < bundle.attributes.length; _a3++) {
                var _attr3 = bundle.attributes[_a3];
                if (_attr3.name === AttributeName.ATTR_BATCH_UV) {
                  uvFormat = _attr3.format;
                  break;
                }
                uvOffset += FormatInfos[_attr3.format].size;
              }
              if (uvFormat) {
                mapBuffer(dataView, function (cur, idx) {
                  cur = repeat$1(cur);
                  var comp = idx === 0 ? 'x' : 'y';
                  return cur * size[comp] + offset[comp];
                }, uvFormat, uvOffset, bundle.view.length, bundle.view.stride, dataView);
              }
              var idxMap = jointIndexMap[_i];
              if (!idxMap) {
                return 1;
              }
              jointOffset = bundle.view.offset;
              jointFormat = Format.UNKNOWN;
              for (var _a4 = 0; _a4 < bundle.attributes.length; _a4++) {
                var _attr4 = bundle.attributes[_a4];
                if (_attr4.name === AttributeName.ATTR_JOINTS) {
                  jointFormat = _attr4.format;
                  break;
                }
                jointOffset += FormatInfos[_attr4.format].size;
              }
              if (jointFormat) {
                mapBuffer(dataView, function (cur) {
                  return idxMap[cur];
                }, jointFormat, jointOffset, bundle.view.length, bundle.view.stride, dataView);
              }
            };
            for (var b = 0; b < newMesh.struct.vertexBundles.length; b++) {
              if (_loop5()) continue;
            }
            _this4._mesh.merge(newMesh);
          };
          for (var _i = 0; _i < unitLen; _i++) {
            if (_loop4()) continue;
          }
          this._onMeshChanged(this._mesh);
          this._updateModels();
        };
        _proto.cookTextures = function cookTextures(target, prop, passIdx) {
          var texImages = [];
          var texImageRegions = [];
          var texBuffers = [];
          var texBufferRegions = [];
          for (var u = 0; u < this.units.length; u++) {
            var unit = this.units[u];
            if (!unit.material) {
              continue;
            }
            var partial = unit.material.getProperty(prop, passIdx);
            if (partial && partial.image && partial.image.data) {
              var region = new BufferTextureCopy();
              region.texOffset.x = unit.offset.x * this.atlasSize;
              region.texOffset.y = unit.offset.y * this.atlasSize;
              region.texExtent.width = unit.size.x * this.atlasSize;
              region.texExtent.height = unit.size.y * this.atlasSize;
              var data = partial.image.data;
              if (!ArrayBuffer.isView(data)) {
                texImages.push(data);
                texImageRegions.push(region);
              } else {
                texBuffers.push(data);
                texBufferRegions.push(region);
              }
            }
          }
          var gfxTex = target.getGFXTexture();
          var _ref = legacyCC.director.root,
            device = _ref.device;
          if (texBuffers.length > 0) {
            device.copyBuffersToTexture(texBuffers, gfxTex, texBufferRegions);
          }
          if (texImages.length > 0) {
            device.copyTexImagesToTexture(texImages, gfxTex, texImageRegions);
          }
        };
        _proto.createTexture = function createTexture(prop) {
          var tex = new Texture2D();
          tex.setFilters(Filter.LINEAR, Filter.LINEAR);
          tex.setMipFilter(Filter.NEAREST);
          tex.reset({
            width: this.atlasSize,
            height: this.atlasSize,
            format: PixelFormat.RGBA8888
          });
          this._textures[prop] = tex;
          return tex;
        };
        _proto.resizeAtlases = function resizeAtlases() {
          for (var prop in this._textures) {
            var tex = this._textures[prop];
            tex.reset({
              width: this.atlasSize,
              height: this.atlasSize,
              format: PixelFormat.RGBA8888
            });
          }
        };
        _proto._createUnitMesh = function _createUnitMesh(unitIdx, mesh) {
          var newMeshStruct = JSON.parse(JSON.stringify(mesh.struct));
          var modifiedBundles = {};
          for (var p = 0; p < mesh.struct.primitives.length; p++) {
            var primitive = mesh.struct.primitives[p];
            var uvOffset = 0;
            var uvFormat = Format.UNKNOWN;
            var bundleIdx = 0;
            for (; bundleIdx < primitive.vertexBundelIndices.length; bundleIdx++) {
              var bundle = mesh.struct.vertexBundles[primitive.vertexBundelIndices[bundleIdx]];
              uvOffset = bundle.view.offset;
              uvFormat = Format.UNKNOWN;
              for (var a = 0; a < bundle.attributes.length; a++) {
                var attr = bundle.attributes[a];
                if (attr.name === AttributeName.ATTR_TEX_COORD) {
                  uvFormat = attr.format;
                  break;
                }
                uvOffset += FormatInfos[attr.format].size;
              }
              if (uvFormat) {
                break;
              }
            }
            if (modifiedBundles[bundleIdx] !== undefined) {
              continue;
            }
            modifiedBundles[bundleIdx] = [uvFormat, uvOffset];
            var newBundle = newMeshStruct.vertexBundles[bundleIdx];
            newBundle.attributes.push(batch_id);
            newBundle.attributes.push(batch_uv);
            newBundle.view.offset = 0;
            newBundle.view.length += newBundle.view.count * batch_extras_size;
            newBundle.view.stride += batch_extras_size;
          }
          var totalLength = 0;
          for (var b = 0; b < newMeshStruct.vertexBundles.length; b++) {
            totalLength += newMeshStruct.vertexBundles[b].view.length;
          }
          for (var _p = 0; _p < newMeshStruct.primitives.length; _p++) {
            var pm = newMeshStruct.primitives[_p];
            if (pm.indexView) {
              pm.indexView.offset = totalLength;
              totalLength += pm.indexView.length;
            }
          }
          var newMeshData = new Uint8Array(totalLength);
          var oldMeshData = mesh.data;
          var newDataView = new DataView(newMeshData.buffer);
          var oldDataView = new DataView(oldMeshData.buffer);
          var isLittleEndian = legacyCC.sys.isLittleEndian;
          for (var _b in modifiedBundles) {
            var _newBundle = newMeshStruct.vertexBundles[_b];
            var oldBundle = mesh.struct.vertexBundles[_b];
            var _modifiedBundles$_b = modifiedBundles[_b],
              _uvFormat = _modifiedBundles$_b[0],
              _uvOffset = _modifiedBundles$_b[1];
            var uvs = readBuffer(oldDataView, _uvFormat, _uvOffset, oldBundle.view.length, oldBundle.view.stride);
            var oldView = oldBundle.view;
            var newView = _newBundle.view;
            var oldStride = oldView.stride;
            var newStride = newView.stride;
            var oldOffset = oldView.offset;
            var newOffset = newView.offset;
            for (var j = 0; j < newView.count; j++) {
              var srcVertex = oldMeshData.subarray(oldOffset, oldOffset + oldStride);
              newMeshData.set(srcVertex, newOffset);
              newDataView.setFloat32(newOffset + oldStride, unitIdx);
              newDataView.setFloat32(newOffset + oldStride + 4, uvs[j * 2], isLittleEndian);
              newDataView.setFloat32(newOffset + oldStride + 8, uvs[j * 2 + 1], isLittleEndian);
              newOffset += newStride;
              oldOffset += oldStride;
            }
          }
          for (var k = 0; k < newMeshStruct.primitives.length; k++) {
            var oldPrimitive = mesh.struct.primitives[k];
            var newPrimitive = newMeshStruct.primitives[k];
            if (oldPrimitive.indexView && newPrimitive.indexView) {
              var _oldStride = oldPrimitive.indexView.stride;
              var _newStride = newPrimitive.indexView.stride;
              var _oldOffset = oldPrimitive.indexView.offset;
              var _newOffset = newPrimitive.indexView.offset;
              for (var _j3 = 0; _j3 < newPrimitive.indexView.count; _j3++) {
                var srcIndices = oldMeshData.subarray(_oldOffset, _oldOffset + _oldStride);
                newMeshData.set(srcIndices, _newOffset);
                _newOffset += _newStride;
                _oldOffset += _oldStride;
              }
            }
          }
          var newMesh = new Mesh();
          newMesh.reset({
            struct: newMeshStruct,
            data: newMeshData
          });
          return newMesh;
        };
        _createClass(SkinnedMeshBatchRenderer, [{
          key: "mesh",
          get: function get() {
            return _SkinnedMeshRenderer.prototype.mesh;
          },
          set: function set(val) {
            this.mesh = val;
          }
        }, {
          key: "skeleton",
          get: function get() {
            return _SkinnedMeshRenderer.prototype.skeleton;
          },
          set: function set(val) {
            this.skeleton = val;
          }
        }]);
        return SkinnedMeshBatchRenderer;
      }(SkinnedMeshRenderer), (_initializer7$f = applyDecoratedInitializer(_class5$q.prototype, "atlasSize", [serializable$j], function () {
        return 1024;
      }), _initializer8$e = applyDecoratedInitializer(_class5$q.prototype, "batchableTextureNames", [_dec8$c, serializable$j], function () {
        return [];
      }), _initializer9$d = applyDecoratedInitializer(_class5$q.prototype, "units", [_dec9$a, serializable$j], function () {
        return [];
      }), _applyDecoratedDescriptor(_class5$q.prototype, "mesh", [override], Object.getOwnPropertyDescriptor(_class5$q.prototype, "mesh"), _class5$q.prototype), _applyDecoratedDescriptor(_class5$q.prototype, "skeleton", [override], Object.getOwnPropertyDescriptor(_class5$q.prototype, "skeleton"), _class5$q.prototype)), _class5$q)) || _class4$o) || _class4$o));

      var _dec$1Q, _dec2$1m, _dec3$X, _dec4$I, _dec5$B, _class$1P, _class2$1D, _initializer$1u, _initializer2$1a, _dec6$l, _dec7$g, _dec8$b, _class4$n, _class5$p, _initializer3$L, _initializer4$A, _initializer5$p;
      var DEFAULT_SCREEN_OCCUPATION = [0.25, 0.125, 0.01];
      var LOD = exports('ad', (_dec$1Q = ccclass$n('cc.LOD'), _dec2$1m = type$7([MeshRenderer]), _dec3$X = type$7(CCFloat), _dec4$I = type$7([MeshRenderer]), _dec5$B = type$7([CCInteger]), _dec$1Q(_class$1P = (_class2$1D = function () {
        function LOD() {
          this._screenUsagePercentage = _initializer$1u && _initializer$1u();
          this._renderers = _initializer2$1a && _initializer2$1a();
          this._LODData = new LODData();
          this._modelAddedCallback = void 0;
          this._LODData.screenUsagePercentage = this._screenUsagePercentage;
          this._modelAddedCallback = null;
        }
        var _proto = LOD.prototype;
        _proto.insertRenderer = function insertRenderer(index, renderer) {
          if (index < 0 || index > this._renderers.length) {
            index = this._renderers.length;
          }
          this._renderers.splice(index, 0, renderer);
          var modelAdded = false;
          if (renderer.model) {
            modelAdded = true;
            this._LODData.addModel(renderer.model);
          }
          if (this._modelAddedCallback && modelAdded) {
            this._modelAddedCallback();
          }
          return renderer;
        };
        _proto.deleteRenderer = function deleteRenderer(index) {
          var _renders$;
          var renders = this._renderers.splice(index, 1);
          var model = renders.length > 0 ? (_renders$ = renders[0]) === null || _renders$ === void 0 ? void 0 : _renders$.model : null;
          if (model) {
            this._LODData.eraseModel(model);
          }
          return renders[0];
        };
        _proto.getRenderer = function getRenderer(index) {
          return this._renderers[index] || null;
        };
        _proto.setRenderer = function setRenderer(index, renderer) {
          if (index < 0 || index >= this.rendererCount) {
            console.error('setRenderer to LOD error, index out of range');
            return;
          }
          this.deleteRenderer(index);
          this.insertRenderer(index, renderer);
        };
        _createClass(LOD, [{
          key: "screenUsagePercentage",
          get: function get() {
            return this._screenUsagePercentage;
          },
          set: function set(val) {
            this._screenUsagePercentage = val;
            this._LODData.screenUsagePercentage = val;
          }
        }, {
          key: "renderers",
          get: function get() {
            return this._renderers;
          },
          set: function set(meshList) {
            if (meshList === this._renderers) return;
            var modelAdded = false;
            this._renderers.length = 0;
            this._LODData.clearModels();
            for (var i = 0; i < meshList.length; i++) {
              var _meshList$i;
              this._renderers[i] = meshList[i];
              var model = (_meshList$i = meshList[i]) === null || _meshList$i === void 0 ? void 0 : _meshList$i.model;
              if (model) {
                modelAdded = true;
                this._LODData.addModel(model);
              }
            }
            if (this._modelAddedCallback && modelAdded) {
              this._modelAddedCallback();
            }
          }
        }, {
          key: "triangleCount",
          get: function get() {
            var tris = [];
            this._renderers.forEach(function (meshRenderer) {
              var count = 0;
              if (meshRenderer && meshRenderer.mesh) {
                var primitives = meshRenderer.mesh.struct.primitives;
                primitives === null || primitives === void 0 ? void 0 : primitives.forEach(function (subMesh) {
                  if (subMesh && subMesh.indexView) {
                    count += subMesh.indexView.count;
                  }
                });
              }
              tris.push(count / 3);
            });
            return tris;
          }
        }, {
          key: "rendererCount",
          get: function get() {
            return this._renderers.length;
          }
        }, {
          key: "lodData",
          get: function get() {
            return this._LODData;
          }
        }, {
          key: "modelAddedCallback",
          set: function set(callback) {
            this._modelAddedCallback = callback;
          }
        }]);
        return LOD;
      }(), (_initializer$1u = applyDecoratedInitializer(_class2$1D.prototype, "_screenUsagePercentage", [serializable$j], function () {
        return 1.0;
      }), _initializer2$1a = applyDecoratedInitializer(_class2$1D.prototype, "_renderers", [_dec2$1m, serializable$j], function () {
        return [];
      }), _applyDecoratedDescriptor(_class2$1D.prototype, "screenUsagePercentage", [_dec3$X], Object.getOwnPropertyDescriptor(_class2$1D.prototype, "screenUsagePercentage"), _class2$1D.prototype), _applyDecoratedDescriptor(_class2$1D.prototype, "renderers", [_dec4$I], Object.getOwnPropertyDescriptor(_class2$1D.prototype, "renderers"), _class2$1D.prototype), _applyDecoratedDescriptor(_class2$1D.prototype, "triangleCount", [_dec5$B], Object.getOwnPropertyDescriptor(_class2$1D.prototype, "triangleCount"), _class2$1D.prototype)), _class2$1D)) || _class$1P));
      var LODGroup = exports('ae', (_dec6$l = ccclass$n('cc.LODGroup'), _dec7$g = type$7(CCFloat), _dec8$b = type$7([LOD]), _dec6$l(_class4$n = (_class5$p = function (_Component) {
        _inheritsLoose(LODGroup, _Component);
        function LODGroup() {
          var _this;
          _this = _Component.call(this) || this;
          _this._localBoundaryCenter = _initializer3$L && _initializer3$L();
          _this._objectSize = _initializer4$A && _initializer4$A();
          _this._LODs = _initializer5$p && _initializer5$p();
          _this._lodGroup = new LODGroup$1();
          _this._eventRegistered = false;
          _this._forceUsedLevels = [];
          return _this;
        }
        var _proto2 = LODGroup.prototype;
        _proto2.onLodModelAddedCallback = function onLodModelAddedCallback() {
          if (this.objectSize === 0) {
            this.recalculateBounds();
          }
        };
        _proto2.insertLOD = function insertLOD(index, screenUsagePercentage, lod) {
          if (index < 0 || index > this.lodCount) {
            index = this.lodCount;
          }
          if (!lod) {
            lod = new LOD();
          }
          lod.modelAddedCallback = this.onLodModelAddedCallback.bind(this);
          if (!screenUsagePercentage) {
            var preLod = this.getLOD(index - 1);
            var nextLod = this.getLOD(index);
            if (preLod && nextLod) {
              screenUsagePercentage = (preLod.screenUsagePercentage + nextLod.screenUsagePercentage) / 2;
            } else if (preLod && !nextLod) {
              screenUsagePercentage = preLod.screenUsagePercentage / 2;
              if (screenUsagePercentage > 0.01) {
                screenUsagePercentage = 0.01;
              }
            } else if (nextLod && !preLod) {
              screenUsagePercentage = nextLod.screenUsagePercentage;
              var curNextLOD = this.getLOD(index + 1);
              nextLod.screenUsagePercentage = (screenUsagePercentage + (curNextLOD ? curNextLOD.screenUsagePercentage : 0)) / 2;
            } else {
              screenUsagePercentage = DEFAULT_SCREEN_OCCUPATION[0];
            }
          }
          lod.screenUsagePercentage = screenUsagePercentage;
          this._LODs.splice(index, 0, lod);
          this._lodGroup.insertLOD(index, lod.lodData);
          this._updateDataToScene();
          if (this.node) {
            this._emitChangeNode(this.node);
          }
          return lod;
        };
        _proto2.eraseLOD = function eraseLOD(index) {
          if (index < 0 || index >= this.lodCount) {
            console.warn('eraseLOD error, index out of range');
            return null;
          }
          var lod = this._LODs[index];
          if (!lod) {
            console.warn('eraseLOD error, LOD not exist at specified index.');
            return null;
          }
          this._LODs.splice(index, 1);
          this._lodGroup.eraseLOD(index);
          this._updateDataToScene();
          this._emitChangeNode(this.node);
          return lod;
        };
        _proto2.getLOD = function getLOD(index) {
          if (index < 0 || index >= this.lodCount) {
            console.warn('getLOD error, index out of range');
            return null;
          }
          return this._LODs[index];
        };
        _proto2.setLOD = function setLOD(index, lod) {
          if (index < 0 || index >= this.lodCount) {
            console.warn('setLOD error, index out of range');
            return;
          }
          this._LODs[index] = lod;
          lod.modelAddedCallback = this.onLodModelAddedCallback.bind(this);
          this.lodGroup.updateLOD(index, lod.lodData);
          this._updateDataToScene();
        };
        _proto2.recalculateBounds = function recalculateBounds() {
          function getTransformedBoundary(c, e, transform) {
            var minPos;
            var maxPos;
            var pts = new Array(new Vec3(c.x - e.x, c.y - e.y, c.z - e.z), new Vec3(c.x - e.x, c.y + e.y, c.z - e.z), new Vec3(c.x + e.x, c.y + e.y, c.z - e.z), new Vec3(c.x + e.x, c.y - e.y, c.z - e.z), new Vec3(c.x - e.x, c.y - e.y, c.z + e.z), new Vec3(c.x - e.x, c.y + e.y, c.z + e.z), new Vec3(c.x + e.x, c.y + e.y, c.z + e.z), new Vec3(c.x + e.x, c.y - e.y, c.z + e.z));
            minPos = pts[0].transformMat4(transform);
            maxPos = minPos.clone();
            for (var i = 1; i < 8; ++i) {
              var pt = pts[i].transformMat4(transform);
              minPos = Vec3.min(minPos, minPos, pt);
              maxPos = Vec3.max(maxPos, maxPos, pt);
            }
            return [minPos, maxPos];
          }
          var minPos = new Vec3();
          var maxPos = new Vec3();
          var boundsMin = null;
          var boundsMax = new Vec3();
          for (var i = 0; i < this.lodCount; ++i) {
            var lod = this.getLOD(i);
            if (lod) {
              for (var j = 0; j < lod.rendererCount; ++j) {
                var _renderer$model, _renderer$model2;
                var renderer = lod.getRenderer(j);
                if (!renderer) {
                  continue;
                }
                (_renderer$model = renderer.model) === null || _renderer$model === void 0 ? void 0 : _renderer$model.updateWorldBound();
                var worldBounds = (_renderer$model2 = renderer.model) === null || _renderer$model2 === void 0 ? void 0 : _renderer$model2.worldBounds;
                if (worldBounds) {
                  worldBounds.getBoundary(minPos, maxPos);
                  if (boundsMin) {
                    Vec3.min(boundsMin, boundsMin, minPos);
                    Vec3.max(boundsMax, boundsMax, maxPos);
                  } else {
                    boundsMin = minPos.clone();
                    boundsMax = maxPos.clone();
                  }
                }
              }
            }
          }
          if (boundsMin) {
            var boundsMin2 = boundsMin;
            var c = new Vec3((boundsMax.x + boundsMin2.x) * 0.5, (boundsMax.y + boundsMin2.y) * 0.5, (boundsMax.z + boundsMin2.z) * 0.5);
            var e = new Vec3((boundsMax.x - boundsMin2.x) * 0.5, (boundsMax.y - boundsMin2.y) * 0.5, (boundsMax.z - boundsMin2.z) * 0.5);
            var _getTransformedBounda = getTransformedBoundary(c, e, this.node.worldMatrix.clone().invert()),
              _minPos = _getTransformedBounda[0],
              _maxPos = _getTransformedBounda[1];
            c.set((_maxPos.x + _minPos.x) * 0.5, (_maxPos.y + _minPos.y) * 0.5, (_maxPos.z + _minPos.z) * 0.5);
            e.set((_maxPos.x - _minPos.x) * 0.5, (_maxPos.y - _minPos.y) * 0.5, (_maxPos.z - _minPos.z) * 0.5);
            this.localBoundaryCenter = c;
            this.objectSize = Math.max(e.x, e.y, e.z) * 2.0;
          } else {
            this.localBoundaryCenter = new Vec3(0, 0, 0);
            this.objectSize = 0;
          }
          this._emitChangeNode(this.node);
        };
        _proto2.resetObjectSize = function resetObjectSize() {
          if (this.objectSize === 1.0) return;
          if (this.objectSize === 0) {
            this.objectSize = 1.0;
          }
          var scale = 1.0 / this.objectSize;
          this.objectSize = 1.0;
          for (var i = 0; i < this.lodCount; ++i) {
            var lod = this.getLOD(i);
            if (lod) {
              lod.screenUsagePercentage *= scale;
            }
          }
          this._emitChangeNode(this.node);
        };
        _proto2.forceLOD = function forceLOD(lodLevel) {
          this._forceUsedLevels = lodLevel < 0 ? [] : [lodLevel];
          this.lodGroup.lockLODLevels(this._forceUsedLevels);
        };
        _proto2.forceLODs = function forceLODs(lodIndexArray) {
        };
        _proto2.onLoad = function onLoad() {
          this._lodGroup.node = this.node;
          this._lodGroup.objectSize = this._objectSize;
          this._lodGroup.localBoundaryCenter = this._localBoundaryCenter;
          if (!this._eventRegistered) {
            this.node.on(NodeEventType.COMPONENT_REMOVED, this._onRemove, this);
            this._eventRegistered = true;
          }
          this._constructLOD();
        };
        _proto2._onRemove = function _onRemove(comp) {
          if (comp === this) {
            this.onDisable();
          }
        };
        _proto2._constructLOD = function _constructLOD() {
          if (this.lodCount < 1) {
            var size = DEFAULT_SCREEN_OCCUPATION.length;
            for (var i = 0; i < size; i++) {
              this.insertLOD(i, DEFAULT_SCREEN_OCCUPATION[i]);
            }
          }
        };
        _proto2.onRestore = function onRestore() {
          this._constructLOD();
          if (this.enabledInHierarchy) {
            this._attachToScene();
          }
        };
        _proto2.onEnable = function onEnable() {
          var _this2 = this;
          this._attachToScene();
          if (this.objectSize === 0) {
            this.recalculateBounds();
          }
          this.lodGroup.lockLODLevels(this._forceUsedLevels);
          if (this.lodCount > 0 && this._lodGroup.lodCount < 1) {
            this._LODs.forEach(function (lod, index) {
              lod.lodData.screenUsagePercentage = lod.screenUsagePercentage;
              var renderers = lod.renderers;
              if (renderers !== null && renderers.length > 0) {
                for (var i = 0; i < renderers.length; i++) {
                  var lodInstance = lod.lodData;
                  var renderer = renderers[i];
                  if (lodInstance && renderer && renderer.model) {
                    lodInstance.addModel(renderer.model);
                  }
                }
              }
              _this2._lodGroup.insertLOD(index, lod.lodData);
            });
          }
        };
        _proto2.onDisable = function onDisable() {
          this._detachFromScene();
          this.lodGroup.lockLODLevels([]);
        };
        _proto2._attachToScene = function _attachToScene() {
          if (this.node && this.node.scene) {
            var renderScene = this._getRenderScene();
            if (this._lodGroup.scene) {
              this._detachFromScene();
            }
            renderScene.addLODGroup(this._lodGroup);
          }
        };
        _proto2._detachFromScene = function _detachFromScene() {
          if (this._lodGroup.scene) {
            this._lodGroup.scene.removeLODGroup(this._lodGroup);
          }
        };
        _proto2._emitChangeNode = function _emitChangeNode(node) {
        };
        _proto2._updateDataToScene = function _updateDataToScene() {
          this._detachFromScene();
          this._attachToScene();
        };
        _createClass(LODGroup, [{
          key: "localBoundaryCenter",
          get: function get() {
            return this._localBoundaryCenter.clone();
          },
          set: function set(val) {
            this._localBoundaryCenter.set(val);
            this._lodGroup.localBoundaryCenter = val;
          }
        }, {
          key: "lodCount",
          get: function get() {
            return this._LODs.length;
          }
        }, {
          key: "objectSize",
          get: function get() {
            return this._objectSize;
          },
          set: function set(val) {
            this._objectSize = val;
            this._lodGroup.objectSize = val;
          }
        }, {
          key: "LODs",
          get: function get() {
            return this._LODs;
          },
          set: function set(valArray) {
            var _this3 = this;
            if (valArray === this._LODs) {
              this._updateDataToScene();
              return;
            }
            this._LODs.length = 0;
            this.lodGroup.clearLODs();
            valArray.forEach(function (lod, index) {
              _this3.lodGroup.insertLOD(index, lod.lodData);
              _this3._LODs[index] = lod;
              lod.modelAddedCallback = _this3.onLodModelAddedCallback.bind(_this3);
            });
            this._updateDataToScene();
          }
        }, {
          key: "lodGroup",
          get: function get() {
            return this._lodGroup;
          }
        }]);
        return LODGroup;
      }(Component), (_initializer3$L = applyDecoratedInitializer(_class5$p.prototype, "_localBoundaryCenter", [serializable$j], function () {
        return new Vec3(0, 0, 0);
      }), _initializer4$A = applyDecoratedInitializer(_class5$p.prototype, "_objectSize", [serializable$j], function () {
        return 0;
      }), _initializer5$p = applyDecoratedInitializer(_class5$p.prototype, "_LODs", [serializable$j], function () {
        return [];
      }), _applyDecoratedDescriptor(_class5$p.prototype, "objectSize", [_dec7$g], Object.getOwnPropertyDescriptor(_class5$p.prototype, "objectSize"), _class5$p.prototype), _applyDecoratedDescriptor(_class5$p.prototype, "LODs", [_dec8$b], Object.getOwnPropertyDescriptor(_class5$p.prototype, "LODs"), _class5$p.prototype)), _class5$p)) || _class4$n));

      var REFLECTION_PROBE_DEFAULT_MASK = Layers.makeMaskExclude([Layers.BitMask.UI_2D, Layers.BitMask.UI_3D, Layers.BitMask.GIZMOS, Layers.BitMask.EDITOR, Layers.BitMask.SCENE_GIZMO, Layers.BitMask.PROFILER, Layers.Enum.IGNORE_RAYCAST]);
      var ReflectionProbeManager = exports('ag', function () {
        function ReflectionProbeManager() {
          this._probes = [];
          this._useCubeModels = new Map();
          this._usePlanarModels = new Map();
          this._updateForRuntime = true;
          this._dataTexture = null;
          this._registeredEvent = false;
        }
        var _proto = ReflectionProbeManager.prototype;
        _proto.registerEvent = function registerEvent() {
          if (!this._registeredEvent) {
            legacyCC.director.on(legacyCC.Director.EVENT_BEFORE_UPDATE, this.onUpdateProbes, this);
            this._registeredEvent = true;
          }
        };
        _proto.onUpdateProbes = function onUpdateProbes() {
          if (this._probes.length === 0) return;
          var scene = legacyCC.director.getScene();
          if (!scene || !scene.renderScene) {
            return;
          }
          var models = scene.renderScene.models;
          for (var i = 0; i < models.length; i++) {
            var model = models[i];
            if (!model.node) continue;
            if (model.node.layer & REFLECTION_PROBE_DEFAULT_MASK) {
              if (model.reflectionProbeType === ReflectionProbeType.BAKED_CUBEMAP || this._isUsedBlending(model)) {
                this.selectReflectionProbe(model);
              } else if (model.reflectionProbeType === ReflectionProbeType.PLANAR_REFLECTION) {
                this.selectPlanarReflectionProbe(model);
              }
            }
          }
        };
        _proto.filterModelsForPlanarReflection = function filterModelsForPlanarReflection() {
          if (this._probes.length === 0) return;
          var scene = legacyCC.director.getScene();
          if (!scene || !scene.renderScene) {
            return;
          }
          var models = scene.renderScene.models;
          for (var i = 0; i < models.length; i++) {
            var model = models[i];
            if (!model.node) continue;
            if (model.node.layer & REFLECTION_PROBE_DEFAULT_MASK && model.reflectionProbeType === ReflectionProbeType.PLANAR_REFLECTION) {
              this.selectPlanarReflectionProbe(model);
            }
          }
        };
        _proto.clearPlanarReflectionMap = function clearPlanarReflectionMap(probe) {
          for (var _iterator = _createForOfIteratorHelperLoose(this._usePlanarModels.entries()), _step; !(_step = _iterator()).done;) {
            var entry = _step.value;
            if (entry[1] === probe) {
              this._updatePlanarMapOfModel(entry[0], null, null);
            }
          }
        };
        _proto.register = function register(probe) {
          var index = this._probes.indexOf(probe);
          if (index === -1) {
            this._probes.push(probe);
            this.updateProbeData();
          }
        };
        _proto.unregister = function unregister(probe) {
          for (var i = 0; i < this._probes.length; i++) {
            if (this._probes[i] === probe) {
              var del = this._probes.splice(i, 1);
              if (del[0]) {
                this._removeDependentModels(del[0]);
              }
              break;
            }
          }
          this.updateProbeData();
        };
        _proto.exists = function exists(probeId) {
          if (this._probes.length === 0) return false;
          for (var i = 0; i < this._probes.length; i++) {
            if (this._probes[i].getProbeId() === probeId) {
              return true;
            }
          }
          return false;
        };
        _proto.getNewReflectionProbeId = function getNewReflectionProbeId() {
          var probeId = 0;
          while (true) {
            if (this.exists(probeId)) {
              probeId++;
            } else {
              return probeId;
            }
          }
        };
        _proto.getProbes = function getProbes() {
          return this._probes;
        };
        _proto.getProbeById = function getProbeById(probeId) {
          for (var i = 0; i < this._probes.length; i++) {
            if (this._probes[i].getProbeId() === probeId) {
              return this._probes[i];
            }
          }
          return null;
        };
        _proto.clearAll = function clearAll() {
          this._probes = [];
        };
        _proto.getProbeByCamera = function getProbeByCamera(camera) {
          for (var i = 0; i < this._probes.length; i++) {
            if (this._probes[i].camera === camera) {
              return this._probes[i];
            }
          }
          return null;
        };
        _proto.updateBakedCubemap = function updateBakedCubemap(probe) {
          var models = this._getModelsByProbe(probe);
          if (!probe.cubemap) return;
          for (var i = 0; i < models.length; i++) {
            var model = models[i];
            this._updateCubemapOfModel(model, probe);
          }
          probe.needRefresh = false;
          if (models.length === 0) {
            for (var _iterator2 = _createForOfIteratorHelperLoose(this._useCubeModels.entries()), _step2; !(_step2 = _iterator2()).done;) {
              var entry = _step2.value;
              if (entry[0].reflectionProbeBlendId === probe.getProbeId()) {
                this._updateBlendCubemap(entry[0], probe);
              }
            }
          }
        };
        _proto.updatePlanarMap = function updatePlanarMap(probe, texture) {
          if (!probe.node || !probe.node.scene) return;
          var models = this._getModelsByProbe(probe);
          for (var i = 0; i < models.length; i++) {
            this._updatePlanarMapOfModel(models[i], texture, probe);
          }
          if (probe.previewPlane) {
            var meshRender = probe.previewPlane.getComponent(MeshRenderer);
            if (meshRender) {
              meshRender.updateProbePlanarMap(texture);
            }
          }
        };
        _proto.selectPlanarReflectionProbe = function selectPlanarReflectionProbe(model) {
          if (!model.node || !model.worldBounds || model.reflectionProbeType !== ReflectionProbeType.PLANAR_REFLECTION) return;
          for (var i = 0; i < this._probes.length; i++) {
            var probe = this._probes[i];
            if (probe.probeType !== ProbeType.PLANAR) continue;
            if (model.node.layer & REFLECTION_PROBE_DEFAULT_MASK) {
              model.updateWorldBound();
              if (intersect.aabbWithAABB(model.worldBounds, probe.boundingBox)) {
                this._usePlanarModels.set(model, probe);
              } else if (this._usePlanarModels.has(model)) {
                var old = this._usePlanarModels.get(model);
                if (old === probe) {
                  this._usePlanarModels["delete"](model);
                  this._updatePlanarMapOfModel(model, null, null);
                }
              }
            }
          }
          for (var _i = 0; _i < this._probes.length; _i++) {
            if (this._probes[_i].probeType === ProbeType.PLANAR) {
              if (!this._probes[_i].realtimePlanarTexture) {
                this.updatePlanarMap(this._probes[_i], null);
              } else {
                this.updatePlanarMap(this._probes[_i], this._probes[_i].realtimePlanarTexture.getGFXTexture());
              }
            }
          }
        };
        _proto.selectReflectionProbe = function selectReflectionProbe(model) {
          if (model.node && model.worldBounds && model.node.layer & REFLECTION_PROBE_DEFAULT_MASK) {
            model.updateWorldBound();
            var nearest = this._getNearestProbe(model);
            if (!nearest) {
              this._updateCubemapOfModel(model, null);
              this._useCubeModels["delete"](model);
            } else if (this._useCubeModels.has(model)) {
              var old = this._useCubeModels.get(model);
              if (old !== nearest) {
                this._useCubeModels.set(model, nearest);
              }
              nearest.needRefresh = true;
            } else {
              this._useCubeModels.set(model, nearest);
              nearest.needRefresh = true;
            }
          }
          for (var i = 0; i < this._probes.length; i++) {
            if (this._probes[i].needRefresh && this._probes[i].probeType === ProbeType.CUBE || this._isUsedBlending(model)) {
              this.updateBakedCubemap(this._probes[i]);
            }
          }
        };
        _proto.updatePreviewSphere = function updatePreviewSphere(probe) {
          if (!probe || !probe.previewSphere) return;
          var meshRender = probe.previewSphere.getComponent(MeshRenderer);
          if (meshRender) {
            meshRender.updateProbeCubemap(probe.cubemap);
            meshRender.updateReflectionProbeId(probe.getProbeId());
          }
        };
        _proto.updatePreviewPlane = function updatePreviewPlane(probe) {
          if (!probe || !probe.previewPlane) return;
          var meshRender = probe.previewPlane.getComponent(MeshRenderer);
          if (meshRender) {
            if (probe.realtimePlanarTexture) {
              this.updatePlanarMap(probe, probe.realtimePlanarTexture.getGFXTexture());
            }
          }
        };
        _proto.updateProbeData = function updateProbeData() {
          if (this._probes.length === 0) return;
          var maxId = this.getMaxProbeId();
          var height = maxId + 1;
          var dataWidth = 3;
          if (this._dataTexture) {
            this._dataTexture.destroy();
          }
          var buffer = new Float32Array(4 * dataWidth * height);
          var bufferOffset = 0;
          for (var i = 0; i <= maxId; i++) {
            var probe = this.getProbeById(i);
            if (!probe) {
              bufferOffset += 4 * dataWidth;
              continue;
            }
            if (probe.probeType === ProbeType.CUBE) {
              buffer[bufferOffset] = probe.node.worldPosition.x;
              buffer[bufferOffset + 1] = probe.node.worldPosition.y;
              buffer[bufferOffset + 2] = probe.node.worldPosition.z;
              buffer[bufferOffset + 3] = 0.0;
              buffer[bufferOffset + 4] = probe.size.x;
              buffer[bufferOffset + 5] = probe.size.y;
              buffer[bufferOffset + 6] = probe.size.z;
              buffer[bufferOffset + 7] = 0.0;
              var mipAndUseRGBE = probe.isRGBE() ? 1000 : 0;
              buffer[bufferOffset + 8] = probe.cubemap ? probe.cubemap.mipmapLevel + mipAndUseRGBE : 1.0 + mipAndUseRGBE;
            } else {
              buffer[bufferOffset] = probe.node.up.x;
              buffer[bufferOffset + 1] = probe.node.up.y;
              buffer[bufferOffset + 2] = probe.node.up.z;
              buffer[bufferOffset + 3] = 1.0;
              buffer[bufferOffset + 4] = 1.0;
              buffer[bufferOffset + 5] = 1.0;
              buffer[bufferOffset + 6] = 0.0;
              buffer[bufferOffset + 7] = 0.0;
              buffer[bufferOffset + 8] = 1.0;
            }
            bufferOffset += 4 * dataWidth;
          }
          var updateView = new Uint8Array(buffer.buffer);
          var image = new ImageAsset({
            _data: updateView,
            _compressed: false,
            width: dataWidth * 4,
            height: height,
            format: PixelFormat.RGBA8888
          });
          this._dataTexture = new Texture2D();
          this._dataTexture.setFilters(Texture2D.Filter.NONE, Texture2D.Filter.NONE);
          this._dataTexture.setMipFilter(Texture2D.Filter.NONE);
          this._dataTexture.setWrapMode(Texture2D.WrapMode.CLAMP_TO_EDGE, Texture2D.WrapMode.CLAMP_TO_EDGE, Texture2D.WrapMode.CLAMP_TO_EDGE);
          this._dataTexture.image = image;
          this._dataTexture.uploadData(updateView);
          for (var _i2 = 0; _i2 < this._probes.length; _i2++) {
            var _probe = this._probes[_i2];
            var models = this._getModelsByProbe(_probe);
            for (var j = 0; j < models.length; j++) {
              var meshRender = models[j].node.getComponent(MeshRenderer);
              if (meshRender) {
                meshRender.updateReflectionProbeDataMap(this._dataTexture);
              }
            }
          }
        };
        _proto.getMaxProbeId = function getMaxProbeId() {
          if (this._probes.length === 0) {
            return -1;
          }
          if (this._probes.length === 1) {
            return this._probes[0].getProbeId();
          }
          this._probes.sort(function (a, b) {
            return a.getProbeId() - b.getProbeId();
          });
          return this._probes[this._probes.length - 1].getProbeId();
        };
        _proto.getUsedReflectionProbe = function getUsedReflectionProbe(model, planarReflection) {
          if (planarReflection) {
            if (this._usePlanarModels.has(model)) {
              return this._usePlanarModels.get(model);
            }
          } else if (this._useCubeModels.has(model)) {
            return this._useCubeModels.get(model);
          }
          return null;
        };
        _proto.setReflectionProbe = function setReflectionProbe(model, probe, blendProbe) {
          if (blendProbe === void 0) {
            blendProbe = null;
          }
          if (!probe) return;
          this._useCubeModels.set(model, probe);
          this._updateCubemapOfModel(model, probe);
          if (blendProbe) {
            this._updateBlendProbeInfo(model, probe, blendProbe);
          }
        };
        _proto.updateProbeOfModels = function updateProbeOfModels() {
          if (this._probes.length === 0) return;
          var scene = legacyCC.director.getScene();
          if (!scene || !scene.renderScene) {
            return;
          }
          var models = scene.renderScene.models;
          for (var i = 0; i < models.length; i++) {
            var model = models[i];
            if (!model.node) continue;
            if (model.node.layer & REFLECTION_PROBE_DEFAULT_MASK) {
              if (model.reflectionProbeType === ReflectionProbeType.BAKED_CUBEMAP || model.reflectionProbeType === ReflectionProbeType.PLANAR_REFLECTION || this._isUsedBlending(model)) {
                model.updateReflectionProbeId();
              }
            }
          }
        };
        _proto._getNearestProbe = function _getNearestProbe(model) {
          if (!model.node || !model.worldBounds || this._probes.length === 0) return null;
          var nearestProbe = null;
          var minDistance = Infinity;
          for (var _iterator3 = _createForOfIteratorHelperLoose(this._probes), _step3; !(_step3 = _iterator3()).done;) {
            var probe = _step3.value;
            if (probe.probeType !== ProbeType.CUBE || !probe.validate() || !intersect.aabbWithAABB(model.worldBounds, probe.boundingBox)) {
              continue;
            }
            var distance = Vec3.distance(model.node.worldPosition, probe.node.worldPosition);
            if (distance < minDistance) {
              minDistance = distance;
              nearestProbe = probe;
            }
          }
          return nearestProbe;
        };
        _proto._getBlendProbe = function _getBlendProbe(model) {
          if (!model || !model.node || !model.worldBounds || this._probes.length < 2) {
            return null;
          }
          var temp = [];
          for (var i = 0; i < this._probes.length; i++) {
            if (this._probes[i].probeType !== ProbeType.CUBE || !this._probes[i].validate() || !intersect.aabbWithAABB(model.worldBounds, this._probes[i].boundingBox)) {
              continue;
            }
            temp.push(this._probes[i]);
          }
          temp.sort(function (a, b) {
            var aDistance = Vec3.distance(model.node.worldPosition, a.node.worldPosition);
            var bDistance = Vec3.distance(model.node.worldPosition, b.node.worldPosition);
            return aDistance - bDistance;
          });
          return temp.length > 1 ? temp[1] : null;
        };
        _proto._getModelsByProbe = function _getModelsByProbe(probe) {
          var models = [];
          var useModels = this._useCubeModels;
          if (probe.probeType === ProbeType.PLANAR) {
            useModels = this._usePlanarModels;
          }
          for (var _iterator4 = _createForOfIteratorHelperLoose(useModels.entries()), _step4; !(_step4 = _iterator4()).done;) {
            var entry = _step4.value;
            if (entry[1] === probe) {
              models.push(entry[0]);
            }
          }
          return models;
        };
        _proto._removeDependentModels = function _removeDependentModels(probe) {
          for (var _iterator5 = _createForOfIteratorHelperLoose(this._useCubeModels.keys()), _step5; !(_step5 = _iterator5()).done;) {
            var key = _step5.value;
            var p = this._useCubeModels.get(key);
            if (p !== undefined && p === probe) {
              this._useCubeModels["delete"](key);
              this.selectReflectionProbe(key);
            }
          }
          for (var _iterator6 = _createForOfIteratorHelperLoose(this._usePlanarModels.keys()), _step6; !(_step6 = _iterator6()).done;) {
            var _key = _step6.value;
            var _p = this._usePlanarModels.get(_key);
            if (_p !== undefined && _p === probe) {
              this._usePlanarModels["delete"](_key);
              this.selectPlanarReflectionProbe(_key);
            }
          }
        };
        _proto._updateCubemapOfModel = function _updateCubemapOfModel(model, probe) {
          var node = model.node;
          if (!node) {
            return;
          }
          var meshRender = node.getComponent(MeshRenderer);
          if (!meshRender) {
            return;
          }
          meshRender.updateProbeCubemap(probe ? probe.cubemap : null);
          meshRender.updateReflectionProbeId(probe && probe.cubemap ? probe.getProbeId() : -1);
          if (probe) {
            meshRender.updateReflectionProbeDataMap(this._dataTexture);
            if (this._isUsedBlending(model)) {
              var blendProbe = this._getBlendProbe(model);
              this._updateBlendProbeInfo(model, probe, blendProbe);
            }
          }
        };
        _proto._updatePlanarMapOfModel = function _updatePlanarMapOfModel(model, texture, probe) {
          var meshRender = model.node.getComponent(MeshRenderer);
          if (meshRender) {
            meshRender.updateProbePlanarMap(texture);
            if (probe) {
              meshRender.updateReflectionProbeId(probe.getProbeId());
              meshRender.updateReflectionProbeDataMap(this._dataTexture);
            } else {
              meshRender.updateReflectionProbeId(-1);
            }
          }
        };
        _proto._isUsedBlending = function _isUsedBlending(model) {
          if (model.reflectionProbeType === ReflectionProbeType.BLEND_PROBES || model.reflectionProbeType === ReflectionProbeType.BLEND_PROBES_AND_SKYBOX) {
            return true;
          }
          return false;
        };
        _proto._updateBlendProbeInfo = function _updateBlendProbeInfo(model, probe, blendProbe) {
          var node = model.node;
          if (!node) {
            return;
          }
          var meshRender = node.getComponent(MeshRenderer);
          if (!meshRender) {
            return;
          }
          if (blendProbe) {
            meshRender.updateReflectionProbeBlendId(blendProbe.getProbeId());
            meshRender.updateProbeBlendCubemap(blendProbe.cubemap);
            meshRender.updateReflectionProbeBlendWeight(this._calculateBlendWeight(model, probe, blendProbe));
          } else {
            meshRender.updateReflectionProbeBlendId(-1);
            if (model.reflectionProbeType === ReflectionProbeType.BLEND_PROBES_AND_SKYBOX) {
              meshRender.updateReflectionProbeBlendWeight(this._calculateBlendWeight(model, probe, blendProbe));
            }
          }
        };
        _proto._updateBlendCubemap = function _updateBlendCubemap(model, probe) {
          var node = model.node;
          if (!node) {
            return;
          }
          if (!this._isUsedBlending(model)) {
            return;
          }
          var meshRender = node.getComponent(MeshRenderer);
          if (meshRender) {
            meshRender.updateProbeBlendCubemap(probe.cubemap);
          }
        };
        _proto._calculateBlendWeight = function _calculateBlendWeight(model, probe, blendProbe) {
          if (blendProbe) {
            var d1 = Vec3.distance(model.node.worldPosition, probe.node.worldPosition);
            var d2 = Vec3.distance(model.node.worldPosition, blendProbe.node.worldPosition);
            return 1.0 - d2 / (d1 + d2);
          }
          if (model.reflectionProbeType === ReflectionProbeType.BLEND_PROBES) {
            return 0.0;
          } else if (model.reflectionProbeType === ReflectionProbeType.BLEND_PROBES_AND_SKYBOX) {
            return this._calculateBlendOfSkybox(model.worldBounds, probe.boundingBox);
          }
          return 0.0;
        };
        _proto._calculateBlendOfSkybox = function _calculateBlendOfSkybox(aabb1, aabb2) {
          if (!aabb1) return 1.0;
          var aMin = new Vec3();
          var aMax = new Vec3();
          var bMin = new Vec3();
          var bMax = new Vec3();
          Vec3.subtract(aMin, aabb1.center, aabb1.halfExtents);
          Vec3.add(aMax, aabb1.center, aabb1.halfExtents);
          Vec3.subtract(bMin, aabb2.center, aabb2.halfExtents);
          Vec3.add(bMax, aabb2.center, aabb2.halfExtents);
          var inside = aMin.x <= bMax.x && aMax.x >= bMin.x && aMin.y <= bMax.y && aMax.y >= bMin.y && aMin.z <= bMax.z && aMax.z >= bMin.z;
          if (inside) {
            var fullSize = new Vec3();
            Vec3.multiplyScalar(fullSize, aabb1.halfExtents, 2.0);
            var boundaryXAdd = aMin.x + fullSize.x <= bMax.x && aMax.x + fullSize.x >= bMin.x;
            var boundaryXSub = aMin.x - fullSize.x <= bMax.x && aMax.x - fullSize.x >= bMin.x;
            var boundaryYAdd = aMin.y + fullSize.y <= bMax.y && aMax.y + fullSize.y >= bMin.y;
            var boundaryYSub = aMin.y - fullSize.y <= bMax.y && aMax.y - fullSize.y >= bMin.y;
            var boundaryZAdd = aMin.z + fullSize.z <= bMax.z && aMax.z + fullSize.z >= bMin.z;
            var boundaryZSub = aMin.z - fullSize.z <= bMax.z && aMax.z - fullSize.z >= bMin.z;
            var weights = [];
            if (!boundaryXAdd) {
              var offset = aMax.x - bMax.x;
              weights.push(offset / fullSize.x);
            }
            if (!boundaryXSub) {
              var _offset = Math.abs(aMin.x - bMin.x);
              weights.push(_offset / fullSize.x);
            }
            if (!boundaryYAdd) {
              var _offset2 = aMax.y - bMax.y;
              weights.push(_offset2 / fullSize.y);
            }
            if (!boundaryYSub) {
              var _offset3 = Math.abs(aMin.y - bMin.y);
              weights.push(_offset3 / fullSize.y);
            }
            if (!boundaryZAdd) {
              var _offset4 = aMax.z - bMax.z;
              weights.push(_offset4 / fullSize.z);
            }
            if (!boundaryZSub) {
              var _offset5 = Math.abs(aMin.z - bMin.z);
              weights.push(_offset5 / fullSize.z);
            }
            if (weights.length > 0) {
              weights.sort(function (a, b) {
                return b - a;
              });
              return weights[0];
            } else {
              return 0.0;
            }
          }
          return 1.0;
        };
        _createClass(ReflectionProbeManager, [{
          key: "updateForRuntime",
          get: function get() {
            return this._updateForRuntime;
          },
          set: function set(val) {
            this._updateForRuntime = val;
          }
        }]);
        return ReflectionProbeManager;
      }());
      ReflectionProbeManager.probeManager = void 0;
      ReflectionProbeManager.probeManager = new ReflectionProbeManager();
      legacyCC.internal.reflectionProbeManager = ReflectionProbeManager.probeManager;

      function wireframe(indices) {
        var offsets = [[0, 1], [1, 2], [2, 0]];
        var lines = [];
        var lineIDs = {};
        for (var i = 0; i < indices.length; i += 3) {
          for (var k = 0; k < 3; ++k) {
            var i1 = indices[i + offsets[k][0]];
            var i2 = indices[i + offsets[k][1]];
            var id = i1 > i2 ? i2 << 16 | i1 : i1 << 16 | i2;
            if (lineIDs[id] === undefined) {
              lineIDs[id] = 0;
              lines.push(i1, i2);
            }
          }
        }
        return lines;
      }
      function invWinding(indices) {
        var newIB = [];
        for (var i = 0; i < indices.length; i += 3) {
          newIB.push(indices[i], indices[i + 2], indices[i + 1]);
        }
        return newIB;
      }
      function toWavefrontOBJ(primitive, scale) {
        if (scale === void 0) {
          scale = 1;
        }
        if (!primitive.indices || !primitive.uvs || !primitive.normals || primitive.primitiveMode !== undefined && primitive.primitiveMode !== PrimitiveMode.TRIANGLE_LIST) {
          return '';
        }
        var v = primitive.positions;
        var t = primitive.uvs;
        var n = primitive.normals;
        var IB = primitive.indices;
        var V = function V(i) {
          return IB[i] + 1 + "/" + (IB[i] + 1) + "/" + (IB[i] + 1);
        };
        var content = '';
        for (var i = 0; i < v.length; i += 3) {
          content += "v " + v[i] * scale + " " + v[i + 1] * scale + " " + v[i + 2] * scale + "\n";
        }
        for (var _i = 0; _i < t.length; _i += 2) {
          content += "vt " + t[_i] + " " + t[_i + 1] + "\n";
        }
        for (var _i2 = 0; _i2 < n.length; _i2 += 3) {
          content += "vn " + n[_i2] + " " + n[_i2 + 1] + " " + n[_i2 + 2] + "\n";
        }
        for (var _i3 = 0; _i3 < IB.length; _i3 += 3) {
          content += "f " + V(_i3) + " " + V(_i3 + 1) + " " + V(_i3 + 2) + "\n";
        }
        return content;
      }
      function normals(positions, nms, length) {
        if (length === void 0) {
          length = 1;
        }
        var verts = new Array(2 * positions.length);
        for (var i = 0; i < positions.length / 3; ++i) {
          var i3 = 3 * i;
          var i6 = 6 * i;
          verts[i6 + 0] = positions[i3 + 0];
          verts[i6 + 1] = positions[i3 + 1];
          verts[i6 + 2] = positions[i3 + 2];
          verts[i6 + 3] = positions[i3 + 0] + nms[i3 + 0] * length;
          verts[i6 + 4] = positions[i3 + 1] + nms[i3 + 1] * length;
          verts[i6 + 5] = positions[i3 + 2] + nms[i3 + 2] * length;
        }
        return verts;
      }

      function applyDefaultGeometryOptions(options) {
        options = options || {};
        if (options.includeNormal === undefined) {
          options.includeNormal = true;
        }
        if (options.includeUV === undefined) {
          options.includeUV = true;
        }
        return options;
      }

      function box(options) {
        options = options || {};
        var ws = options.widthSegments || 1;
        var hs = options.heightSegments || 1;
        var ls = options.lengthSegments || 1;
        var hw = (options.width || 1) / 2;
        var hh = (options.height || 1) / 2;
        var hl = (options.length || 1) / 2;
        var corners = [Vec3.set(c0, -hw, -hh, hl), Vec3.set(c1, hw, -hh, hl), Vec3.set(c2, hw, hh, hl), Vec3.set(c3, -hw, hh, hl), Vec3.set(c4, hw, -hh, -hl), Vec3.set(c5, -hw, -hh, -hl), Vec3.set(c6, -hw, hh, -hl), Vec3.set(c7, hw, hh, -hl)];
        var faceAxes = [[2, 3, 1], [4, 5, 7], [7, 6, 2], [1, 0, 4], [1, 4, 2], [5, 0, 6]];
        var faceNormals = [[0, 0, 1], [0, 0, -1], [0, 1, 0], [0, -1, 0], [1, 0, 0], [-1, 0, 0]];
        var faceTangents = [[-1, 0, 0, 1], [-1, 0, 0, 1], [-1, 0, 0, 1], [-1, 0, 0, 1], [0, 0, -1, 1], [0, 0, 1, 1]];
        var positions = [];
        var normals = [];
        var uvs = [];
        var tangents = [];
        var indices = [];
        var minPos = new Vec3(-hw, -hh, -hl);
        var maxPos = new Vec3(hw, hh, hl);
        var boundingRadius = Math.sqrt(hw * hw + hh * hh + hl * hl);
        function _buildPlane(side, uSegments, vSegments) {
          var u;
          var v;
          var ix;
          var iy;
          var offset = positions.length / 3;
          var faceAxe = faceAxes[side];
          var faceNormal = faceNormals[side];
          var faceTangent = faceTangents[side];
          for (iy = 0; iy <= vSegments; iy++) {
            for (ix = 0; ix <= uSegments; ix++) {
              u = ix / uSegments;
              v = iy / vSegments;
              Vec3.lerp(temp1$3, corners[faceAxe[0]], corners[faceAxe[1]], u);
              Vec3.lerp(temp2$3, corners[faceAxe[0]], corners[faceAxe[2]], v);
              Vec3.subtract(temp3$1, temp2$3, corners[faceAxe[0]]);
              Vec3.add(r$1, temp1$3, temp3$1);
              positions.push(r$1.x, r$1.y, r$1.z);
              normals.push(faceNormal[0], faceNormal[1], faceNormal[2]);
              uvs.push(u, v);
              tangents.push(faceTangent[0], faceTangent[1], faceTangent[2], faceTangent[3]);
              if (ix < uSegments && iy < vSegments) {
                var useg1 = uSegments + 1;
                var a = ix + iy * useg1;
                var b = ix + (iy + 1) * useg1;
                var c = ix + 1 + (iy + 1) * useg1;
                var d = ix + 1 + iy * useg1;
                indices.push(offset + a, offset + d, offset + b);
                indices.push(offset + b, offset + d, offset + c);
              }
            }
          }
        }
        _buildPlane(0, ws, hs);
        _buildPlane(4, ls, hs);
        _buildPlane(1, ws, hs);
        _buildPlane(5, ls, hs);
        _buildPlane(3, ws, ls);
        _buildPlane(2, ws, ls);
        return {
          positions: positions,
          normals: normals,
          uvs: uvs,
          tangents: tangents,
          indices: indices,
          minPos: minPos,
          maxPos: maxPos,
          boundingRadius: boundingRadius
        };
      }
      var temp1$3 = new Vec3();
      var temp2$3 = new Vec3();
      var temp3$1 = new Vec3();
      var r$1 = new Vec3();
      var c0 = new Vec3();
      var c1 = new Vec3();
      var c2 = new Vec3();
      var c3 = new Vec3();
      var c4 = new Vec3();
      var c5 = new Vec3();
      var c6 = new Vec3();
      var c7 = new Vec3();

      var temp1$2 = new Vec3(0, 0, 0);
      var temp2$2 = new Vec3(0, 0, 0);
      function cylinder(radiusTop, radiusBottom, height, opts) {
        if (radiusTop === void 0) {
          radiusTop = 0.5;
        }
        if (radiusBottom === void 0) {
          radiusBottom = 0.5;
        }
        if (height === void 0) {
          height = 2;
        }
        if (opts === void 0) {
          opts = {};
        }
        var halfHeight = height * 0.5;
        var radialSegments = opts.radialSegments || 32;
        var heightSegments = opts.heightSegments || 1;
        var capped = opts.capped !== undefined ? opts.capped : true;
        var arc = opts.arc || 2.0 * Math.PI;
        var cntCap = 0;
        if (!capped) {
          if (radiusTop > 0) {
            cntCap++;
          }
          if (radiusBottom > 0) {
            cntCap++;
          }
        }
        var vertCount = (radialSegments + 1) * (heightSegments + 1);
        if (capped) {
          vertCount += (radialSegments + 1) * cntCap + radialSegments * cntCap;
        }
        var indexCount = radialSegments * heightSegments * 2 * 3;
        if (capped) {
          indexCount += radialSegments * cntCap * 3;
        }
        var indices = new Array(indexCount);
        var positions = new Array(vertCount * 3);
        var normals = new Array(vertCount * 3);
        var uvs = new Array(vertCount * 2);
        var maxRadius = Math.max(radiusTop, radiusBottom);
        var minPos = new Vec3(-maxRadius, -halfHeight, -maxRadius);
        var maxPos = new Vec3(maxRadius, halfHeight, maxRadius);
        var boundingRadius = Math.sqrt(maxRadius * maxRadius + halfHeight * halfHeight);
        var index = 0;
        var indexOffset = 0;
        generateTorso();
        if (capped) {
          if (radiusBottom > 0) {
            generateCap(false);
          }
          if (radiusTop > 0) {
            generateCap(true);
          }
        }
        return {
          positions: positions,
          normals: normals,
          uvs: uvs,
          indices: indices,
          minPos: minPos,
          maxPos: maxPos,
          boundingRadius: boundingRadius
        };
        function generateTorso() {
          var indexArray = [];
          var r = radiusTop - radiusBottom;
          var slope = r * r / height * Math.sign(r);
          for (var y = 0; y <= heightSegments; y++) {
            var indexRow = [];
            var v = y / heightSegments;
            var radius = v * r + radiusBottom;
            for (var x = 0; x <= radialSegments; ++x) {
              var u = x / radialSegments;
              var theta = u * arc;
              var sinTheta = Math.sin(theta);
              var cosTheta = Math.cos(theta);
              positions[3 * index] = radius * sinTheta;
              positions[3 * index + 1] = v * height - halfHeight;
              positions[3 * index + 2] = radius * cosTheta;
              Vec3.normalize(temp1$2, Vec3.set(temp2$2, sinTheta, -slope, cosTheta));
              normals[3 * index] = temp1$2.x;
              normals[3 * index + 1] = temp1$2.y;
              normals[3 * index + 2] = temp1$2.z;
              uvs[2 * index] = (1 - u) * 2 % 1;
              uvs[2 * index + 1] = v;
              indexRow.push(index);
              ++index;
            }
            indexArray.push(indexRow);
          }
          for (var _y = 0; _y < heightSegments; ++_y) {
            for (var _x = 0; _x < radialSegments; ++_x) {
              var i1 = indexArray[_y][_x];
              var i2 = indexArray[_y + 1][_x];
              var i3 = indexArray[_y + 1][_x + 1];
              var i4 = indexArray[_y][_x + 1];
              indices[indexOffset] = i1;
              ++indexOffset;
              indices[indexOffset] = i4;
              ++indexOffset;
              indices[indexOffset] = i2;
              ++indexOffset;
              indices[indexOffset] = i4;
              ++indexOffset;
              indices[indexOffset] = i3;
              ++indexOffset;
              indices[indexOffset] = i2;
              ++indexOffset;
            }
          }
        }
        function generateCap(top) {
          var radius = top ? radiusTop : radiusBottom;
          var sign = top ? 1 : -1;
          var centerIndexStart = index;
          for (var x = 1; x <= radialSegments; ++x) {
            positions[3 * index] = 0;
            positions[3 * index + 1] = halfHeight * sign;
            positions[3 * index + 2] = 0;
            normals[3 * index] = 0;
            normals[3 * index + 1] = sign;
            normals[3 * index + 2] = 0;
            uvs[2 * index] = 0.5;
            uvs[2 * index + 1] = 0.5;
            ++index;
          }
          var centerIndexEnd = index;
          for (var _x2 = 0; _x2 <= radialSegments; ++_x2) {
            var u = _x2 / radialSegments;
            var theta = u * arc;
            var cosTheta = Math.cos(theta);
            var sinTheta = Math.sin(theta);
            positions[3 * index] = radius * sinTheta;
            positions[3 * index + 1] = halfHeight * sign;
            positions[3 * index + 2] = radius * cosTheta;
            normals[3 * index] = 0;
            normals[3 * index + 1] = sign;
            normals[3 * index + 2] = 0;
            uvs[2 * index] = 0.5 - sinTheta * 0.5 * sign;
            uvs[2 * index + 1] = 0.5 + cosTheta * 0.5;
            ++index;
          }
          for (var _x3 = 0; _x3 < radialSegments; ++_x3) {
            var c = centerIndexStart + _x3;
            var i = centerIndexEnd + _x3;
            if (top) {
              indices[indexOffset] = i + 1;
              ++indexOffset;
              indices[indexOffset] = c;
              ++indexOffset;
              indices[indexOffset] = i;
              ++indexOffset;
            } else {
              indices[indexOffset] = c;
              ++indexOffset;
              indices[indexOffset] = i + 1;
              ++indexOffset;
              indices[indexOffset] = i;
              ++indexOffset;
            }
          }
        }
      }

      function cone(radius, height, opts) {
        if (radius === void 0) {
          radius = 0.5;
        }
        if (height === void 0) {
          height = 1;
        }
        if (opts === void 0) {
          opts = {};
        }
        return cylinder(0, radius, height, opts);
      }

      function applyDefaultPlaneOptions(options) {
        options = applyDefaultGeometryOptions(options);
        options.width = options.width || 10;
        options.length = options.length || 10;
        options.widthSegments = options.widthSegments || 10;
        options.lengthSegments = options.lengthSegments || 10;
        return options;
      }
      var temp1$1 = new Vec3(0, 0, 0);
      var temp2$1 = new Vec3(0, 0, 0);
      var temp3 = new Vec3(0, 0, 0);
      var r = new Vec3(0, 0, 0);
      var c00 = new Vec3(0, 0, 0);
      var c10 = new Vec3(0, 0, 0);
      var c01 = new Vec3(0, 0, 0);
      function plane(options) {
        var normalizedOptions = applyDefaultPlaneOptions(options);
        var width = normalizedOptions.width,
          length = normalizedOptions.length,
          uSegments = normalizedOptions.widthSegments,
          vSegments = normalizedOptions.lengthSegments;
        var hw = width * 0.5;
        var hl = length * 0.5;
        var positions = [];
        var uvs = [];
        var indices = [];
        var minPos = new Vec3(-hw, 0, -hl);
        var maxPos = new Vec3(hw, 0, hl);
        var boundingRadius = Math.sqrt(width * width + length * length);
        Vec3.set(c00, -hw, 0, hl);
        Vec3.set(c10, hw, 0, hl);
        Vec3.set(c01, -hw, 0, -hl);
        for (var y = 0; y <= vSegments; y++) {
          for (var x = 0; x <= uSegments; x++) {
            var u = x / uSegments;
            var v = y / vSegments;
            Vec3.lerp(temp1$1, c00, c10, u);
            Vec3.lerp(temp2$1, c00, c01, v);
            Vec3.subtract(temp3, temp2$1, c00);
            Vec3.add(r, temp1$1, temp3);
            positions.push(r.x, r.y, r.z);
            if (normalizedOptions.includeUV) {
              uvs.push(u, v);
            }
            if (x < uSegments && y < vSegments) {
              var useg1 = uSegments + 1;
              var a = x + y * useg1;
              var b = x + (y + 1) * useg1;
              var c = x + 1 + (y + 1) * useg1;
              var d = x + 1 + y * useg1;
              indices.push(a, d, b);
              indices.push(d, c, b);
            }
          }
        }
        var result = {
          positions: positions,
          indices: indices,
          minPos: minPos,
          maxPos: maxPos,
          boundingRadius: boundingRadius
        };
        if (normalizedOptions.includeNormal) {
          var nVertex = (vSegments + 1) * (uSegments + 1);
          var normals = new Array(3 * nVertex);
          result.normals = normals;
          for (var i = 0; i < nVertex; ++i) {
            normals[i * 3 + 0] = 0;
            normals[i * 3 + 1] = 1;
            normals[i * 3 + 2] = 0;
          }
        }
        if (normalizedOptions.includeUV) {
          result.uvs = uvs;
        }
        return result;
      }

      function quad(options) {
        var normalizedOptions = applyDefaultGeometryOptions(options);
        var result = {
          positions: [-0.5, -0.5, 0, -0.5, 0.5, 0, 0.5, 0.5, 0, 0.5, -0.5, 0],
          indices: [0, 3, 1, 3, 2, 1],
          minPos: {
            x: -0.5,
            y: -0.5,
            z: 0
          },
          maxPos: {
            x: 0.5,
            y: 0.5,
            z: 0
          },
          boundingRadius: Math.sqrt(0.5 * 0.5 + 0.5 * 0.5)
        };
        if (normalizedOptions.includeNormal !== false) {
          result.normals = [0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1];
        }
        if (normalizedOptions.includeUV !== false) {
          result.uvs = [0, 0, 0, 1, 1, 1, 1, 0];
        }
        return result;
      }

      function sphere(radius, opts) {
        if (radius === void 0) {
          radius = 0.5;
        }
        if (opts === void 0) {
          opts = {};
        }
        var segments = opts.segments !== undefined ? opts.segments : 32;
        var positions = [];
        var normals = [];
        var uvs = [];
        var indices = [];
        var minPos = new Vec3(-radius, -radius, -radius);
        var maxPos = new Vec3(radius, radius, radius);
        var boundingRadius = radius;
        for (var lat = 0; lat <= segments; ++lat) {
          var theta = lat * Math.PI / segments;
          var sinTheta = Math.sin(theta);
          var cosTheta = -Math.cos(theta);
          for (var lon = 0; lon <= segments; ++lon) {
            var phi = lon * 2 * Math.PI / segments - Math.PI / 2.0;
            var sinPhi = Math.sin(phi);
            var cosPhi = Math.cos(phi);
            var x = sinPhi * sinTheta;
            var y = cosTheta;
            var z = cosPhi * sinTheta;
            var u = lon / segments;
            var v = lat / segments;
            positions.push(x * radius, y * radius, z * radius);
            normals.push(x, y, z);
            uvs.push(u, v);
            if (lat < segments && lon < segments) {
              var seg1 = segments + 1;
              var a = seg1 * lat + lon;
              var b = seg1 * (lat + 1) + lon;
              var c = seg1 * (lat + 1) + lon + 1;
              var d = seg1 * lat + lon + 1;
              indices.push(a, d, b);
              indices.push(d, c, b);
            }
          }
        }
        return {
          positions: positions,
          indices: indices,
          normals: normals,
          uvs: uvs,
          minPos: minPos,
          maxPos: maxPos,
          boundingRadius: boundingRadius
        };
      }

      function torus(radius, tube, opts) {
        if (radius === void 0) {
          radius = 0.4;
        }
        if (tube === void 0) {
          tube = 0.1;
        }
        if (opts === void 0) {
          opts = {};
        }
        var radialSegments = opts.radialSegments || 32;
        var tubularSegments = opts.tubularSegments || 32;
        var arc = opts.arc || 2.0 * Math.PI;
        var positions = [];
        var normals = [];
        var uvs = [];
        var indices = [];
        var minPos = new Vec3(-radius - tube, -tube, -radius - tube);
        var maxPos = new Vec3(radius + tube, tube, radius + tube);
        var boundingRadius = radius + tube;
        for (var j = 0; j <= radialSegments; j++) {
          for (var i = 0; i <= tubularSegments; i++) {
            var u = i / tubularSegments;
            var v = j / radialSegments;
            var u1 = u * arc;
            var v1 = v * Math.PI * 2;
            var x = (radius + tube * Math.cos(v1)) * Math.sin(u1);
            var y = tube * Math.sin(v1);
            var z = (radius + tube * Math.cos(v1)) * Math.cos(u1);
            var nx = Math.sin(u1) * Math.cos(v1);
            var ny = Math.sin(v1);
            var nz = Math.cos(u1) * Math.cos(v1);
            positions.push(x, y, z);
            normals.push(nx, ny, nz);
            uvs.push(u, v);
            if (i < tubularSegments && j < radialSegments) {
              var seg1 = tubularSegments + 1;
              var a = seg1 * j + i;
              var b = seg1 * (j + 1) + i;
              var c = seg1 * (j + 1) + i + 1;
              var d = seg1 * j + i + 1;
              indices.push(a, d, b);
              indices.push(d, c, b);
            }
          }
        }
        return {
          positions: positions,
          normals: normals,
          uvs: uvs,
          indices: indices,
          minPos: minPos,
          maxPos: maxPos,
          boundingRadius: boundingRadius
        };
      }

      var temp1 = new Vec3(0, 0, 0);
      var temp2 = new Vec3(0, 0, 0);
      function capsule(radiusTop, radiusBottom, height, opts) {
        if (radiusTop === void 0) {
          radiusTop = 0.5;
        }
        if (radiusBottom === void 0) {
          radiusBottom = 0.5;
        }
        if (height === void 0) {
          height = 2;
        }
        if (opts === void 0) {
          opts = {};
        }
        var torsoHeight = height - radiusTop - radiusBottom;
        var sides = opts.sides || 32;
        var heightSegments = opts.heightSegments || 32;
        var bottomProp = radiusBottom / height;
        var torProp = torsoHeight / height;
        var topProp = radiusTop / height;
        var bottomSegments = Math.floor(heightSegments * bottomProp);
        var topSegments = Math.floor(heightSegments * topProp);
        var torSegments = Math.floor(heightSegments * torProp);
        var topOffset = torsoHeight + radiusBottom - height / 2;
        var torOffset = radiusBottom - height / 2;
        var bottomOffset = radiusBottom - height / 2;
        var arc = opts.arc || 2.0 * Math.PI;
        var positions = [];
        var normals = [];
        var uvs = [];
        var indices = [];
        var maxRadius = Math.max(radiusTop, radiusBottom);
        var minPos = new Vec3(-maxRadius, -height / 2, -maxRadius);
        var maxPos = new Vec3(maxRadius, height / 2, maxRadius);
        var boundingRadius = height / 2;
        var index = 0;
        var indexArray = [];
        generateBottom();
        generateTorso();
        generateTop();
        return {
          positions: positions,
          normals: normals,
          uvs: uvs,
          indices: indices,
          minPos: minPos,
          maxPos: maxPos,
          boundingRadius: boundingRadius
        };
        function generateTorso() {
          var slope = (radiusTop - radiusBottom) / torsoHeight;
          for (var y = 0; y <= torSegments; y++) {
            var indexRow = [];
            var lat = y / torSegments;
            var radius = lat * (radiusTop - radiusBottom) + radiusBottom;
            for (var x = 0; x <= sides; ++x) {
              var u = x / sides;
              var v = lat * torProp + bottomProp;
              var theta = u * arc - arc / 4;
              var sinTheta = Math.sin(theta);
              var cosTheta = Math.cos(theta);
              positions.push(radius * sinTheta);
              positions.push(lat * torsoHeight + torOffset);
              positions.push(radius * cosTheta);
              Vec3.normalize(temp1, Vec3.set(temp2, sinTheta, -slope, cosTheta));
              normals.push(temp1.x);
              normals.push(temp1.y);
              normals.push(temp1.z);
              uvs.push(u, v);
              indexRow.push(index);
              ++index;
            }
            indexArray.push(indexRow);
          }
          for (var _y = 0; _y < torSegments; ++_y) {
            for (var _x = 0; _x < sides; ++_x) {
              var i1 = indexArray[_y][_x];
              var i2 = indexArray[_y + 1][_x];
              var i3 = indexArray[_y + 1][_x + 1];
              var i4 = indexArray[_y][_x + 1];
              indices.push(i1);
              indices.push(i4);
              indices.push(i2);
              indices.push(i4);
              indices.push(i3);
              indices.push(i2);
            }
          }
        }
        function generateBottom() {
          for (var lat = 0; lat <= bottomSegments; ++lat) {
            var theta = lat * Math.PI / bottomSegments / 2;
            var sinTheta = Math.sin(theta);
            var cosTheta = -Math.cos(theta);
            for (var lon = 0; lon <= sides; ++lon) {
              var phi = lon * 2 * Math.PI / sides - Math.PI / 2.0;
              var sinPhi = Math.sin(phi);
              var cosPhi = Math.cos(phi);
              var x = sinPhi * sinTheta;
              var y = cosTheta;
              var z = cosPhi * sinTheta;
              var u = lon / sides;
              var v = lat / heightSegments;
              positions.push(x * radiusBottom, y * radiusBottom + bottomOffset, z * radiusBottom);
              normals.push(x, y, z);
              uvs.push(u, v);
              if (lat < bottomSegments && lon < sides) {
                var seg1 = sides + 1;
                var a = seg1 * lat + lon;
                var b = seg1 * (lat + 1) + lon;
                var c = seg1 * (lat + 1) + lon + 1;
                var d = seg1 * lat + lon + 1;
                indices.push(a, d, b);
                indices.push(d, c, b);
              }
              ++index;
            }
          }
        }
        function generateTop() {
          for (var lat = 0; lat <= topSegments; ++lat) {
            var theta = lat * Math.PI / topSegments / 2 + Math.PI / 2;
            var sinTheta = Math.sin(theta);
            var cosTheta = -Math.cos(theta);
            for (var lon = 0; lon <= sides; ++lon) {
              var phi = lon * 2 * Math.PI / sides - Math.PI / 2.0;
              var sinPhi = Math.sin(phi);
              var cosPhi = Math.cos(phi);
              var x = sinPhi * sinTheta;
              var y = cosTheta;
              var z = cosPhi * sinTheta;
              var u = lon / sides;
              var v = lat / heightSegments + (1 - topProp);
              positions.push(x * radiusTop, y * radiusTop + topOffset, z * radiusTop);
              normals.push(x, y, z);
              uvs.push(u, v);
              if (lat < topSegments && lon < sides) {
                var seg1 = sides + 1;
                var a = seg1 * lat + lon + indexArray[torSegments][sides] + 1;
                var b = seg1 * (lat + 1) + lon + indexArray[torSegments][sides] + 1;
                var c = seg1 * (lat + 1) + lon + 1 + indexArray[torSegments][sides] + 1;
                var d = seg1 * lat + lon + 1 + indexArray[torSegments][sides] + 1;
                indices.push(a, d, b);
                indices.push(d, c, b);
              }
            }
          }
        }
      }

      function applyDefaultCircleOptions(options) {
        options = applyDefaultGeometryOptions(options);
        options.segments = 64;
        return options;
      }
      function circle(options) {
        var normalizedOptions = applyDefaultCircleOptions(options);
        var segments = normalizedOptions.segments;
        var positions = new Array(3 * (segments + 1));
        positions[0] = 0;
        positions[1] = 0;
        positions[2] = 0;
        var indices = new Array(1 + segments * 2);
        indices[0] = 0;
        var step = Math.PI * 2 / segments;
        for (var iSegment = 0; iSegment < segments; ++iSegment) {
          var angle = step * iSegment;
          var x = Math.cos(angle);
          var y = Math.sin(angle);
          var p = (iSegment + 1) * 3;
          positions[p + 0] = x;
          positions[p + 1] = y;
          positions[p + 2] = 0;
          var i = iSegment * 2;
          indices[1 + i] = iSegment + 1;
          indices[1 + (i + 1)] = iSegment + 2;
        }
        if (segments > 0) {
          indices[indices.length - 1] = 1;
        }
        var result = {
          positions: positions,
          indices: indices,
          minPos: {
            x: 1,
            y: 1,
            z: 0
          },
          maxPos: {
            x: -1,
            y: -1,
            z: 0
          },
          boundingRadius: 1,
          primitiveMode: PrimitiveMode.TRIANGLE_FAN
        };
        return result;
      }

      function translate(geometry, offset) {
        var x = offset.x || 0;
        var y = offset.y || 0;
        var z = offset.z || 0;
        var nVertex = Math.floor(geometry.positions.length / 3);
        for (var iVertex = 0; iVertex < nVertex; ++iVertex) {
          var iX = iVertex * 3;
          var iY = iVertex * 3 + 1;
          var iZ = iVertex * 3 + 2;
          geometry.positions[iX] += x;
          geometry.positions[iY] += y;
          geometry.positions[iZ] += z;
        }
        if (geometry.minPos) {
          geometry.minPos.x += x;
          geometry.minPos.y += y;
          geometry.minPos.z += z;
        }
        if (geometry.maxPos) {
          geometry.maxPos.x += x;
          geometry.maxPos.y += y;
          geometry.maxPos.z += z;
        }
        return geometry;
      }
      function scale(geometry, value) {
        var _value$x, _value$y, _value$z;
        var x = (_value$x = value.x) !== null && _value$x !== void 0 ? _value$x : 1.0;
        var y = (_value$y = value.y) !== null && _value$y !== void 0 ? _value$y : 1.0;
        var z = (_value$z = value.z) !== null && _value$z !== void 0 ? _value$z : 1.0;
        var nVertex = Math.floor(geometry.positions.length / 3);
        for (var iVertex = 0; iVertex < nVertex; ++iVertex) {
          var iX = iVertex * 3;
          var iY = iVertex * 3 + 1;
          var iZ = iVertex * 3 + 2;
          geometry.positions[iX] *= x;
          geometry.positions[iY] *= y;
          geometry.positions[iZ] *= z;
        }
        var minPos = geometry.minPos,
          maxPos = geometry.maxPos;
        if (minPos) {
          minPos.x *= x;
          minPos.y *= y;
          minPos.z *= z;
        }
        if (maxPos) {
          maxPos.x *= x;
          maxPos.y *= y;
          maxPos.z *= z;
        }
        if (minPos && maxPos) {
          if (x < 0) {
            var tmp = minPos.x;
            minPos.x = maxPos.x;
            maxPos.x = tmp;
          }
          if (y < 0) {
            var _tmp = minPos.y;
            minPos.y = maxPos.y;
            maxPos.y = _tmp;
          }
          if (z < 0) {
            var _tmp2 = minPos.z;
            minPos.z = maxPos.z;
            maxPos.z = _tmp2;
          }
        }
        if (typeof geometry.boundingRadius !== 'undefined') {
          geometry.boundingRadius *= Math.max(Math.max(Math.abs(x), Math.abs(y)), Math.abs(z));
        }
        return geometry;
      }
      function wireframed(geometry) {
        var indices = geometry.indices;
        if (!indices) {
          return geometry;
        }
        if (geometry.primitiveMode && geometry.primitiveMode !== PrimitiveMode.TRIANGLE_LIST) {
          return geometry;
        }
        var offsets = [[0, 1], [1, 2], [2, 0]];
        var lines = [];
        var lineIDs = {};
        for (var i = 0; i < indices.length; i += 3) {
          for (var k = 0; k < 3; ++k) {
            var i1 = indices[i + offsets[k][0]];
            var i2 = indices[i + offsets[k][1]];
            var id = i1 > i2 ? i2 << 16 | i1 : i1 << 16 | i2;
            if (lineIDs[id] === undefined) {
              lineIDs[id] = 0;
              lines.push(i1, i2);
            }
          }
        }
        geometry.indices = lines;
        geometry.primitiveMode = PrimitiveMode.LINE_LIST;
        return geometry;
      }

      var primitives = /*#__PURE__*/Object.freeze({
        __proto__: null,
        box: box,
        cone: cone,
        cylinder: cylinder,
        plane: plane,
        quad: quad,
        sphere: sphere,
        torus: torus,
        capsule: capsule,
        circle: circle,
        translate: translate,
        scale: scale,
        wireframed: wireframed,
        wireframe: wireframe,
        invWinding: invWinding,
        toWavefrontOBJ: toWavefrontOBJ,
        normals: normals,
        applyDefaultGeometryOptions: applyDefaultGeometryOptions
      });
      exports('f7', primitives);

      function setWrap(object, wrapper) {
        object.__cc_wrapper__ = wrapper;
      }
      function getWrap(object) {
        return object.__cc_wrapper__;
      }
      function maxComponent(v) {
        return Math.max(v.x, Math.max(v.y, v.z));
      }
      var VEC3_0 = new Vec3();
      var TriggerEventObject$1 = {
        type: 'onTriggerEnter',
        selfCollider: null,
        otherCollider: null,
        impl: null
      };
      var CharacterTriggerEventObject = {
        type: 'onControllerTriggerEnter',
        collider: null,
        characterController: null,
        impl: null
      };
      var CollisionEventObject$1 = {
        type: 'onCollisionEnter',
        selfCollider: null,
        otherCollider: null,
        contacts: [],
        impl: null
      };
      function shrinkPositions(buffer) {
        var pos = [];
        if (buffer.length >= 3) {
          pos[0] = buffer[0], pos[1] = buffer[1], pos[2] = buffer[2];
          var len = buffer.length;
          for (var i = 3; i < len; i += 3) {
            var p0 = buffer[i];
            var p1 = buffer[i + 1];
            var p2 = buffer[i + 2];
            var len2 = pos.length;
            var isNew = true;
            for (var j = 0; j < len2; j += 3) {
              if (equals$1(p0, pos[j]) && equals$1(p1, pos[j + 1]) && equals$1(p2, pos[j + 2])) {
                isNew = false;
                break;
              }
            }
            if (isNew) {
              pos.push(p0);
              pos.push(p1);
              pos.push(p2);
            }
          }
        }
        return pos;
      }
      function absolute(v) {
        v.x = Math.abs(v.x);
        v.y = Math.abs(v.y);
        v.z = Math.abs(v.z);
        return v;
      }

      var util = /*#__PURE__*/Object.freeze({
        __proto__: null,
        setWrap: setWrap,
        getWrap: getWrap,
        maxComponent: maxComponent,
        VEC3_0: VEC3_0,
        TriggerEventObject: TriggerEventObject$1,
        CharacterTriggerEventObject: CharacterTriggerEventObject,
        CollisionEventObject: CollisionEventObject$1,
        shrinkPositions: shrinkPositions,
        absolute: absolute,
        cylinder: cylinder
      });

      var _dec$1P, _dec2$1l, _dec3$W, _dec4$H, _dec5$A, _dec6$k, _dec7$f, _dec8$a, _dec9$9, _class$1O, _class2$1C, _initializer$1t, _initializer2$19, _initializer3$K, _initializer4$z, _initializer5$o, _initializer6$i, _initializer7$e, _initializer8$d, _initializer9$c, _initializer10$b, _class3$q;
      var ProbeResolution;
      (function (ProbeResolution) {
        ProbeResolution[ProbeResolution["Low_256x256"] = 256] = "Low_256x256";
        ProbeResolution[ProbeResolution["Medium_512x512"] = 512] = "Medium_512x512";
        ProbeResolution[ProbeResolution["High_768x768"] = 768] = "High_768x768";
      })(ProbeResolution || (ProbeResolution = {}));
      var ReflectionProbe = exports('af', (_dec$1P = ccclass$n('cc.ReflectionProbe'), _dec2$1l = type$7(Vec3), _dec3$W = type$7(Enum(ProbeType)), _dec4$H = type$7(Enum(ProbeResolution)), _dec5$A = type$7(Enum(ProbeClearFlag)), _dec6$k = type$7(Color$1), _dec7$f = type$7(Layers.BitMask), _dec8$a = type$7(Camera), _dec9$9 = type$7(CCBoolean), _dec$1P(_class$1O = (_class2$1C = (_class3$q = function (_Component) {
        _inheritsLoose(ReflectionProbe, _Component);
        function ReflectionProbe() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Component.call.apply(_Component, [this].concat(args)) || this;
          _this._lastSize = new Vec3();
          _this._resolution = _initializer$1t && _initializer$1t();
          _this._clearFlag = _initializer2$19 && _initializer2$19();
          _this._backgroundColor = _initializer3$K && _initializer3$K();
          _this._visibility = _initializer4$z && _initializer4$z();
          _this._probeType = _initializer5$o && _initializer5$o();
          _this._cubemap = _initializer6$i && _initializer6$i();
          _this._size = _initializer7$e && _initializer7$e();
          _this._sourceCamera = _initializer8$d && _initializer8$d();
          _this._probeId = _initializer9$c && _initializer9$c();
          _this._fastBake = _initializer10$b && _initializer10$b();
          _this._probe = null;
          _this._previewSphere = null;
          _this._previewPlane = null;
          _this._sourceCameraPos = new Vec3(0, 0, 0);
          _this._position = new Vec3(0, 0, 0);
          return _this;
        }
        var _proto = ReflectionProbe.prototype;
        _proto.onLoad = function onLoad() {
          this._createProbe();
        };
        _proto.onEnable = function onEnable() {
          if (this._probe) {
            var probe = ReflectionProbeManager.probeManager.getProbeById(this._probeId);
            if (probe !== null && probe !== this._probe) {
              this._probeId = ReflectionProbeManager.probeManager.getNewReflectionProbeId();
              this._probe.updateProbeId(this._probeId);
            }
            ReflectionProbeManager.probeManager.register(this._probe);
            ReflectionProbeManager.probeManager.onUpdateProbes();
            this._probe.enable();
          }
        };
        _proto.onDisable = function onDisable() {
          if (this._probe) {
            ReflectionProbeManager.probeManager.unregister(this._probe);
            this._probe.disable();
          }
        };
        _proto.start = function start() {
          if (this._sourceCamera && this.probeType === ProbeType.PLANAR) {
            this.probe.renderPlanarReflection(this.sourceCamera.camera);
            ReflectionProbeManager.probeManager.filterModelsForPlanarReflection();
          }
          ReflectionProbeManager.probeManager.updateProbeData();
          this._position = this.node.getWorldPosition().clone();
        };
        _proto.onDestroy = function onDestroy() {
          if (this.probe) {
            this.probe.destroy();
          }
        };
        _proto.update = function update(dt) {
          if (!this.probe) return;
          if (this.probeType === ProbeType.PLANAR && this.sourceCamera) {
            if (this.sourceCamera.node.hasChangedFlags & TransformBit.TRS || !this._sourceCameraPos.equals(this.sourceCamera.node.getWorldPosition())) {
              this._sourceCameraPos = this.sourceCamera.node.getWorldPosition();
              this.probe.renderPlanarReflection(this.sourceCamera.camera);
            }
          }
          if (this.node.hasChangedFlags & TransformBit.POSITION) {
            this.probe.updateBoundingBox();
            ReflectionProbeManager.probeManager.onUpdateProbes();
            ReflectionProbeManager.probeManager.updateProbeData();
          }
          {
            var worldPos = this.node.getWorldPosition();
            if (!this._position.equals(worldPos)) {
              this._position = worldPos;
              this.probe.updateBoundingBox();
              ReflectionProbeManager.probeManager.updateProbeData();
              ReflectionProbeManager.probeManager.updateProbeOfModels();
            }
          }
        };
        _proto.clearBakedCubemap = function clearBakedCubemap() {
          this.cubemap = null;
          ReflectionProbeManager.probeManager.updateBakedCubemap(this.probe);
          ReflectionProbeManager.probeManager.updatePreviewSphere(this.probe);
        };
        _proto._createProbe = function _createProbe() {
          if (this._probeId === -1 || ReflectionProbeManager.probeManager.exists(this._probeId)) {
            this._probeId = ReflectionProbeManager.probeManager.getNewReflectionProbeId();
          }
          this._probe = new ReflectionProbe$1(this._probeId);
          if (this._probe) {
            var cameraNode = new Node$1('ReflectionProbeCamera');
            cameraNode.hideFlags |= CCObject.Flags.DontSave | CCObject.Flags.HideInHierarchy;
            this.node.scene.addChild(cameraNode);
            this._probe.initialize(this.node, cameraNode);
            if (this.enabled) {
              ReflectionProbeManager.probeManager.register(this._probe);
            }
            this._probe.resolution = this._resolution;
            this._probe.clearFlag = this._clearFlag;
            this._probe.backgroundColor = this._backgroundColor;
            this._probe.visibility = this._visibility;
            this._probe.probeType = this._probeType;
            this._probe.size = this._size;
            this._probe.cubemap = this._cubemap;
          }
        };
        _createClass(ReflectionProbe, [{
          key: "size",
          get: function get() {
            return this._size;
          },
          set: function set(value) {
            this._size.set(value);
            absolute(this._size);
            this.probe.size = this._size;
            if (this.probe) {
              this.probe.updateBoundingBox();
              ReflectionProbeManager.probeManager.onUpdateProbes();
              ReflectionProbeManager.probeManager.updateProbeData();
              ReflectionProbeManager.probeManager.updateProbeOfModels();
            }
          }
        }, {
          key: "probeType",
          get: function get() {
            return this._probeType;
          },
          set: function set(value) {
            this.probe.probeType = value;
            if (value !== this._probeType) {
              var lastSize = this._size.clone();
              var lastSizeIsNoExist = Vec3.equals(this._lastSize, Vec3.ZERO);
              this._probeType = value;
              if (this._probeType === ProbeType.CUBE) {
                if (lastSizeIsNoExist) {
                  this._size.set(ReflectionProbe.DEFAULT_CUBE_SIZE);
                }
                this.probe.switchProbeType(value, null);
                ReflectionProbeManager.probeManager.clearPlanarReflectionMap(this.probe);
              } else {
                if (lastSizeIsNoExist) {
                  this._size.set(ReflectionProbe.DEFAULT_PLANER_SIZE);
                }
                if (!this._sourceCamera) {
                  warn('the reflection camera is invalid, please set the reflection camera');
                } else {
                  this.probe.switchProbeType(value, this._sourceCamera.camera);
                }
              }
              if (!lastSizeIsNoExist) {
                this._size.set(this._lastSize);
              }
              this._lastSize.set(lastSize);
              this.size = this._size;
            }
          }
        }, {
          key: "resolution",
          get: function get() {
            return this._resolution;
          },
          set: function set(value) {
            this._resolution = value;
            this.probe.resolution = value;
          }
        }, {
          key: "clearFlag",
          get: function get() {
            return this._clearFlag;
          },
          set: function set(value) {
            this._clearFlag = value;
            this.probe.clearFlag = this._clearFlag;
          }
        }, {
          key: "backgroundColor",
          get: function get() {
            return this._backgroundColor;
          },
          set: function set(val) {
            this._backgroundColor = val;
            this.probe.backgroundColor = this._backgroundColor;
          }
        }, {
          key: "visibility",
          get: function get() {
            return this._visibility;
          },
          set: function set(val) {
            this._visibility = val;
            this.probe.visibility = this._visibility;
          }
        }, {
          key: "sourceCamera",
          get: function get() {
            return this._sourceCamera;
          },
          set: function set(camera) {
            this._sourceCamera = camera;
            if (camera) {
              this.visibility = camera.visibility;
              this.clearFlag = camera.clearFlags;
              this.backgroundColor = camera.clearColor;
              if (this.probeType === ProbeType.PLANAR) {
                this.probe.switchProbeType(this.probeType, camera.camera);
              }
            }
          }
        }, {
          key: "fastBake",
          get: function get() {
            return this._fastBake;
          },
          set: function set(val) {
            this._fastBake = val;
          }
        }, {
          key: "cubemap",
          get: function get() {
            return this._cubemap;
          },
          set: function set(val) {
            this._cubemap = val;
            this.probe.cubemap = val;
            ReflectionProbeManager.probeManager.onUpdateProbes();
          }
        }, {
          key: "probe",
          get: function get() {
            return this._probe;
          }
        }, {
          key: "previewSphere",
          get: function get() {
            return this._previewSphere;
          },
          set: function set(val) {
            this._previewSphere = val;
            if (this.probe) {
              this.probe.previewSphere = val;
              if (this._previewSphere) {
                ReflectionProbeManager.probeManager.updatePreviewSphere(this.probe);
              }
            }
          }
        }, {
          key: "previewPlane",
          get: function get() {
            return this._previewPlane;
          },
          set: function set(val) {
            this._previewPlane = val;
            if (this.probe) {
              this.probe.previewPlane = val;
              if (this._previewPlane) {
                ReflectionProbeManager.probeManager.updatePreviewPlane(this.probe);
              }
            }
          }
        }]);
        return ReflectionProbe;
      }(Component), _class3$q.DEFAULT_CUBE_SIZE = new Vec3(1, 1, 1), _class3$q.DEFAULT_PLANER_SIZE = new Vec3(5, 0.5, 5), _class3$q), (_initializer$1t = applyDecoratedInitializer(_class2$1C.prototype, "_resolution", [serializable$j], function () {
        return 256;
      }), _initializer2$19 = applyDecoratedInitializer(_class2$1C.prototype, "_clearFlag", [serializable$j], function () {
        return ProbeClearFlag.SKYBOX;
      }), _initializer3$K = applyDecoratedInitializer(_class2$1C.prototype, "_backgroundColor", [serializable$j], function () {
        return new Color$1(0, 0, 0, 255);
      }), _initializer4$z = applyDecoratedInitializer(_class2$1C.prototype, "_visibility", [serializable$j], function () {
        return CAMERA_DEFAULT_MASK;
      }), _initializer5$o = applyDecoratedInitializer(_class2$1C.prototype, "_probeType", [serializable$j], function () {
        return ProbeType.CUBE;
      }), _initializer6$i = applyDecoratedInitializer(_class2$1C.prototype, "_cubemap", [serializable$j], function () {
        return null;
      }), _initializer7$e = applyDecoratedInitializer(_class2$1C.prototype, "_size", [serializable$j], function () {
        return new Vec3(1, 1, 1);
      }), _initializer8$d = applyDecoratedInitializer(_class2$1C.prototype, "_sourceCamera", [serializable$j], function () {
        return null;
      }), _initializer9$c = applyDecoratedInitializer(_class2$1C.prototype, "_probeId", [serializable$j], function () {
        return -1;
      }), _initializer10$b = applyDecoratedInitializer(_class2$1C.prototype, "_fastBake", [serializable$j], function () {
        return false;
      }), _applyDecoratedDescriptor(_class2$1C.prototype, "size", [_dec2$1l], Object.getOwnPropertyDescriptor(_class2$1C.prototype, "size"), _class2$1C.prototype), _applyDecoratedDescriptor(_class2$1C.prototype, "probeType", [_dec3$W], Object.getOwnPropertyDescriptor(_class2$1C.prototype, "probeType"), _class2$1C.prototype), _applyDecoratedDescriptor(_class2$1C.prototype, "resolution", [_dec4$H], Object.getOwnPropertyDescriptor(_class2$1C.prototype, "resolution"), _class2$1C.prototype), _applyDecoratedDescriptor(_class2$1C.prototype, "clearFlag", [_dec5$A], Object.getOwnPropertyDescriptor(_class2$1C.prototype, "clearFlag"), _class2$1C.prototype), _applyDecoratedDescriptor(_class2$1C.prototype, "backgroundColor", [_dec6$k], Object.getOwnPropertyDescriptor(_class2$1C.prototype, "backgroundColor"), _class2$1C.prototype), _applyDecoratedDescriptor(_class2$1C.prototype, "visibility", [_dec7$f], Object.getOwnPropertyDescriptor(_class2$1C.prototype, "visibility"), _class2$1C.prototype), _applyDecoratedDescriptor(_class2$1C.prototype, "sourceCamera", [_dec8$a], Object.getOwnPropertyDescriptor(_class2$1C.prototype, "sourceCamera"), _class2$1C.prototype), _applyDecoratedDescriptor(_class2$1C.prototype, "fastBake", [_dec9$9], Object.getOwnPropertyDescriptor(_class2$1C.prototype, "fastBake"), _class2$1C.prototype)), _class2$1C)) || _class$1O));

      legacyCC.utils = utils;

      var CLASS_NAME_PREFIX_ANIM = 'cc.animation.';
      var createEvalSymbol = Symbol('CreateEval');

      var _dec$1O, _class$1N, _class2$1B, _initializer$1s, _initializer2$18, _initializer3$J, _initializer4$y;
      (_dec$1O = ccclass$n(CLASS_NAME_PREFIX_ANIM + "EmbeddedPlayer"), _dec$1O(_class$1N = (_class2$1B = function (_EditorExtendable) {
        _inheritsLoose(EmbeddedPlayer, _EditorExtendable);
        function EmbeddedPlayer() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _EditorExtendable.call.apply(_EditorExtendable, [this].concat(args)) || this;
          _this.begin = _initializer$1s && _initializer$1s();
          _this.end = _initializer2$18 && _initializer2$18();
          _this.reconciledSpeed = _initializer3$J && _initializer3$J();
          _this.playable = _initializer4$y && _initializer4$y();
          return _this;
        }
        return EmbeddedPlayer;
      }(EditorExtendable), (_initializer$1s = applyDecoratedInitializer(_class2$1B.prototype, "begin", [serializable$j], function () {
        return 0.0;
      }), _initializer2$18 = applyDecoratedInitializer(_class2$1B.prototype, "end", [serializable$j], function () {
        return 0.0;
      }), _initializer3$J = applyDecoratedInitializer(_class2$1B.prototype, "reconciledSpeed", [serializable$j], function () {
        return false;
      }), _initializer4$y = applyDecoratedInitializer(_class2$1B.prototype, "playable", [serializable$j], function () {
        return null;
      })), _class2$1B)) || _class$1N);
      var EmbeddedPlayable = function EmbeddedPlayable() {};
      var EmbeddedPlayableState = function () {
        function EmbeddedPlayableState(randomAccess) {
          this._randomAccess = randomAccess;
        }
        var _proto = EmbeddedPlayableState.prototype;
        _proto.setTime = function setTime(_time) {};
        _createClass(EmbeddedPlayableState, [{
          key: "randomAccess",
          get: function get() {
            return this._randomAccess;
          }
        }]);
        return EmbeddedPlayableState;
      }();

      var Playable = function () {
        function Playable() {
          this._isPlaying = false;
          this._isPaused = false;
          this._stepOnce = false;
        }
        var _proto = Playable.prototype;
        _proto.play = function play() {
          if (this._isPlaying) {
            if (this._isPaused) {
              this._isPaused = false;
              this.onResume();
            } else {
              this.onError(getError(3912));
            }
          } else {
            this._isPlaying = true;
            this.onPlay();
          }
        };
        _proto.stop = function stop() {
          if (this._isPlaying) {
            this._isPlaying = false;
            this.onStop();
            this._isPaused = false;
          }
        };
        _proto.pause = function pause() {
          if (this._isPlaying && !this._isPaused) {
            this._isPaused = true;
            this.onPause();
          }
        };
        _proto.resume = function resume() {
          if (this._isPlaying && this._isPaused) {
            this._isPaused = false;
            this.onResume();
          }
        };
        _proto.step = function step() {
          this.pause();
          this._stepOnce = true;
          if (!this._isPlaying) {
            this.play();
          }
        };
        _proto.update = function update(deltaTime) {};
        _proto.onPlay = function onPlay() {};
        _proto.onPause = function onPause() {};
        _proto.onResume = function onResume() {};
        _proto.onStop = function onStop() {};
        _proto.onError = function onError(message) {};
        _createClass(Playable, [{
          key: "isPlaying",
          get: function get() {
            return this._isPlaying;
          }
        }, {
          key: "isPaused",
          get: function get() {
            return this._isPaused;
          }
        }, {
          key: "isMotionless",
          get: function get() {
            return !this.isPlaying || this.isPaused;
          }
        }]);
        return Playable;
      }();

      var WrapMode;
      (function (WrapMode) {
        WrapMode[WrapMode["Default"] = WrapModeMask.Default] = "Default";
        WrapMode[WrapMode["Normal"] = WrapModeMask.Normal] = "Normal";
        WrapMode[WrapMode["Reverse"] = WrapModeMask.Reverse] = "Reverse";
        WrapMode[WrapMode["Loop"] = WrapModeMask.Loop] = "Loop";
        WrapMode[WrapMode["LoopReverse"] = WrapModeMask.Loop | WrapModeMask.Reverse] = "LoopReverse";
        WrapMode[WrapMode["PingPong"] = WrapModeMask.PingPong] = "PingPong";
        WrapMode[WrapMode["PingPongReverse"] = WrapModeMask.PingPong | WrapModeMask.Reverse] = "PingPongReverse";
      })(WrapMode || (WrapMode = {}));
      ccenum(WrapMode);
      var WrappedInfo = function () {
        function WrappedInfo(info) {
          this.ratio = 0;
          this.time = 0;
          this.direction = 1;
          this.stopped = true;
          this.iterations = 0;
          this.frameIndex = undefined;
          if (info) {
            this.set(info);
          }
        }
        var _proto = WrappedInfo.prototype;
        _proto.set = function set(info) {
          this.ratio = info.ratio;
          this.time = info.time;
          this.direction = info.direction;
          this.stopped = info.stopped;
          this.iterations = info.iterations;
          this.frameIndex = info.frameIndex;
        };
        return WrappedInfo;
      }();
      function isLerpable(object) {
        return typeof object.lerp === 'function';
      }

      var PoseOutput = function () {
        function PoseOutput(pose) {
          this.weight = 0.0;
          this._pose = void 0;
          this._blendStateWriters = [];
          this._pose = pose;
        }
        var _proto = PoseOutput.prototype;
        _proto.destroy = function destroy() {
          for (var iBlendStateWriter = 0; iBlendStateWriter < this._blendStateWriters.length; ++iBlendStateWriter) {
            this._pose.destroyWriter(this._blendStateWriters[iBlendStateWriter]);
          }
          this._blendStateWriters.length = 0;
        };
        _proto.createPoseWriter = function createPoseWriter(node, property, constants) {
          var writer = this._pose.createWriter(node, property, this, constants);
          this._blendStateWriters.push(writer);
          return writer;
        };
        return PoseOutput;
      }();

      function getGlobalAnimationManager() {
        var animationManager = legacyCC.director.getAnimationManager();
        return animationManager;
      }

      var EventType$5;
      (function (EventType) {
        EventType["PLAY"] = "play";
        EventType["STOP"] = "stop";
        EventType["PAUSE"] = "pause";
        EventType["RESUME"] = "resume";
        EventType["LASTFRAME"] = "lastframe";
        EventType["FINISHED"] = "finished";
      })(EventType$5 || (EventType$5 = {}));
      ccenum(EventType$5);
      var AnimationState = exports('ak', function (_Playable) {
        _inheritsLoose(AnimationState, _Playable);
        function AnimationState(clip, name) {
          var _this;
          if (name === void 0) {
            name = '';
          }
          _this = _Playable.call(this) || this;
          _this.duration = 1.0;
          _this.time = 0.0;
          _this.frameRate = 0;
          _this._targetNode = null;
          _this._curveLoaded = false;
          _this._clip = void 0;
          _this._speed = 1.0;
          _this._useSimpleProcess = false;
          _this._target = null;
          _this._wrapMode = WrapMode.Normal;
          _this._repeatCount = 1;
          _this._delay = 0.0;
          _this._delayTime = 0.0;
          _this._currentFramePlayed = false;
          _this._name = void 0;
          _this._lastIterations = NaN;
          _this._lastWrapInfo = null;
          _this._wrappedInfo = new WrappedInfo();
          _this._allowLastFrame = false;
          _this._blendStateWriterHost = {
            weight: 0.0
          };
          _this._playbackDuration = 0.0;
          _this._invDuration = 1.0;
          _this._poseOutput = null;
          _this._weight = 1.0;
          _this._clipEval = void 0;
          _this._clipEventEval = void 0;
          _this._clipEmbeddedPlayerEval = void 0;
          _this._doNotCreateEval = false;
          _this._clip = clip;
          _this._name = name || clip && clip.name;
          _this._playbackRange = {
            min: 0.0,
            max: clip.duration
          };
          _this._playbackDuration = clip.duration;
          if (!clip.duration) {
            debug("Clip " + clip.name + " has zero duration.");
          }
          return _this;
        }
        var _proto = AnimationState.prototype;
        _proto.initialize = function initialize(root, blendStateBuffer, mask) {
          if (this._curveLoaded) {
            return;
          }
          this._curveLoaded = true;
          if (this._poseOutput) {
            this._poseOutput.destroy();
            this._poseOutput = null;
          }
          if (this._clipEval) {
            this._clipEval = undefined;
          }
          if (this._clipEventEval) {
            this._clipEventEval = undefined;
          }
          if (this._clipEmbeddedPlayerEval) {
            this._clipEmbeddedPlayerEval.destroy();
            this._clipEmbeddedPlayerEval = undefined;
          }
          this._targetNode = root;
          var clip = this._clip;
          this.duration = clip.duration;
          this._invDuration = 1.0 / this.duration;
          this._speed = clip.speed;
          this.wrapMode = clip.wrapMode;
          this.frameRate = clip.sample;
          this._playbackRange.min = 0.0;
          this._playbackRange.max = clip.duration;
          this._playbackDuration = clip.duration;
          if ((this.wrapMode & WrapModeMask.Loop) === WrapModeMask.Loop) {
            this.repeatCount = Infinity;
          } else {
            this.repeatCount = 1;
          }
          if (!this._doNotCreateEval) {
            var _ref, _getGlobalAnimationMa, _this$_poseOutput;
            var pose = (_ref = blendStateBuffer !== null && blendStateBuffer !== void 0 ? blendStateBuffer : (_getGlobalAnimationMa = getGlobalAnimationManager()) === null || _getGlobalAnimationMa === void 0 ? void 0 : _getGlobalAnimationMa.blendState) !== null && _ref !== void 0 ? _ref : null;
            if (pose) {
              this._poseOutput = new PoseOutput(pose);
            }
            this._clipEval = clip.createEvaluator({
              target: root,
              pose: (_this$_poseOutput = this._poseOutput) !== null && _this$_poseOutput !== void 0 ? _this$_poseOutput : undefined,
              mask: mask
            });
          }
          {
            if (clip.containsAnyEvent()) {
              this._clipEventEval = clip.createEventEvaluator(this._targetNode);
            }
          }
          if (clip.containsAnyEmbeddedPlayer()) {
            this._clipEmbeddedPlayerEval = clip.createEmbeddedPlayerEvaluator(this._targetNode);
            this._clipEmbeddedPlayerEval.notifyHostSpeedChanged(this._speed);
          }
        };
        _proto.destroy = function destroy() {
          if (!this.isMotionless) {
            getGlobalAnimationManager().removeAnimation(this);
          }
          if (this._poseOutput) {
            this._poseOutput.destroy();
            this._poseOutput = null;
          }
          this._clipEval = undefined;
        };
        _proto.emit = function emit() {
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          getGlobalAnimationManager().pushDelayEvent(this._emit, this, args);
        };
        _proto.on = function on(type, callback, target) {
          if (this._target && this._target.isValid) {
            return this._target.on(type, callback, target);
          } else {
            return null;
          }
        };
        _proto.once = function once(type, callback, target) {
          if (this._target && this._target.isValid) {
            return this._target.once(type, callback, target);
          } else {
            return null;
          }
        };
        _proto.off = function off(type, callback, target) {
          if (this._target && this._target.isValid) {
            this._target.off(type, callback, target);
          }
        };
        _proto.allowLastFrameEvent = function allowLastFrameEvent(allowed) {
          this._allowLastFrame = allowed;
        };
        _proto._setEventTarget = function _setEventTarget(target) {
          this._target = target;
        };
        _proto.setTime = function setTime(time) {
          this._currentFramePlayed = false;
          this.time = time || 0.0;
          {
            var _this$_clipEventEval;
            var info = this.getWrappedInfo(time, this._wrappedInfo);
            (_this$_clipEventEval = this._clipEventEval) === null || _this$_clipEventEval === void 0 ? void 0 : _this$_clipEventEval.ignore(info.ratio, info.direction);
          }
        };
        _proto.update = function update(delta) {
          if (this._delayTime > 0.0) {
            this._delayTime -= delta;
            if (this._delayTime > 0.0) {
              return;
            }
          }
          if (this._currentFramePlayed) {
            this.time += delta * this._speed;
          } else {
            this._currentFramePlayed = true;
          }
          this._process();
        };
        _proto.sample = function sample() {
          var info = this.getWrappedInfo(this.time, this._wrappedInfo);
          this._sampleCurves(info.time);
          {
            this._sampleEvents(info);
          }
          this._sampleEmbeddedPlayers(info);
          return info;
        };
        _proto.onPlay = function onPlay() {
          var _this$_clipEmbeddedPl;
          this.setTime(this._getPlaybackStart());
          this._delayTime = this._delay;
          this._onReplayOrResume();
          this.emit(EventType$5.PLAY, this);
          (_this$_clipEmbeddedPl = this._clipEmbeddedPlayerEval) === null || _this$_clipEmbeddedPl === void 0 ? void 0 : _this$_clipEmbeddedPl.notifyHostPlay(this.current);
        };
        _proto.onStop = function onStop() {
          var _this$_clipEmbeddedPl2;
          if (!this.isPaused) {
            this._onPauseOrStop();
          }
          this.emit(EventType$5.STOP, this);
          (_this$_clipEmbeddedPl2 = this._clipEmbeddedPlayerEval) === null || _this$_clipEmbeddedPl2 === void 0 ? void 0 : _this$_clipEmbeddedPl2.notifyHostStop();
        };
        _proto.onResume = function onResume() {
          var _this$_clipEmbeddedPl3;
          this._onReplayOrResume();
          this.emit(EventType$5.RESUME, this);
          (_this$_clipEmbeddedPl3 = this._clipEmbeddedPlayerEval) === null || _this$_clipEmbeddedPl3 === void 0 ? void 0 : _this$_clipEmbeddedPl3.notifyHostPlay(this.current);
        };
        _proto.onPause = function onPause() {
          var _this$_clipEmbeddedPl4;
          this._onPauseOrStop();
          this.emit(EventType$5.PAUSE, this);
          (_this$_clipEmbeddedPl4 = this._clipEmbeddedPlayerEval) === null || _this$_clipEmbeddedPl4 === void 0 ? void 0 : _this$_clipEmbeddedPl4.notifyHostPause(this.current);
        };
        _proto._sampleCurves = function _sampleCurves(time) {
          var poseOutput = this._poseOutput,
            clipEval = this._clipEval;
          if (poseOutput) {
            poseOutput.weight = this.weight;
          }
          if (clipEval) {
            clipEval.evaluate(time);
          }
        };
        _proto._process = function _process() {
          if (this._useSimpleProcess) {
            this.simpleProcess();
          } else {
            this.process();
          }
        };
        _proto.process = function process() {
          var info = this.sample();
          if (this._allowLastFrame) {
            var lastInfo;
            if (!this._lastWrapInfo) {
              lastInfo = this._lastWrapInfo = new WrappedInfo(info);
            } else {
              lastInfo = this._lastWrapInfo;
            }
            if (this.repeatCount > 1 && (info.iterations | 0) > (lastInfo.iterations | 0)) {
              this.emit(EventType$5.LASTFRAME, this);
            }
            lastInfo.set(info);
          }
          if (info.stopped) {
            this.stop();
            this.emit(EventType$5.FINISHED, this);
          }
        };
        _proto.simpleProcess = function simpleProcess() {
          var playbackStart = this._playbackRange.min;
          var playbackDuration = this._playbackDuration;
          var time = 0.0;
          var ratio = 0.0;
          if (playbackDuration !== 0.0) {
            time = this.time % playbackDuration;
            if (time < 0.0) {
              time += playbackDuration;
            }
            var realTime = playbackStart + time;
            ratio = realTime * this._invDuration;
          }
          this._sampleCurves(playbackStart + time);
          if (this._clipEventEval || this._clipEmbeddedPlayerEval) {
            var wrapInfo = this.getWrappedInfo(this.time, this._wrappedInfo);
            {
              this._sampleEvents(wrapInfo);
            }
            this._sampleEmbeddedPlayers(wrapInfo);
          }
          if (this._allowLastFrame) {
            if (Number.isNaN(this._lastIterations)) {
              this._lastIterations = ratio;
            }
            if (this.time > 0 && this._lastIterations > ratio || this.time < 0 && this._lastIterations < ratio) {
              this.emit(EventType$5.LASTFRAME, this);
            }
            this._lastIterations = ratio;
          }
        };
        _proto._needReverse = function _needReverse(currentIterations) {
          var wrapMode = this.wrapMode;
          var needReverse = false;
          if ((wrapMode & WrapModeMask.PingPong) === WrapModeMask.PingPong) {
            var isEnd = currentIterations - (currentIterations | 0) === 0;
            if (isEnd && currentIterations > 0) {
              currentIterations -= 1;
            }
            var isOddIteration = currentIterations & 1;
            if (isOddIteration) {
              needReverse = !needReverse;
            }
          }
          if ((wrapMode & WrapModeMask.Reverse) === WrapModeMask.Reverse) {
            needReverse = !needReverse;
          }
          return needReverse;
        };
        _proto.getWrappedInfo = function getWrappedInfo(time, info) {
          info = info || new WrappedInfo();
          var playbackStart = this._playbackRange.min,
            playbackDuration = this._playbackDuration;
          var repeatCount = this.repeatCount;
          if (playbackDuration === 0.0) {
            info.time = 0.0;
            info.ratio = 0.0;
            info.direction = 1.0;
            info.stopped = !!Number.isFinite(repeatCount);
            info.iterations = 0.0;
            return info;
          }
          var stopped = false;
          time -= playbackStart;
          var currentIterations = time > 0 ? time / playbackDuration : -(time / playbackDuration);
          if (currentIterations >= repeatCount) {
            currentIterations = repeatCount;
            stopped = true;
            var tempRatio = repeatCount - (repeatCount | 0);
            if (tempRatio === 0) {
              tempRatio = 1;
            }
            time = tempRatio * playbackDuration * (time > 0 ? 1 : -1);
          }
          if (time > playbackDuration) {
            var tempTime = time % playbackDuration;
            time = tempTime === 0 ? playbackDuration : tempTime;
          } else if (time < 0) {
            time %= playbackDuration;
            if (time !== 0) {
              time += playbackDuration;
            }
          }
          var needReverse = false;
          var shouldWrap = this._wrapMode & WrapModeMask.ShouldWrap;
          if (shouldWrap) {
            needReverse = this._needReverse(currentIterations);
          }
          var direction = needReverse ? -1 : 1;
          if (this.speed < 0) {
            direction *= -1;
          }
          if (shouldWrap && needReverse) {
            time = playbackDuration - time;
          }
          info.time = playbackStart + time;
          info.ratio = info.time / this.duration;
          info.direction = direction;
          info.stopped = stopped;
          info.iterations = currentIterations;
          return info;
        };
        _proto._getPlaybackStart = function _getPlaybackStart() {
          return this._playbackRange.min;
        };
        _proto._sampleEvents = function _sampleEvents(wrapInfo) {
          var _this$_clipEventEval2;
          (_this$_clipEventEval2 = this._clipEventEval) === null || _this$_clipEventEval2 === void 0 ? void 0 : _this$_clipEventEval2.sample(wrapInfo.ratio, wrapInfo.direction, wrapInfo.iterations);
        };
        _proto._sampleEmbeddedPlayers = function _sampleEmbeddedPlayers(wrapInfo) {
          var _this$_clipEmbeddedPl5;
          (_this$_clipEmbeddedPl5 = this._clipEmbeddedPlayerEval) === null || _this$_clipEmbeddedPl5 === void 0 ? void 0 : _this$_clipEmbeddedPl5.evaluate(wrapInfo.time, Math.trunc(wrapInfo.iterations));
        };
        _proto._emit = function _emit(type, state) {
          if (this._target && this._target.isValid) {
            this._target.emit(type, type, state);
          }
        };
        _proto._onReplayOrResume = function _onReplayOrResume() {
          getGlobalAnimationManager().addAnimation(this);
        };
        _proto._onPauseOrStop = function _onPauseOrStop() {
          getGlobalAnimationManager().removeAnimation(this);
        };
        _createClass(AnimationState, [{
          key: "clip",
          get: function get() {
            return this._clip;
          }
        }, {
          key: "name",
          get: function get() {
            return this._name;
          }
        }, {
          key: "length",
          get: function get() {
            return this.duration;
          }
        }, {
          key: "wrapMode",
          get: function get() {
            return this._wrapMode;
          },
          set: function set(value) {
            var _this$_clipEventEval3;
            this._wrapMode = value;
            this.time = 0;
            if (value & WrapModeMask.Loop) {
              this.repeatCount = Infinity;
            } else {
              this.repeatCount = 1;
            }
            (_this$_clipEventEval3 = this._clipEventEval) === null || _this$_clipEventEval3 === void 0 ? void 0 : _this$_clipEventEval3.setWrapMode(value);
          }
        }, {
          key: "repeatCount",
          get: function get() {
            return this._repeatCount;
          },
          set: function set(value) {
            this._repeatCount = value;
            var shouldWrap = this._wrapMode & WrapModeMask.ShouldWrap;
            var reverse = (this.wrapMode & WrapModeMask.Reverse) === WrapModeMask.Reverse;
            if (value === Infinity && !shouldWrap && !reverse) {
              this._useSimpleProcess = true;
            } else {
              this._useSimpleProcess = false;
            }
          }
        }, {
          key: "delay",
          get: function get() {
            return this._delay;
          },
          set: function set(value) {
            this._delayTime = this._delay = value;
          }
        }, {
          key: "playbackRange",
          get: function get() {
            return this._playbackRange;
          },
          set: function set(value) {
            assertIsTrue(value.max >= value.min);
            this._playbackRange.min = Math.max(value.min, 0);
            this._playbackRange.max = Math.min(value.max, this.duration);
            this._playbackDuration = this._playbackRange.max - this._playbackRange.min;
            this.setTime(0.0);
          }
        }, {
          key: "speed",
          get: function get() {
            return this._speed;
          },
          set: function set(value) {
            var _this$_clipEmbeddedPl6;
            this._speed = value;
            (_this$_clipEmbeddedPl6 = this._clipEmbeddedPlayerEval) === null || _this$_clipEmbeddedPl6 === void 0 ? void 0 : _this$_clipEmbeddedPl6.notifyHostSpeedChanged(value);
          }
        }, {
          key: "current",
          get: function get() {
            return this.getWrappedInfo(this.time).time;
          }
        }, {
          key: "ratio",
          get: function get() {
            return this.duration === 0.0 ? 0.0 : this.current / this.duration;
          }
        }, {
          key: "weight",
          get: function get() {
            return this._weight;
          },
          set: function set(value) {
            this._weight = value;
            if (this._poseOutput) {
              this._poseOutput.weight = value;
            }
          }
        }, {
          key: "curveLoaded",
          get: function get() {
            return this._curveLoaded;
          }
        }]);
        return AnimationState;
      }(Playable));
      legacyCC.AnimationState = AnimationState;

      var _dec$1N, _class$1M, _class2$1A, _initializer$1r, _initializer2$17;
      (_dec$1N = ccclass$n(CLASS_NAME_PREFIX_ANIM + "EmbeddedAnimationClipPlayable"), _dec$1N(_class$1M = (_class2$1A = function (_EmbeddedPlayable) {
        _inheritsLoose(EmbeddedAnimationClipPlayable, _EmbeddedPlayable);
        function EmbeddedAnimationClipPlayable() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _EmbeddedPlayable.call.apply(_EmbeddedPlayable, [this].concat(args)) || this;
          _this.path = _initializer$1r && _initializer$1r();
          _this.clip = _initializer2$17 && _initializer2$17();
          return _this;
        }
        var _proto = EmbeddedAnimationClipPlayable.prototype;
        _proto.instantiate = function instantiate(root) {
          var clip = this.clip,
            path = this.path;
          if (!clip) {
            return null;
          }
          var clipRoot = root.getChildByPath(path);
          if (!clipRoot) {
            errorID(3938, path, root.getPathInHierarchy(), clip.name);
            return null;
          }
          var state = new AnimationState(clip);
          state.initialize(clipRoot);
          return new EmbeddedAnimationClipPlayableState(state);
        };
        return EmbeddedAnimationClipPlayable;
      }(EmbeddedPlayable), (_initializer$1r = applyDecoratedInitializer(_class2$1A.prototype, "path", [serializable$j], function () {
        return '';
      }), _initializer2$17 = applyDecoratedInitializer(_class2$1A.prototype, "clip", [serializable$j], function () {
        return null;
      })), _class2$1A)) || _class$1M);
      var EmbeddedAnimationClipPlayableState = function (_EmbeddedPlayableStat) {
        _inheritsLoose(EmbeddedAnimationClipPlayableState, _EmbeddedPlayableStat);
        function EmbeddedAnimationClipPlayableState(animationState) {
          var _this2;
          _this2 = _EmbeddedPlayableStat.call(this, true) || this;
          _this2._animationState = void 0;
          _this2._animationState = animationState;
          return _this2;
        }
        var _proto2 = EmbeddedAnimationClipPlayableState.prototype;
        _proto2.destroy = function destroy() {
          this._animationState.destroy();
        };
        _proto2.play = function play() {
          this._animationState.play();
        };
        _proto2.pause = function pause() {
          this._animationState.pause();
        };
        _proto2.stop = function stop() {
          this._animationState.stop();
        };
        _proto2.setSpeed = function setSpeed(speed) {
          this._animationState.speed = speed;
        };
        _proto2.setTime = function setTime(time) {
          this._animationState.time = time;
        };
        return EmbeddedAnimationClipPlayableState;
      }(EmbeddedPlayableState);

      var _dec$1M, _class$1L, _class2$1z, _initializer$1q;
      (_dec$1M = ccclass$n(CLASS_NAME_PREFIX_ANIM + "EmbeddedParticleSystemPlayable"), _dec$1M(_class$1L = (_class2$1z = function (_EmbeddedPlayable) {
        _inheritsLoose(EmbeddedParticleSystemPlayable, _EmbeddedPlayable);
        function EmbeddedParticleSystemPlayable() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _EmbeddedPlayable.call.apply(_EmbeddedPlayable, [this].concat(args)) || this;
          _this.path = _initializer$1q && _initializer$1q();
          return _this;
        }
        var _proto = EmbeddedParticleSystemPlayable.prototype;
        _proto.instantiate = function instantiate(root) {
          var node = root.getChildByPath(this.path);
          if (!node) {
            warn("Hierarchy path " + this.path + " does not exists.");
            return null;
          }
          var ParticleSystemConstructor = getClassByName("cc.ParticleSystem");
          if (!ParticleSystemConstructor) {
            warn("Particle system is required for embedded particle system player.");
            return null;
          }
          var particleSystem = node.getComponent(ParticleSystemConstructor);
          if (!particleSystem) {
            warn(this.path + " does not includes a particle system component.");
            return null;
          }
          return new EmbeddedParticleSystemPlayableState(particleSystem);
        };
        return EmbeddedParticleSystemPlayable;
      }(EmbeddedPlayable), (_initializer$1q = applyDecoratedInitializer(_class2$1z.prototype, "path", [serializable$j], function () {
        return '';
      })), _class2$1z)) || _class$1L);
      var EmbeddedParticleSystemPlayableState = function (_EmbeddedPlayableStat) {
        _inheritsLoose(EmbeddedParticleSystemPlayableState, _EmbeddedPlayableStat);
        function EmbeddedParticleSystemPlayableState(particleSystem) {
          var _this2;
          _this2 = _EmbeddedPlayableStat.call(this, false) || this;
          _this2._particleSystem = void 0;
          _this2._particleSystem = particleSystem;
          return _this2;
        }
        var _proto2 = EmbeddedParticleSystemPlayableState.prototype;
        _proto2.destroy = function destroy() {};
        _proto2.play = function play() {
          this._particleSystem.play();
        };
        _proto2.pause = function pause() {
          this._particleSystem.stopEmitting();
        };
        _proto2.stop = function stop() {
          this._particleSystem.stopEmitting();
        };
        _proto2.setSpeed = function setSpeed(speed) {
          this._particleSystem.simulationSpeed = speed;
        };
        return EmbeddedParticleSystemPlayableState;
      }(EmbeddedPlayableState);

      var _dec$1L, _class$1K, _class2$1y, _initializer$1p, _dec2$1k, _class4$m, _class5$o, _initializer2$16;
      function isPropertyPath(path) {
        return typeof path === 'string' || typeof path === 'number';
      }
      function isCustomPath(path, constructor) {
        return path instanceof constructor;
      }
      var HierarchyPath = (_dec$1L = ccclass$n('cc.animation.HierarchyPath'), _dec$1L(_class$1K = (_class2$1y = function () {
        function HierarchyPath(path) {
          this.path = _initializer$1p && _initializer$1p();
          this.path = path || '';
        }
        var _proto = HierarchyPath.prototype;
        _proto.get = function get(target) {
          if (!(target instanceof Node$1)) {
            warnID(3925);
            return null;
          }
          var result = target.getChildByPath(this.path);
          if (!result) {
            warnID(3926, target.name, this.path);
            return null;
          }
          return result;
        };
        return HierarchyPath;
      }(), (_initializer$1p = applyDecoratedInitializer(_class2$1y.prototype, "path", [serializable$j], function () {
        return '';
      })), _class2$1y)) || _class$1K);
      var ComponentPath = (_dec2$1k = ccclass$n('cc.animation.ComponentPath'), _dec2$1k(_class4$m = (_class5$o = function () {
        function ComponentPath(component) {
          this.component = _initializer2$16 && _initializer2$16();
          this.component = component || '';
        }
        var _proto2 = ComponentPath.prototype;
        _proto2.get = function get(target) {
          if (!(target instanceof Node$1)) {
            warnID(3927);
            return null;
          }
          var result = target.getComponent(this.component);
          if (!result) {
            warnID(3928, target.name, this.component);
            return null;
          }
          return result;
        };
        return ComponentPath;
      }(), (_initializer2$16 = applyDecoratedInitializer(_class5$o.prototype, "component", [serializable$j], function () {
        return '';
      })), _class5$o)) || _class4$m);

      var _dec$1K, _class$1J, _class2$1x, _initializer$1o, _dec2$1j, _class4$l, _class5$n, _initializer2$15, _initializer3$I, _class6$5, _dec3$V, _class7$8, _class8$7, _initializer4$x, _dec4$G, _class10$3, _class11$3, _initializer5$n, _dec5$z, _class13$2, _class14$2, _initializer6$h;
      var normalizedFollowTag = Symbol('NormalizedFollow');
      var parseTrsPathTag = Symbol('ConvertAsTrsPath');
      var trackBindingTag = Symbol('TrackBinding');
      var TrackPath = (_dec$1K = ccclass$n(CLASS_NAME_PREFIX_ANIM + "TrackPath"), _dec$1K(_class$1J = (_class2$1x = function () {
        function TrackPath() {
          this._paths = _initializer$1o && _initializer$1o();
        }
        var _proto = TrackPath.prototype;
        _proto.toProperty = function toProperty(name) {
          this._paths.push(name);
          return this;
        };
        _proto.toElement = function toElement(index) {
          this._paths.push(index);
          return this;
        };
        _proto.toHierarchy = function toHierarchy(nodePath) {
          this._paths.push(new HierarchyPath(nodePath));
          return this;
        };
        _proto.toComponent = function toComponent(constructor) {
          var path = new ComponentPath(typeof constructor === 'string' ? constructor : getClassName(constructor));
          this._paths.push(path);
          return this;
        };
        _proto.toCustomized = function toCustomized(resolver) {
          this._paths.push(resolver);
          return this;
        };
        _proto.append = function append() {
          var _this$_paths;
          for (var _len = arguments.length, trackPaths = new Array(_len), _key = 0; _key < _len; _key++) {
            trackPaths[_key] = arguments[_key];
          }
          var paths = (_this$_paths = this._paths).concat.apply(_this$_paths, trackPaths.map(function (trackPath) {
            return trackPath._paths;
          }));
          this._paths = paths;
          return this;
        };
        _proto.isPropertyAt = function isPropertyAt(index) {
          return typeof this._paths[index] === 'string';
        };
        _proto.parsePropertyAt = function parsePropertyAt(index) {
          return this._paths[index];
        };
        _proto.isElementAt = function isElementAt(index) {
          return typeof this._paths[index] === 'number';
        };
        _proto.parseElementAt = function parseElementAt(index) {
          return this._paths[index];
        };
        _proto.isHierarchyAt = function isHierarchyAt(index) {
          return this._paths[index] instanceof HierarchyPath;
        };
        _proto.parseHierarchyAt = function parseHierarchyAt(index) {
          assertIsTrue(this.isHierarchyAt(index));
          return this._paths[index].path;
        };
        _proto.isComponentAt = function isComponentAt(index) {
          return this._paths[index] instanceof ComponentPath;
        };
        _proto.parseComponentAt = function parseComponentAt(index) {
          assertIsTrue(this.isComponentAt(index));
          return this._paths[index].component;
        };
        _proto.slice = function slice(beginIndex, endIndex) {
          var trackPath = new TrackPath();
          trackPath._paths = this._paths.slice(beginIndex, endIndex);
          return trackPath;
        };
        _proto.trace = function trace(object, beginIndex, endIndex) {
          var _beginIndex, _endIndex;
          (_beginIndex = beginIndex) !== null && _beginIndex !== void 0 ? _beginIndex : beginIndex = 0;
          (_endIndex = endIndex) !== null && _endIndex !== void 0 ? _endIndex : endIndex = this._paths.length;
          return this[normalizedFollowTag](object, beginIndex, endIndex);
        };
        _proto[parseTrsPathTag] = function () {
          var paths = this._paths;
          var nPaths = paths.length;
          var iPath = 0;
          var nodePath = '';
          for (; iPath < nPaths; ++iPath) {
            var path = paths[iPath];
            if (!(path instanceof HierarchyPath)) {
              break;
            } else if (!path.path) {
              continue;
            } else if (nodePath) {
              nodePath += "/" + path.path;
            } else {
              nodePath = path.path;
            }
          }
          if (iPath === nPaths) {
            return null;
          }
          var prs;
          if (iPath !== nPaths - 1) {
            return null;
          }
          switch (paths[iPath]) {
            case 'position':
            case 'scale':
            case 'rotation':
            case 'eulerAngles':
              prs = paths[iPath];
              break;
            default:
              return null;
          }
          return {
            node: nodePath,
            property: prs
          };
        };
        _proto[normalizedFollowTag] = function (root, beginIndex, endIndex) {
          var paths = this._paths;
          var result = root;
          for (var iPath = beginIndex; iPath < endIndex; ++iPath) {
            var path = paths[iPath];
            if (isPropertyPath(path)) {
              if (!(path in result)) {
                warnID(3929, path);
                return null;
              } else {
                result = result[path];
              }
            } else {
              result = path.get(result);
            }
            if (result === null) {
              break;
            }
          }
          return result;
        };
        _createClass(TrackPath, [{
          key: "length",
          get: function get() {
            return this._paths.length;
          }
        }]);
        return TrackPath;
      }(), (_initializer$1o = applyDecoratedInitializer(_class2$1x.prototype, "_paths", [serializable$j], function () {
        return [];
      })), _class2$1x)) || _class$1J);
      var TrackBinding = (_dec2$1j = ccclass$n(CLASS_NAME_PREFIX_ANIM + "TrackBinding"), _dec2$1j(_class4$l = uniquelyReferenced(_class4$l = (_class5$n = (_class6$5 = function () {
        function TrackBinding() {
          this.path = _initializer2$15 && _initializer2$15();
          this.proxy = _initializer3$I && _initializer3$I();
        }
        var _proto2 = TrackBinding.prototype;
        _proto2.parseTrsPath = function parseTrsPath() {
          if (this.proxy) {
            return null;
          } else {
            return this.path[parseTrsPathTag]();
          }
        };
        _proto2.createRuntimeBinding = function createRuntimeBinding(target, poseOutput, isConstant) {
          var path = this.path,
            proxy = this.proxy;
          var nPaths = path.length;
          var iLastPath = nPaths - 1;
          if (nPaths !== 0 && (path.isPropertyAt(iLastPath) || path.isElementAt(iLastPath)) && !proxy) {
            var lastPropertyKey = path.isPropertyAt(iLastPath) ? path.parsePropertyAt(iLastPath) : path.parseElementAt(iLastPath);
            var resultTarget = path[normalizedFollowTag](target, 0, nPaths - 1);
            if (resultTarget === null) {
              return null;
            }
            if (poseOutput && resultTarget instanceof Node$1 && isTrsPropertyName(lastPropertyKey)) {
              var blendStateWriter = poseOutput.createPoseWriter(resultTarget, lastPropertyKey, isConstant);
              return blendStateWriter;
            }
            var _setValue;
            var _getValue;
            {
              var animationFunction = TrackBinding._animationFunctions.get(resultTarget.constructor);
              if (!animationFunction) {
                animationFunction = new Map();
                TrackBinding._animationFunctions.set(resultTarget.constructor, animationFunction);
              }
              var accessor = animationFunction.get(lastPropertyKey);
              if (!accessor) {
                accessor = {
                  setValue: Function('value', "this.target." + lastPropertyKey + " = value;"),
                  getValue: Function("return this.target." + lastPropertyKey + ";")
                };
                animationFunction.set(lastPropertyKey, accessor);
              }
              _setValue = accessor.setValue;
              _getValue = accessor.getValue;
            }
            return {
              target: resultTarget,
              setValue: _setValue,
              getValue: _getValue
            };
          } else if (!proxy) {
            errorID(3921);
            return null;
          } else {
            var _resultTarget = path[normalizedFollowTag](target, 0, nPaths);
            if (_resultTarget === null) {
              return null;
            }
            var runtimeProxy = proxy.forTarget(_resultTarget);
            if (!runtimeProxy) {
              return null;
            }
            var _binding = {
              setValue: function setValue(value) {
                runtimeProxy.set(value);
              }
            };
            var proxyGet = runtimeProxy.get;
            if (proxyGet) {
              _binding.getValue = function () {
                return proxyGet.call(runtimeProxy);
              };
            }
            return _binding;
          }
        };
        _proto2.isMaskedOff = function isMaskedOff(mask) {
          var trsPath = this.parseTrsPath();
          if (!trsPath) {
            return false;
          }
          var joints = mask.joints[Symbol.iterator]();
          for (var jointMaskInfoIter = joints.next(); !jointMaskInfoIter.done; jointMaskInfoIter = joints.next()) {
            var _jointMaskInfoIter = jointMaskInfoIter,
              jointMaskInfo = _jointMaskInfoIter.value;
            if (jointMaskInfo.path !== trsPath.node) {
              continue;
            }
            return !jointMaskInfo.enabled;
          }
          return false;
        };
        return TrackBinding;
      }(), _class6$5._animationFunctions = new WeakMap(), _class6$5), (_initializer2$15 = applyDecoratedInitializer(_class5$n.prototype, "path", [serializable$j], function () {
        return new TrackPath();
      }), _initializer3$I = applyDecoratedInitializer(_class5$n.prototype, "proxy", [serializable$j], null)), _class5$n)) || _class4$l) || _class4$l);
      function isTrsPropertyName(name) {
        return name === 'position' || name === 'rotation' || name === 'scale' || name === 'eulerAngles';
      }
      var Track = (_dec3$V = ccclass$n(CLASS_NAME_PREFIX_ANIM + "Track"), _dec3$V(_class7$8 = (_class8$7 = function () {
        function Track() {
          this._binding = _initializer4$x && _initializer4$x();
        }
        var _proto3 = Track.prototype;
        _proto3.channels = function channels() {
          return [];
        };
        _proto3.range = function range() {
          var range = {
            min: Infinity,
            max: -Infinity
          };
          for (var _iterator = _createForOfIteratorHelperLoose(this.channels()), _step; !(_step = _iterator()).done;) {
            var channel = _step.value;
            range.min = Math.min(range.min, channel.curve.rangeMin);
            range.max = Math.max(range.max, channel.curve.rangeMax);
          }
          return range;
        };
        _createClass(Track, [{
          key: "path",
          get: function get() {
            return this._binding.path;
          },
          set: function set(value) {
            this._binding.path = value;
          }
        }, {
          key: "proxy",
          get: function get() {
            return this._binding.proxy;
          },
          set: function set(value) {
            this._binding.proxy = value;
          }
        }, {
          key: trackBindingTag,
          get: function get() {
            return this._binding;
          }
        }]);
        return Track;
      }(), (_initializer4$x = applyDecoratedInitializer(_class8$7.prototype, "_binding", [serializable$j], function () {
        return new TrackBinding();
      })), _class8$7)) || _class7$8);
      var Channel = (_dec4$G = ccclass$n(CLASS_NAME_PREFIX_ANIM + "Channel"), _dec4$G(_class10$3 = (_class11$3 = function () {
        function Channel(curve) {
          this.name = '';
          this._curve = _initializer5$n && _initializer5$n();
          this._curve = curve;
        }
        _createClass(Channel, [{
          key: "curve",
          get: function get() {
            return this._curve;
          }
        }]);
        return Channel;
      }(), (_initializer5$n = applyDecoratedInitializer(_class11$3.prototype, "_curve", [serializable$j], null)), _class11$3)) || _class10$3);
      var SingleChannelTrack = (_dec5$z = ccclass$n(CLASS_NAME_PREFIX_ANIM + "SingleChannelTrack"), _dec5$z(_class13$2 = (_class14$2 = function (_Track) {
        _inheritsLoose(SingleChannelTrack, _Track);
        function SingleChannelTrack() {
          var _this;
          _this = _Track.call(this) || this;
          _this._channel = _initializer6$h && _initializer6$h();
          _this._channel = new Channel(_this.createCurve());
          return _this;
        }
        var _proto4 = SingleChannelTrack.prototype;
        _proto4.channels = function channels() {
          return [this._channel];
        };
        _proto4.createCurve = function createCurve() {
          throw new Error("Not impl");
        };
        _proto4[createEvalSymbol] = function () {
          var curve = this._channel.curve;
          return new SingleChannelTrackEval(curve);
        };
        _createClass(SingleChannelTrack, [{
          key: "channel",
          get: function get() {
            return this._channel;
          }
        }]);
        return SingleChannelTrack;
      }(Track), (_initializer6$h = applyDecoratedInitializer(_class14$2.prototype, "_channel", [serializable$j], null)), _class14$2)) || _class13$2);
      var SingleChannelTrackEval = function () {
        function SingleChannelTrackEval(_curve) {
          this._curve = _curve;
        }
        var _proto5 = SingleChannelTrackEval.prototype;
        _proto5.evaluate = function evaluate(time) {
          return this._curve.evaluate(time);
        };
        _createClass(SingleChannelTrackEval, [{
          key: "requiresDefault",
          get: function get() {
            return false;
          }
        }]);
        return SingleChannelTrackEval;
      }();

      var _dec$1J, _class$1I, _class2$1w, _initializer$1n;
      var ccclass$g = ccclass$n,
        serializable$d = serializable$j;
      (_dec$1J = ccclass$g(CLASS_NAME_PREFIX_ANIM + "RealArrayTrack"), _dec$1J(_class$1I = (_class2$1w = function (_Track) {
        _inheritsLoose(RealArrayTrack, _Track);
        function RealArrayTrack() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Track.call.apply(_Track, [this].concat(args)) || this;
          _this._channels = _initializer$1n && _initializer$1n();
          return _this;
        }
        var _proto = RealArrayTrack.prototype;
        _proto.channels = function channels() {
          return this._channels;
        };
        _proto[createEvalSymbol] = function () {
          return new RealArrayTrackEval(this._channels.map(function (_ref) {
            var curve = _ref.curve;
            return curve;
          }));
        };
        _createClass(RealArrayTrack, [{
          key: "elementCount",
          get: function get() {
            return this._channels.length;
          },
          set: function set(value) {
            var channels = this._channels;
            var nChannels = channels.length;
            if (value < nChannels) {
              this._channels.splice(value);
            } else if (value > nChannels) {
              var _this$_channels;
              (_this$_channels = this._channels).push.apply(_this$_channels, Array.from({
                length: value - nChannels
              }, function () {
                return new Channel(new RealCurve());
              }));
            }
          }
        }]);
        return RealArrayTrack;
      }(Track), (_initializer$1n = applyDecoratedInitializer(_class2$1w.prototype, "_channels", [serializable$d], function () {
        return [];
      })), _class2$1w)) || _class$1I);
      var RealArrayTrackEval = function () {
        function RealArrayTrackEval(_curves) {
          this._curves = _curves;
          this._result = new Array(_curves.length).fill(0.0);
        }
        var _proto2 = RealArrayTrackEval.prototype;
        _proto2.evaluate = function evaluate(time) {
          var result = this._result;
          var nElements = result.length;
          for (var iElement = 0; iElement < nElements; ++iElement) {
            result[iElement] = this._curves[iElement].evaluate(time);
          }
          return this._result;
        };
        _createClass(RealArrayTrackEval, [{
          key: "requiresDefault",
          get: function get() {
            return false;
          }
        }]);
        return RealArrayTrackEval;
      }();

      var _dec$1I, _class$1H, _class2$1v, _initializer$1m, _initializer2$14, _descriptor$b;
      var UniformProxyFactory = (_dec$1I = ccclass$n('cc.animation.UniformProxyFactory'), _dec$1I(_class$1H = (_class2$1v = function () {
        function UniformProxyFactory(uniformName, passIndex) {
          this.passIndex = _initializer$1m && _initializer$1m();
          this.uniformName = _initializer2$14 && _initializer2$14();
          _initializerDefineProperty(this, "channelIndex", _descriptor$b, this);
          this.passIndex = passIndex || 0;
          this.uniformName = uniformName || '';
        }
        var _proto = UniformProxyFactory.prototype;
        _proto.forTarget = function forTarget(target) {
          if (!(target instanceof Material)) {
            warnID(3940, target);
            return undefined;
          }
          var passIndex = this.passIndex,
            uniformName = this.uniformName,
            channelIndex = this.channelIndex;
          if (passIndex < 0 || passIndex >= target.passes.length) {
            warnID(3941, target.name, passIndex);
            return undefined;
          }
          var pass = target.passes[passIndex];
          var handle = pass.getHandle(uniformName);
          if (!handle) {
            warnID(3942, target.name, passIndex, uniformName);
            return undefined;
          }
          var type = Pass.getTypeFromHandle(handle);
          if (type < Type$1.SAMPLER1D) {
            var realHandle = channelIndex === undefined ? handle : pass.getHandle(uniformName, channelIndex, Type$1.FLOAT);
            if (!realHandle) {
              warnID(3943, target.name, passIndex, uniformName, channelIndex);
              return undefined;
            }
            if (isUniformArray(pass, uniformName)) {
              return {
                set: function set(value) {
                  pass.setUniformArray(realHandle, value);
                }
              };
            }
            return {
              set: function set(value) {
                pass.setUniform(realHandle, value);
              }
            };
          } else {
            var binding = Pass.getBindingFromHandle(handle);
            var prop = pass.properties[uniformName];
            var texName = prop && prop.value ? "" + prop.value + getStringFromType(prop.type) : getDefaultFromType(prop.type);
            var dftTex = builtinResMgr.get(texName);
            if (!dftTex) {
              warn("Illegal texture default value: " + texName + ".");
              dftTex = builtinResMgr.get('default-texture');
            }
            return {
              set: function set(value) {
                if (!value) {
                  value = dftTex;
                }
                var texture = value.getGFXTexture();
                if (!texture || !texture.width || !texture.height) {
                  return;
                }
                pass.bindTexture(binding, texture);
                if (value instanceof TextureBase) {
                  pass.bindSampler(binding, deviceManager.gfxDevice.getSampler(value.getSamplerInfo()));
                }
              }
            };
          }
        };
        return UniformProxyFactory;
      }(), (_initializer$1m = applyDecoratedInitializer(_class2$1v.prototype, "passIndex", [serializable$j], function () {
        return 0;
      }), _initializer2$14 = applyDecoratedInitializer(_class2$1v.prototype, "uniformName", [serializable$j], function () {
        return '';
      }), _descriptor$b = _applyDecoratedDescriptor(_class2$1v.prototype, "channelIndex", [_float], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return undefined;
        }
      })), _class2$1v)) || _class$1H);
      function isUniformArray(pass, name) {
        for (var _iterator = _createForOfIteratorHelperLoose(pass.shaderInfo.blocks), _step; !(_step = _iterator()).done;) {
          var block = _step.value;
          for (var _iterator2 = _createForOfIteratorHelperLoose(block.members), _step2; !(_step2 = _iterator2()).done;) {
            var uniform = _step2.value;
            if (uniform.name === name) {
              return uniform.count > 1;
            }
          }
        }
        return false;
      }

      var _dec$1H, _class$1G, _class2$1u, _initializer$1l, _initializer2$13, _dec2$1i, _class4$k, _class5$m, _initializer3$H, _dec3$U, _class7$7;
      var MorphWeightValueProxy = (_dec$1H = ccclass$n('cc.animation.MorphWeightValueProxy'), _dec$1H(_class$1G = (_class2$1u = function () {
        function MorphWeightValueProxy() {
          this.subMeshIndex = _initializer$1l && _initializer$1l();
          this.shapeIndex = _initializer2$13 && _initializer2$13();
        }
        var _proto = MorphWeightValueProxy.prototype;
        _proto.forTarget = function forTarget(target) {
          var _this = this;
          return {
            set: function set(value) {
              target.setWeight(value, _this.subMeshIndex, _this.shapeIndex);
            }
          };
        };
        return MorphWeightValueProxy;
      }(), (_initializer$1l = applyDecoratedInitializer(_class2$1u.prototype, "subMeshIndex", [serializable$j], function () {
        return 0;
      }), _initializer2$13 = applyDecoratedInitializer(_class2$1u.prototype, "shapeIndex", [serializable$j], function () {
        return 0;
      })), _class2$1u)) || _class$1G);
      var MorphWeightsValueProxy = (_dec2$1i = ccclass$n('cc.animation.MorphWeightsValueProxy'), _dec2$1i(_class4$k = (_class5$m = function () {
        function MorphWeightsValueProxy() {
          this.subMeshIndex = _initializer3$H && _initializer3$H();
        }
        var _proto2 = MorphWeightsValueProxy.prototype;
        _proto2.forTarget = function forTarget(target) {
          var _this2 = this;
          return {
            set: function set(value) {
              target.setWeights(value, _this2.subMeshIndex);
            }
          };
        };
        return MorphWeightsValueProxy;
      }(), (_initializer3$H = applyDecoratedInitializer(_class5$m.prototype, "subMeshIndex", [serializable$j], function () {
        return 0;
      })), _class5$m)) || _class4$k);
      var MorphWeightsAllValueProxy = (_dec3$U = ccclass$n('cc.animation.MorphWeightsAllValueProxy'), _dec3$U(_class7$7 = function () {
        function MorphWeightsAllValueProxy() {}
        var _proto3 = MorphWeightsAllValueProxy.prototype;
        _proto3.forTarget = function forTarget(target) {
          return {
            set: function set(value) {
              var _target$mesh$struct$p, _target$mesh;
              var nSubMeshes = (_target$mesh$struct$p = (_target$mesh = target.mesh) === null || _target$mesh === void 0 ? void 0 : _target$mesh.struct.primitives.length) !== null && _target$mesh$struct$p !== void 0 ? _target$mesh$struct$p : 0;
              for (var iSubMesh = 0; iSubMesh < nSubMeshes; ++iSubMesh) {
                target.setWeights(value, iSubMesh);
              }
            }
          };
        };
        return MorphWeightsAllValueProxy;
      }()) || _class7$7);

      var _dec2$1h, _class4$j, _class5$l, _initializer4$w, _initializer5$m, _initializer6$g;
      function makeCubicSplineValueConstructor(name, ConstructorX, scaleFx, scaleAndAdd) {
        var _dec, _class, _class2, _initializer, _initializer2, _initializer3;
        var tempValue = new ConstructorX();
        var m0 = new ConstructorX();
        var m1 = new ConstructorX();
        var CubicSplineValueClass = (_dec = ccclass$n(name), _dec(_class = (_class2 = function () {
          function CubicSplineValueClass(dataPoint, inTangent, outTangent) {
            this.dataPoint = _initializer && _initializer();
            this.inTangent = _initializer2 && _initializer2();
            this.outTangent = _initializer3 && _initializer3();
            this.dataPoint = dataPoint || new ConstructorX();
            this.inTangent = inTangent || new ConstructorX();
            this.outTangent = outTangent || new ConstructorX();
          }
          var _proto = CubicSplineValueClass.prototype;
          _proto.lerp = function lerp(to, t, dt) {
            var p0 = this.dataPoint;
            var p1 = to.dataPoint;
            m0 = scaleFx(m0, this.inTangent, dt);
            m1 = scaleFx(m1, to.outTangent, dt);
            var t_3 = t * t * t;
            var t_2 = t * t;
            var f_0 = 2 * t_3 - 3 * t_2 + 1;
            var f_1 = t_3 - 2 * t_2 + t;
            var f_2 = -2 * t_3 + 3 * t_2;
            var f_3 = t_3 - t_2;
            tempValue = scaleFx(tempValue, p0, f_0);
            tempValue = scaleAndAdd(tempValue, tempValue, m0, f_1);
            tempValue = scaleAndAdd(tempValue, tempValue, p1, f_2);
            tempValue = scaleAndAdd(tempValue, tempValue, m1, f_3);
            return tempValue;
          };
          _proto.getNoLerp = function getNoLerp() {
            return this.dataPoint;
          };
          return CubicSplineValueClass;
        }(), (_initializer = applyDecoratedInitializer(_class2.prototype, "dataPoint", [serializable$j], function () {
          return new ConstructorX();
        }), _initializer2 = applyDecoratedInitializer(_class2.prototype, "inTangent", [serializable$j], function () {
          return new ConstructorX();
        }), _initializer3 = applyDecoratedInitializer(_class2.prototype, "outTangent", [serializable$j], function () {
          return new ConstructorX();
        })), _class2)) || _class);
        if (ConstructorX === Quat) {
          var _lerp = CubicSplineValueClass.prototype.lerp;
          CubicSplineValueClass.prototype.lerp = function (to, t, dt) {
            var result = _lerp.call(this, to, t, dt);
            Quat.normalize(result, result);
            return result;
          };
        }
        return CubicSplineValueClass;
      }
      var CubicSplineVec2Value = makeCubicSplineValueConstructor('cc.CubicSplineVec2Value', Vec2, Vec2.multiplyScalar, Vec2.scaleAndAdd);
      var CubicSplineVec3Value = makeCubicSplineValueConstructor('cc.CubicSplineVec3Value', Vec3, Vec3.multiplyScalar, Vec3.scaleAndAdd);
      var CubicSplineVec4Value = makeCubicSplineValueConstructor('cc.CubicSplineVec4Value', Vec4, Vec4.multiplyScalar, Vec4.scaleAndAdd);
      var CubicSplineQuatValue = makeCubicSplineValueConstructor('cc.CubicSplineQuatValue', Quat, Quat.multiplyScalar, Quat.scaleAndAdd);
      var CubicSplineNumberValue = (_dec2$1h = ccclass$n('cc.CubicSplineNumberValue'), _dec2$1h(_class4$j = (_class5$l = function () {
        function CubicSplineNumberValue(dataPoint, inTangent, outTangent) {
          this.dataPoint = _initializer4$w && _initializer4$w();
          this.inTangent = _initializer5$m && _initializer5$m();
          this.outTangent = _initializer6$g && _initializer6$g();
          this.dataPoint = dataPoint;
          this.inTangent = inTangent;
          this.outTangent = outTangent;
        }
        var _proto2 = CubicSplineNumberValue.prototype;
        _proto2.lerp = function lerp(to, t, dt) {
          var p0 = this.dataPoint;
          var p1 = to.dataPoint;
          var m0 = this.outTangent * dt;
          var m1 = to.inTangent * dt;
          var t_3 = t * t * t;
          var t_2 = t * t;
          var f_0 = 2 * t_3 - 3 * t_2 + 1;
          var f_1 = t_3 - 2 * t_2 + t;
          var f_2 = -2 * t_3 + 3 * t_2;
          var f_3 = t_3 - t_2;
          return p0 * f_0 + m0 * f_1 + p1 * f_2 + m1 * f_3;
        };
        _proto2.getNoLerp = function getNoLerp() {
          return this.dataPoint;
        };
        return CubicSplineNumberValue;
      }(), (_initializer4$w = applyDecoratedInitializer(_class5$l.prototype, "dataPoint", [serializable$j], function () {
        return 0;
      }), _initializer5$m = applyDecoratedInitializer(_class5$l.prototype, "inTangent", [serializable$j], function () {
        return 0;
      }), _initializer6$g = applyDecoratedInitializer(_class5$l.prototype, "outTangent", [serializable$j], function () {
        return 0;
      })), _class5$l)) || _class4$j);

      var _dec$1G, _class$1F;
      var RealTrack = (_dec$1G = ccclass$n(CLASS_NAME_PREFIX_ANIM + "RealTrack"), _dec$1G(_class$1F = function (_SingleChannelTrack) {
        _inheritsLoose(RealTrack, _SingleChannelTrack);
        function RealTrack() {
          return _SingleChannelTrack.apply(this, arguments) || this;
        }
        var _proto = RealTrack.prototype;
        _proto.createCurve = function createCurve() {
          return new RealCurve();
        };
        return RealTrack;
      }(SingleChannelTrack)) || _class$1F);

      function maskIfEmpty(curve) {
        return curve.keyFramesCount === 0 ? undefined : curve;
      }

      var _dec$1F, _class$1E, _class2$1t, _initializer$1k, _initializer2$12;
      var CHANNEL_NAMES$2 = ['X', 'Y', 'Z', 'W'];
      var VectorTrack = (_dec$1F = ccclass$n(CLASS_NAME_PREFIX_ANIM + "VectorTrack"), _dec$1F(_class$1E = (_class2$1t = function (_Track) {
        _inheritsLoose(VectorTrack, _Track);
        function VectorTrack() {
          var _this;
          _this = _Track.call(this) || this;
          _this._channels = _initializer$1k && _initializer$1k();
          _this._nComponents = _initializer2$12 && _initializer2$12();
          _this._channels = new Array(4);
          for (var i = 0; i < _this._channels.length; ++i) {
            var channel = new Channel(new RealCurve());
            channel.name = CHANNEL_NAMES$2[i];
            _this._channels[i] = channel;
          }
          return _this;
        }
        var _proto = VectorTrack.prototype;
        _proto.channels = function channels() {
          return this._channels;
        };
        _proto[createEvalSymbol] = function () {
          switch (this._nComponents) {
            default:
            case 2:
              return new Vec2TrackEval(maskIfEmpty(this._channels[0].curve), maskIfEmpty(this._channels[1].curve));
            case 3:
              return new Vec3TrackEval(maskIfEmpty(this._channels[0].curve), maskIfEmpty(this._channels[1].curve), maskIfEmpty(this._channels[2].curve));
            case 4:
              return new Vec4TrackEval(maskIfEmpty(this._channels[0].curve), maskIfEmpty(this._channels[1].curve), maskIfEmpty(this._channels[2].curve), maskIfEmpty(this._channels[3].curve));
          }
        };
        _createClass(VectorTrack, [{
          key: "componentsCount",
          get: function get() {
            return this._nComponents;
          },
          set: function set(value) {
            this._nComponents = value;
          }
        }]);
        return VectorTrack;
      }(Track), (_initializer$1k = applyDecoratedInitializer(_class2$1t.prototype, "_channels", [serializable$j], null), _initializer2$12 = applyDecoratedInitializer(_class2$1t.prototype, "_nComponents", [serializable$j], function () {
        return 4;
      })), _class2$1t)) || _class$1E);
      var Vec2TrackEval = function () {
        function Vec2TrackEval(_x, _y) {
          this._result = new Vec2();
          this._x = _x;
          this._y = _y;
        }
        var _proto2 = Vec2TrackEval.prototype;
        _proto2.evaluate = function evaluate(time, defaultValue) {
          if (defaultValue) {
            Vec2.copy(this._result, defaultValue);
          }
          if (this._x) {
            this._result.x = this._x.evaluate(time);
          }
          if (this._y) {
            this._result.y = this._y.evaluate(time);
          }
          return this._result;
        };
        _createClass(Vec2TrackEval, [{
          key: "requiresDefault",
          get: function get() {
            return !this._x || !this._y;
          }
        }]);
        return Vec2TrackEval;
      }();
      var Vec3TrackEval = function () {
        function Vec3TrackEval(_x, _y, _z) {
          this._result = new Vec3();
          this._x = _x;
          this._y = _y;
          this._z = _z;
        }
        var _proto3 = Vec3TrackEval.prototype;
        _proto3.evaluate = function evaluate(time, defaultValue) {
          var _x = this._x,
            _y = this._y,
            _z = this._z,
            _result = this._result;
          if (defaultValue) {
            Vec3.copy(_result, defaultValue);
          }
          if (_x) {
            _result.x = _x.evaluate(time);
          }
          if (_y) {
            _result.y = _y.evaluate(time);
          }
          if (_z) {
            _result.z = _z.evaluate(time);
          }
          return _result;
        };
        _createClass(Vec3TrackEval, [{
          key: "requiresDefault",
          get: function get() {
            return !this._x || !this._y || !this._z;
          }
        }]);
        return Vec3TrackEval;
      }();
      var Vec4TrackEval = function () {
        function Vec4TrackEval(_x, _y, _z, _w) {
          this._result = new Vec4();
          this._x = _x;
          this._y = _y;
          this._z = _z;
          this._w = _w;
        }
        var _proto4 = Vec4TrackEval.prototype;
        _proto4.evaluate = function evaluate(time, defaultValue) {
          if (defaultValue) {
            Vec4.copy(this._result, defaultValue);
          }
          if (this._x) {
            this._result.x = this._x.evaluate(time);
          }
          if (this._y) {
            this._result.y = this._y.evaluate(time);
          }
          if (this._z) {
            this._result.z = this._z.evaluate(time);
          }
          if (this._w) {
            this._result.w = this._w.evaluate(time);
          }
          return this._result;
        };
        _createClass(Vec4TrackEval, [{
          key: "requiresDefault",
          get: function get() {
            return !this._x || !this._y || !this._z || !this._w;
          }
        }]);
        return Vec4TrackEval;
      }();

      var _dec$1E, _class$1D;
      var QuatTrack = (_dec$1E = ccclass$n(CLASS_NAME_PREFIX_ANIM + "QuatTrack"), _dec$1E(_class$1D = function (_SingleChannelTrack) {
        _inheritsLoose(QuatTrack, _SingleChannelTrack);
        function QuatTrack() {
          return _SingleChannelTrack.apply(this, arguments) || this;
        }
        var _proto = QuatTrack.prototype;
        _proto.createCurve = function createCurve() {
          return new QuatCurve();
        };
        _proto[createEvalSymbol] = function () {
          return new QuatTrackEval(this.channels()[0].curve);
        };
        return QuatTrack;
      }(SingleChannelTrack)) || _class$1D);
      var QuatTrackEval = function () {
        function QuatTrackEval(_curve) {
          this._result = new Quat();
          this._curve = _curve;
        }
        var _proto2 = QuatTrackEval.prototype;
        _proto2.evaluate = function evaluate(time) {
          this._curve.evaluate(time, this._result);
          return this._result;
        };
        _createClass(QuatTrackEval, [{
          key: "requiresDefault",
          get: function get() {
            return false;
          }
        }]);
        return QuatTrackEval;
      }();

      var _dec$1D, _class$1C, _class2$1s, _initializer$1j;
      var CHANNEL_NAMES$1 = ['Red', 'Green', 'Blue', 'Alpha'];
      var ColorTrack = (_dec$1D = ccclass$n(CLASS_NAME_PREFIX_ANIM + "ColorTrack"), _dec$1D(_class$1C = (_class2$1s = function (_Track) {
        _inheritsLoose(ColorTrack, _Track);
        function ColorTrack() {
          var _this;
          _this = _Track.call(this) || this;
          _this._channels = _initializer$1j && _initializer$1j();
          _this._channels = new Array(4);
          for (var i = 0; i < _this._channels.length; ++i) {
            var channel = new Channel(new RealCurve());
            channel.name = CHANNEL_NAMES$1[i];
            _this._channels[i] = channel;
          }
          return _this;
        }
        var _proto = ColorTrack.prototype;
        _proto.channels = function channels() {
          return this._channels;
        };
        _proto[createEvalSymbol] = function () {
          return new ColorTrackEval(maskIfEmpty(this._channels[0].curve), maskIfEmpty(this._channels[1].curve), maskIfEmpty(this._channels[2].curve), maskIfEmpty(this._channels[3].curve));
        };
        return ColorTrack;
      }(Track), (_initializer$1j = applyDecoratedInitializer(_class2$1s.prototype, "_channels", [serializable$j], null)), _class2$1s)) || _class$1C);
      var ColorTrackEval = function () {
        function ColorTrackEval(_x, _y, _z, _w) {
          this._result = new Color$1();
          this._x = _x;
          this._y = _y;
          this._z = _z;
          this._w = _w;
        }
        var _proto2 = ColorTrackEval.prototype;
        _proto2.evaluate = function evaluate(time, defaultValue) {
          if (defaultValue) {
            Color$1.copy(this._result, defaultValue);
          }
          if (this._x) {
            this._result.r = this._x.evaluate(time);
          }
          if (this._y) {
            this._result.g = this._y.evaluate(time);
          }
          if (this._z) {
            this._result.b = this._z.evaluate(time);
          }
          if (this._w) {
            this._result.a = this._w.evaluate(time);
          }
          return this._result;
        };
        _createClass(ColorTrackEval, [{
          key: "requiresDefault",
          get: function get() {
            return !this._x || !this._y || !this._z || !this._w;
          }
        }]);
        return ColorTrackEval;
      }();

      var _dec$1C, _class$1B, _class2$1r, _initializer$1i;
      var CHANNEL_NAMES = ['Width', 'Height'];
      var SizeTrack = (_dec$1C = ccclass$n(CLASS_NAME_PREFIX_ANIM + "SizeTrack"), _dec$1C(_class$1B = (_class2$1r = function (_Track) {
        _inheritsLoose(SizeTrack, _Track);
        function SizeTrack() {
          var _this;
          _this = _Track.call(this) || this;
          _this._channels = _initializer$1i && _initializer$1i();
          _this._channels = new Array(2);
          for (var i = 0; i < _this._channels.length; ++i) {
            var channel = new Channel(new RealCurve());
            channel.name = CHANNEL_NAMES[i];
            _this._channels[i] = channel;
          }
          return _this;
        }
        var _proto = SizeTrack.prototype;
        _proto.channels = function channels() {
          return this._channels;
        };
        _proto[createEvalSymbol] = function () {
          return new SizeTrackEval(maskIfEmpty(this._channels[0].curve), maskIfEmpty(this._channels[1].curve));
        };
        return SizeTrack;
      }(Track), (_initializer$1i = applyDecoratedInitializer(_class2$1r.prototype, "_channels", [serializable$j], null)), _class2$1r)) || _class$1B);
      var SizeTrackEval = function () {
        function SizeTrackEval(_width, _height) {
          this._result = new Size$1();
          this._width = _width;
          this._height = _height;
        }
        var _proto2 = SizeTrackEval.prototype;
        _proto2.evaluate = function evaluate(time, defaultValue) {
          if (defaultValue) {
            this._result.x = defaultValue.x;
            this._result.y = defaultValue.y;
          }
          if (this._width) {
            this._result.width = this._width.evaluate(time);
          }
          if (this._height) {
            this._result.height = this._height.evaluate(time);
          }
          return this._result;
        };
        _createClass(SizeTrackEval, [{
          key: "requiresDefault",
          get: function get() {
            return !this._width || !this._height;
          }
        }]);
        return SizeTrackEval;
      }();

      var _dec$1B, _class$1A;
      var ObjectTrack = (_dec$1B = ccclass$n(CLASS_NAME_PREFIX_ANIM + "ObjectTrack"), _dec$1B(_class$1A = function (_SingleChannelTrack) {
        _inheritsLoose(ObjectTrack, _SingleChannelTrack);
        function ObjectTrack() {
          return _SingleChannelTrack.apply(this, arguments) || this;
        }
        var _proto = ObjectTrack.prototype;
        _proto.createCurve = function createCurve() {
          return new ObjectCurve();
        };
        return ObjectTrack;
      }(SingleChannelTrack)) || _class$1A);

      var ownerSymbol = Symbol('[[Owner]]');
      function assertsOwnedBy(mastered, owner) {
        assertIsTrue(mastered[ownerSymbol] === owner);
      }
      function own(mastered, owner) {
        {
          mastered[ownerSymbol] = owner;
        }
      }
      function markAsDangling(mastered) {
        {
          mastered[ownerSymbol] = undefined;
        }
      }

      var VariableType;
      (function (VariableType) {
        VariableType[VariableType["FLOAT"] = 0] = "FLOAT";
        VariableType[VariableType["BOOLEAN"] = 1] = "BOOLEAN";
        VariableType[VariableType["TRIGGER"] = 2] = "TRIGGER";
        VariableType[VariableType["INTEGER"] = 3] = "INTEGER";
        VariableType[VariableType["VEC3_experimental"] = 4] = "VEC3_experimental";
        VariableType[VariableType["QUAT_experimental"] = 5] = "QUAT_experimental";
      })(VariableType || (VariableType = {}));
      var createInstanceTag = Symbol('CreateInstance');
      var VarInstanceBase = function () {
        function VarInstanceBase(type) {
          this._refs = [];
          this.type = type;
        }
        var _proto = VarInstanceBase.prototype;
        _proto.bind = function bind(fn, thisArg) {
          for (var _len = arguments.length, args = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
            args[_key - 2] = arguments[_key];
          }
          this._refs.push({
            fn: fn,
            thisArg: thisArg,
            args: args
          });
          return this.getValue();
        };
        _createClass(VarInstanceBase, [{
          key: "value",
          get: function get() {
            return this.getValue();
          },
          set: function set(value) {
            this.setValue(value);
            for (var _iterator = _createForOfIteratorHelperLoose(this._refs), _step; !(_step = _iterator()).done;) {
              var _step$value = _step.value,
                fn = _step$value.fn,
                thisArg = _step$value.thisArg,
                args = _step$value.args;
              fn.call.apply(fn, [thisArg, value].concat(args));
            }
          }
        }]);
        return VarInstanceBase;
      }();

      var _dec$1A, _class$1z, _class2$1q, _initializer$1h, _initializer2$11;
      var PlainVariable = (_dec$1A = ccclass$n('cc.animation.PlainVariable'), _dec$1A(_class$1z = (_class2$1q = function () {
        function PlainVariable(type) {
          this._type = _initializer$1h && _initializer$1h();
          this._value = _initializer2$11 && _initializer2$11();
          if (typeof type === 'undefined') {
            return;
          }
          this._type = type;
          switch (type) {
            default:
              break;
            case VariableType.FLOAT:
              this._value = 0.0;
              break;
            case VariableType.INTEGER:
              this._value = 0;
              break;
            case VariableType.BOOLEAN:
              this._value = false;
              break;
          }
        }
        var _proto = PlainVariable.prototype;
        _proto[createInstanceTag] = function () {
          return new VarInstancePrimitive(this._type, this._value);
        };
        _createClass(PlainVariable, [{
          key: "type",
          get: function get() {
            return this._type;
          }
        }, {
          key: "value",
          get: function get() {
            return this._value;
          },
          set: function set(value) {
            {
              switch (this._type) {
                default:
                  break;
                case VariableType.FLOAT:
                  assertIsTrue(typeof value === 'number');
                  break;
                case VariableType.INTEGER:
                  assertIsTrue(Number.isInteger(value));
                  break;
                case VariableType.BOOLEAN:
                  assertIsTrue(typeof value === 'boolean');
                  break;
              }
            }
            this._value = value;
          }
        }]);
        return PlainVariable;
      }(), (_initializer$1h = applyDecoratedInitializer(_class2$1q.prototype, "_type", [serializable$j], function () {
        return VariableType.FLOAT;
      }), _initializer2$11 = applyDecoratedInitializer(_class2$1q.prototype, "_value", [serializable$j], function () {
        return 0.0;
      })), _class2$1q)) || _class$1z);
      var VarInstancePrimitive = function (_VarInstanceBase) {
        _inheritsLoose(VarInstancePrimitive, _VarInstanceBase);
        function VarInstancePrimitive(type, value) {
          var _this;
          _this = _VarInstanceBase.call(this, type) || this;
          _this._value = void 0;
          _this._value = value;
          return _this;
        }
        var _proto2 = VarInstancePrimitive.prototype;
        _proto2.getValue = function getValue() {
          return this._value;
        };
        _proto2.setValue = function setValue(value) {
          this._value = value;
        };
        return VarInstancePrimitive;
      }(VarInstanceBase);

      var _dec$1z, _class$1y, _class2$1p, _initializer$1g;
      var TriggerResetMode;
      (function (TriggerResetMode) {
        TriggerResetMode[TriggerResetMode["AFTER_CONSUMED"] = 0] = "AFTER_CONSUMED";
        TriggerResetMode[TriggerResetMode["NEXT_FRAME_OR_AFTER_CONSUMED"] = 1] = "NEXT_FRAME_OR_AFTER_CONSUMED";
      })(TriggerResetMode || (TriggerResetMode = {}));
      var TRIGGER_VARIABLE_FLAG_VALUE_START = 0;
      var TRIGGER_VARIABLE_FLAG_VALUE_MASK = 1;
      var TRIGGER_VARIABLE_FLAG_RESET_MODE_START = 1;
      var TRIGGER_VARIABLE_FLAG_RESET_MODE_MASK = 6;
      var TRIGGER_VARIABLE_DEFAULT_FLAGS = 0;
      assertIsTrue((0 << TRIGGER_VARIABLE_FLAG_VALUE_START | TriggerResetMode.AFTER_CONSUMED << TRIGGER_VARIABLE_FLAG_RESET_MODE_START) === TRIGGER_VARIABLE_DEFAULT_FLAGS);
      var TriggerVariable = (_dec$1z = ccclass$n('cc.animation.TriggerVariable'), _dec$1z(_class$1y = (_class2$1p = function () {
        function TriggerVariable() {
          this._flags = _initializer$1g && _initializer$1g();
        }
        var _proto = TriggerVariable.prototype;
        _proto[createInstanceTag] = function () {
          return new VarInstanceTrigger(this.value, this.resetMode);
        };
        _createClass(TriggerVariable, [{
          key: "type",
          get: function get() {
            return VariableType.TRIGGER;
          }
        }, {
          key: "value",
          get: function get() {
            return !!((this._flags & TRIGGER_VARIABLE_FLAG_VALUE_MASK) >> TRIGGER_VARIABLE_FLAG_VALUE_START);
          },
          set: function set(value) {
            if (value) {
              this._flags |= 1 << TRIGGER_VARIABLE_FLAG_VALUE_START;
            } else {
              this._flags &= ~(1 << TRIGGER_VARIABLE_FLAG_VALUE_START);
            }
          }
        }, {
          key: "resetMode",
          get: function get() {
            return (this._flags & TRIGGER_VARIABLE_FLAG_RESET_MODE_MASK) >> TRIGGER_VARIABLE_FLAG_RESET_MODE_START;
          },
          set: function set(value) {
            this._flags &= ~TRIGGER_VARIABLE_FLAG_RESET_MODE_MASK;
            this._flags |= value << TRIGGER_VARIABLE_FLAG_RESET_MODE_START;
          }
        }]);
        return TriggerVariable;
      }(), (_initializer$1g = applyDecoratedInitializer(_class2$1p.prototype, "_flags", [serializable$j], function () {
        return TRIGGER_VARIABLE_DEFAULT_FLAGS;
      })), _class2$1p)) || _class$1y);
      var VarInstanceTrigger = function (_VarInstanceBase) {
        _inheritsLoose(VarInstanceTrigger, _VarInstanceBase);
        function VarInstanceTrigger(value, resetMode) {
          var _this;
          _this = _VarInstanceBase.call(this, VariableType.TRIGGER) || this;
          _this.resetMode = TriggerResetMode.AFTER_CONSUMED;
          _this._value = void 0;
          _this.resetMode = resetMode;
          _this._value = value;
          return _this;
        }
        var _proto2 = VarInstanceTrigger.prototype;
        _proto2.getValue = function getValue() {
          return this._value;
        };
        _proto2.setValue = function setValue(value) {
          this._value = value;
        };
        return VarInstanceTrigger;
      }(VarInstanceBase);

      var _dec$1y, _class$1x, _class2$1o, _initializer$1f;
      var Vec3Variable = (_dec$1y = ccclass$n('cc.animation.Vec3Variable'), _dec$1y(_class$1x = (_class2$1o = function () {
        function Vec3Variable() {
          this._value = _initializer$1f && _initializer$1f();
        }
        var _proto = Vec3Variable.prototype;
        _proto[createInstanceTag] = function () {
          return new VarInstanceVec3(this.value);
        };
        _createClass(Vec3Variable, [{
          key: "type",
          get: function get() {
            return VariableType.VEC3_experimental;
          }
        }, {
          key: "value",
          get: function get() {
            return this._value;
          },
          set: function set(value) {
            Vec3.copy(this._value, value);
          }
        }]);
        return Vec3Variable;
      }(), (_initializer$1f = applyDecoratedInitializer(_class2$1o.prototype, "_value", [serializable$j], function () {
        return new Vec3();
      })), _class2$1o)) || _class$1x);
      var VarInstanceVec3 = function (_VarInstanceBase) {
        _inheritsLoose(VarInstanceVec3, _VarInstanceBase);
        function VarInstanceVec3(value) {
          var _this;
          _this = _VarInstanceBase.call(this, VariableType.VEC3_experimental) || this;
          _this._value = new Vec3();
          Vec3.copy(_this._value, value);
          return _this;
        }
        var _proto2 = VarInstanceVec3.prototype;
        _proto2.getValue = function getValue() {
          return this._value;
        };
        _proto2.setValue = function setValue(value) {
          assertIsTrue(value instanceof Vec3);
          Vec3.copy(this._value, value);
        };
        return VarInstanceVec3;
      }(VarInstanceBase);

      var _dec$1x, _class$1w, _class2$1n, _initializer$1e;
      var QuatVariable = (_dec$1x = ccclass$n('cc.animation.QuatVariable'), _dec$1x(_class$1w = (_class2$1n = function () {
        function QuatVariable() {
          this._value = _initializer$1e && _initializer$1e();
        }
        var _proto = QuatVariable.prototype;
        _proto[createInstanceTag] = function () {
          return new VarInstanceQuat(this._value);
        };
        _createClass(QuatVariable, [{
          key: "type",
          get: function get() {
            return VariableType.QUAT_experimental;
          }
        }, {
          key: "value",
          get: function get() {
            return this._value;
          },
          set: function set(value) {
            Quat.copy(this._value, value);
          }
        }]);
        return QuatVariable;
      }(), (_initializer$1e = applyDecoratedInitializer(_class2$1n.prototype, "_value", [serializable$j], function () {
        return new Quat();
      })), _class2$1n)) || _class$1w);
      var VarInstanceQuat = function (_VarInstanceBase) {
        _inheritsLoose(VarInstanceQuat, _VarInstanceBase);
        function VarInstanceQuat(value) {
          var _this;
          _this = _VarInstanceBase.call(this, VariableType.QUAT_experimental) || this;
          _this._value = new Quat();
          Quat.copy(_this._value, value);
          return _this;
        }
        var _proto2 = VarInstanceQuat.prototype;
        _proto2.getValue = function getValue() {
          return this._value;
        };
        _proto2.setValue = function setValue(value) {
          assertIsTrue(value instanceof Quat);
          Quat.copy(this._value, value);
        };
        return VarInstanceQuat;
      }(VarInstanceBase);

      function createVariable(type, initialValue) {
        var variable;
        switch (type) {
          case VariableType.FLOAT:
          case VariableType.INTEGER:
          case VariableType.BOOLEAN:
            variable = new PlainVariable(type);
            break;
          case VariableType.TRIGGER:
            variable = new TriggerVariable();
            break;
          case VariableType.VEC3_experimental:
            variable = new Vec3Variable();
            break;
          case VariableType.QUAT_experimental:
            variable = new QuatVariable();
            break;
          default:
            throw new Error("Unknown variable type " + type);
        }
        if (typeof initialValue !== 'undefined') {
          variable.value = initialValue;
        }
        return variable;
      }

      var InvalidTransitionError = function (_Error) {
        _inheritsLoose(InvalidTransitionError, _Error);
        function InvalidTransitionError(type) {
          var _this;
          _this = _Error.call(this, type + " transition is invalid") || this;
          _this.name = 'TransitionRejectError';
          return _this;
        }
        return InvalidTransitionError;
      }(_wrapNativeSuper(Error));
      var VariableNotDefinedError = function (_Error2) {
        _inheritsLoose(VariableNotDefinedError, _Error2);
        function VariableNotDefinedError(name) {
          return _Error2.call(this, "Graph variable " + name + " is not defined") || this;
        }
        return VariableNotDefinedError;
      }(_wrapNativeSuper(Error));
      var VariableTypeMismatchedError = function (_Error3) {
        _inheritsLoose(VariableTypeMismatchedError, _Error3);
        function VariableTypeMismatchedError(name, expected, received) {
          return _Error3.call(this, "Expect graph variable " + name + " to have type '" + expected + "' instead of received '" + (received !== null && received !== void 0 ? received : typeof received) + "'") || this;
        }
        return VariableTypeMismatchedError;
      }(_wrapNativeSuper(Error));

      var Destroyed = CCObject.Flags.Destroyed;
      var PersistentMask = CCObject.Flags.PersistentMask;
      var objsToClearTmpVar = [];
      function hasImplementedInstantiate(original) {
        return typeof original._instantiate === 'function';
      }
      function instantiate(original, internalForce) {
        var clone;
        if (isCCObject(original)) {
          if (hasImplementedInstantiate(original)) {
            legacyCC.game._isCloning = true;
            clone = original._instantiate(null, true);
            legacyCC.game._isCloning = false;
            return clone;
          } else if (original instanceof legacyCC.Asset) {
            throw new TypeError(getError(6903));
          }
        }
        legacyCC.game._isCloning = true;
        clone = doInstantiate(original);
        legacyCC.game._isCloning = false;
        return clone;
      }
      function doInstantiate(obj, parent) {
        var clone;
        if (obj._iN$t) {
          clone = obj._iN$t;
        } else if (obj.constructor) {
          var Klass = obj.constructor;
          clone = new Klass();
        } else {
          clone = Object.create(null);
        }
        enumerateObject(obj, clone, parent);
        for (var i = 0, len = objsToClearTmpVar.length; i < len; ++i) {
          objsToClearTmpVar[i]._iN$t = null;
        }
        objsToClearTmpVar.length = 0;
        return clone;
      }
      function enumerateCCClass(klass, obj, clone, parent) {
        var props = klass.__values__;
        for (var p = 0; p < props.length; p++) {
          var key = props[p];
          var value = obj[key];
          if (typeof value === 'object' && value) {
            var initValue = clone[key];
            if (initValue instanceof ValueType && initValue.constructor === value.constructor) {
              initValue.set(value);
            } else {
              clone[key] = value._iN$t || instantiateObj(value, parent);
            }
          } else {
            clone[key] = value;
          }
        }
      }
      function enumerateObject(obj, clone, parent) {
        value(obj, '_iN$t', clone, true);
        objsToClearTmpVar.push(obj);
        var klass = obj.constructor;
        if (isCCClassOrFastDefined(klass)) {
          enumerateCCClass(klass, obj, clone, parent);
        } else {
          for (var key in obj) {
            if (!obj.hasOwnProperty(key) || key.charCodeAt(0) === 95 && key.charCodeAt(1) === 95 && key !== '__type__' && key !== '__prefab') {
              continue;
            }
            var value$1 = obj[key];
            if (typeof value$1 === 'object' && value$1) {
              if (value$1 === clone) {
                continue;
              }
              clone[key] = value$1._iN$t || instantiateObj(value$1, parent);
            } else {
              clone[key] = value$1;
            }
          }
        }
        if (isCCObject(obj)) {
          clone._objFlags &= PersistentMask;
        }
      }
      function instantiateObj(obj, parent) {
        if (obj instanceof ValueType) {
          return obj.clone();
        }
        if (obj instanceof legacyCC.Asset) {
          return obj;
        }
        var clone;
        if (ArrayBuffer.isView(obj)) {
          var len = obj.length;
          clone = new obj.constructor(len);
          obj._iN$t = clone;
          objsToClearTmpVar.push(obj);
          for (var i = 0; i < len; ++i) {
            clone[i] = obj[i];
          }
          return clone;
        }
        if (Array.isArray(obj)) {
          var _len = obj.length;
          clone = new Array(_len);
          obj._iN$t = clone;
          objsToClearTmpVar.push(obj);
          for (var _i = 0; _i < _len; ++_i) {
            var value = obj[_i];
            if (typeof value === 'object' && value) {
              clone[_i] = value._iN$t || instantiateObj(value, parent);
            } else {
              clone[_i] = value;
            }
          }
          return clone;
        } else if (obj._objFlags & Destroyed) {
          return null;
        }
        var ctor = obj.constructor;
        if (isCCClassOrFastDefined(ctor)) {
          if (parent) {
            if (parent instanceof Component) {
              if (obj instanceof Node$1 || obj instanceof Component) {
                return obj;
              }
            } else if (parent instanceof Node$1) {
              if (obj instanceof Node$1) {
                if (!obj.isChildOf(parent)) {
                  return obj;
                }
              } else if (obj instanceof Component) {
                if (obj.node && !obj.node.isChildOf(parent)) {
                  return obj;
                }
              }
            }
          }
          clone = new ctor();
        } else if (ctor === Object) {
          clone = {};
        } else if (!ctor) {
          clone = Object.create(null);
        } else {
          return obj;
        }
        enumerateObject(obj, clone, parent);
        return clone;
      }
      instantiate._clone = doInstantiate;
      legacyCC.instantiate = instantiate;

      function cloneAnimationGraphEditorExtrasFrom(object) {
        var editorExtras = object[editorExtrasTag];
        if (typeof editorExtras === 'object' && editorExtras) {
          var _maybeCloneableEditor;
          var maybeCloneableEditorExtras = editorExtras;
          return (_maybeCloneableEditor = maybeCloneableEditorExtras.clone) === null || _maybeCloneableEditor === void 0 ? void 0 : _maybeCloneableEditor.call(maybeCloneableEditorExtras, object);
        }
        return undefined;
      }

      var _dec$1w, _class$1v, _class2$1m, _initializer$1d, _dec2$1g, _class4$i, _class5$k, _initializer2$10;
      var outgoingsSymbol = Symbol('[[Outgoing transitions]]');
      var incomingsSymbol = Symbol('[[Incoming transitions]]');
      var ccclass$f = ccclass$n,
        serializable$c = serializable$j;
      var State$1 = (_dec$1w = ccclass$f('cc.animation.State'), _dec$1w(_class$1v = (_class2$1m = function (_EditorExtendable) {
        _inheritsLoose(State, _EditorExtendable);
        function State() {
          var _this;
          _this = _EditorExtendable.call(this) || this;
          _this.name = _initializer$1d && _initializer$1d();
          _this[outgoingsSymbol] = [];
          _this[incomingsSymbol] = [];
          return _this;
        }
        var _proto = State.prototype;
        _proto.copyTo = function copyTo(that) {
          that.name = this.name;
          that[editorExtrasTag] = cloneAnimationGraphEditorExtrasFrom(this);
        };
        return State;
      }(EditorExtendable), (_initializer$1d = applyDecoratedInitializer(_class2$1m.prototype, "name", [serializable$c], function () {
        return '';
      })), _class2$1m)) || _class$1v);
      var InteractiveState = (_dec2$1g = ccclass$f(CLASS_NAME_PREFIX_ANIM + "InteractiveState"), _dec2$1g(_class4$i = (_class5$k = function (_State) {
        _inheritsLoose(InteractiveState, _State);
        function InteractiveState() {
          var _this2;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this2 = _State.call.apply(_State, [this].concat(args)) || this;
          _this2._components = _initializer2$10 && _initializer2$10();
          return _this2;
        }
        var _proto2 = InteractiveState.prototype;
        _proto2.addComponent = function addComponent(constructor) {
          var component = new constructor();
          this._components.push(component);
          return component;
        };
        _proto2.removeComponent = function removeComponent(component) {
          remove(this._components, component);
        };
        _proto2.instantiateComponents = function instantiateComponents() {
          var instantiatedComponents = this._components.map(function (component) {
            var instantiated = instantiate(component);
            return instantiated;
          });
          return instantiatedComponents;
        };
        _proto2.copyTo = function copyTo(that) {
          _State.prototype.copyTo.call(this, that);
          that._components = this.instantiateComponents();
        };
        _createClass(InteractiveState, [{
          key: "components",
          get: function get() {
            return this._components;
          }
        }]);
        return InteractiveState;
      }(State$1), (_initializer2$10 = applyDecoratedInitializer(_class5$k.prototype, "_components", [serializable$c], function () {
        return [];
      })), _class5$k)) || _class4$i);

      function invokeComponentMethodsEngagedInAnimationEvent(node, methodName, args) {
        var components = node.components;
        var nComponents = components.length;
        for (var iComponent = 0; iComponent < nComponents; ++iComponent) {
          var component = components[iComponent];
          var fx = component[methodName];
          if (typeof fx === 'function') {
            fx.apply(component, args);
          }
        }
      }

      var _dec$1v, _class$1u, _class2$1l, _initializer$1c;
      var AnimationGraphEventBinding = (_dec$1v = ccclass$n(CLASS_NAME_PREFIX_ANIM + "AnimationGraphEventBinding"), _dec$1v(_class$1u = (_class2$1l = function () {
        function AnimationGraphEventBinding() {
          this.methodName = _initializer$1c && _initializer$1c();
        }
        var _proto = AnimationGraphEventBinding.prototype;
        _proto.emit = function emit(origin) {
          if (!this.methodName) {
            return;
          }
          invokeComponentMethodsEngagedInAnimationEvent(origin, this.methodName, []);
        };
        _proto.copyTo = function copyTo(that) {
          that.methodName = this.methodName;
          return this;
        };
        _createClass(AnimationGraphEventBinding, [{
          key: "isBound",
          get: function get() {
            return !!this.methodName;
          }
        }]);
        return AnimationGraphEventBinding;
      }(), (_initializer$1c = applyDecoratedInitializer(_class2$1l.prototype, "methodName", [serializable$j], function () {
        return '';
      })), _class2$1l)) || _class$1u);

      var _dec$1u, _class$1t, _class2$1k, _initializer$1b, _initializer2$$, _initializer3$G, _initializer4$v, _initializer5$l, _initializer6$f;
      var MotionState = (_dec$1u = ccclass$n('cc.animation.Motion'), _dec$1u(_class$1t = (_class2$1k = function (_InteractiveState) {
        _inheritsLoose(MotionState, _InteractiveState);
        function MotionState() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _InteractiveState.call.apply(_InteractiveState, [this].concat(args)) || this;
          _this.motion = _initializer$1b && _initializer$1b();
          _this.speed = _initializer2$$ && _initializer2$$();
          _this.speedMultiplier = _initializer3$G && _initializer3$G();
          _this.speedMultiplierEnabled = _initializer4$v && _initializer4$v();
          _this.transitionInEventBinding = _initializer5$l && _initializer5$l();
          _this.transitionOutEventBinding = _initializer6$f && _initializer6$f();
          return _this;
        }
        var _proto = MotionState.prototype;
        _proto.__callOnAfterDeserializeRecursive = function __callOnAfterDeserializeRecursive() {
          var _this$motion;
          (_this$motion = this.motion) === null || _this$motion === void 0 ? void 0 : _this$motion.__callOnAfterDeserializeRecursive();
        };
        _proto.copyTo = function copyTo(that) {
          var _this$motion$clone, _this$motion2;
          _InteractiveState.prototype.copyTo.call(this, that);
          that.motion = (_this$motion$clone = (_this$motion2 = this.motion) === null || _this$motion2 === void 0 ? void 0 : _this$motion2.clone()) !== null && _this$motion$clone !== void 0 ? _this$motion$clone : null;
          that.speed = this.speed;
          that.speedMultiplier = this.speedMultiplier;
          that.speedMultiplierEnabled = this.speedMultiplierEnabled;
          this.transitionInEventBinding.copyTo(that.transitionInEventBinding);
          this.transitionOutEventBinding.copyTo(that.transitionOutEventBinding);
          return this;
        };
        return MotionState;
      }(InteractiveState), (_initializer$1b = applyDecoratedInitializer(_class2$1k.prototype, "motion", [serializable$j], function () {
        return null;
      }), _initializer2$$ = applyDecoratedInitializer(_class2$1k.prototype, "speed", [serializable$j], function () {
        return 1.0;
      }), _initializer3$G = applyDecoratedInitializer(_class2$1k.prototype, "speedMultiplier", [serializable$j], function () {
        return '';
      }), _initializer4$v = applyDecoratedInitializer(_class2$1k.prototype, "speedMultiplierEnabled", [serializable$j], function () {
        return false;
      }), _initializer5$l = applyDecoratedInitializer(_class2$1k.prototype, "transitionInEventBinding", [serializable$j], function () {
        return new AnimationGraphEventBinding();
      }), _initializer6$f = applyDecoratedInitializer(_class2$1k.prototype, "transitionOutEventBinding", [serializable$j], function () {
        return new AnimationGraphEventBinding();
      })), _class2$1k)) || _class$1t);

      var onAfterDeserializedTag = Symbol('[[OnAfterDeserialized]]');

      var _dec$1t, _class$1s;
      var AnimationGraphLike = (_dec$1t = ccclass$n(CLASS_NAME_PREFIX_ANIM + "AnimationGraphLike"), _dec$1t(_class$1s = function (_Asset) {
        _inheritsLoose(AnimationGraphLike, _Asset);
        function AnimationGraphLike() {
          return _Asset.apply(this, arguments) || this;
        }
        return AnimationGraphLike;
      }(Asset)) || _class$1s);

      function renameObjectProperty(object, originalPropertyKey, newPropertyKey) {
        var propertyIsEnumerable = Object.prototype.propertyIsEnumerable;
        if (!propertyIsEnumerable.call(object, originalPropertyKey)) {
          return object;
        }
        if (newPropertyKey in object) {
          return object;
        }
        var result = {};
        if (typeof originalPropertyKey === 'symbol') {
          Object.entries(object).forEach(function (_ref) {
            var k = _ref[0],
              v = _ref[1];
            result[k] = v;
          });
          Object.getOwnPropertySymbols(object).forEach(function (k) {
            if (!propertyIsEnumerable.call(object, k)) {
              return;
            }
            result[k === originalPropertyKey ? newPropertyKey : k] = object[k];
          });
        } else {
          Object.entries(object).forEach(function (_ref2) {
            var k = _ref2[0],
              v = _ref2[1];
            result[k === originalPropertyKey ? newPropertyKey : k] = v;
          });
          Object.getOwnPropertySymbols(object).forEach(function (k) {
            if (!propertyIsEnumerable.call(object, k)) {
              return;
            }
            result[k] = object[k];
          });
        }
        return result;
      }
      var createInstanceofProxy = function () {
        var isSymbolHasInstanceAvailable = false;
        try {
          var Array1 = function (_Symbol$hasInstance) {
            function Array1() {}
            Array1[_Symbol$hasInstance] = function (instance) {
              return Array.isArray(instance);
            };
            return Array1;
          }(Symbol.hasInstance);
          isSymbolHasInstanceAvailable = [] instanceof Array1;
        } catch (_unused) {
          isSymbolHasInstanceAvailable = false;
        }
        if (!isSymbolHasInstanceAvailable) {
          return function (constructor) {
            return constructor;
          };
        }
        return function (constructor) {
          function InstanceOfProxy() {
            throw new Error("This function can not be called as a constructor.");
          }
          Object.defineProperty(InstanceOfProxy, Symbol.hasInstance, {
            value: function value(instance) {
              return instance instanceof constructor;
            }
          });
          return InstanceOfProxy;
        };
      }();

      var _dec$1s, _class$1r, _class2$1j, _initializer$1a, _dec2$1f, _class4$h, _class5$j, _initializer2$_, _initializer3$F, _initializer4$u;
      var PoseGraphNodeShell = (_dec$1s = ccclass$n(CLASS_NAME_PREFIX_ANIM + "PoseGraphNodeShell"), _dec$1s(_class$1r = (_class2$1j = function (_EditorExtendable) {
        _inheritsLoose(PoseGraphNodeShell, _EditorExtendable);
        function PoseGraphNodeShell() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _EditorExtendable.call.apply(_EditorExtendable, [this].concat(args)) || this;
          _this._bindings = _initializer$1a && _initializer$1a();
          return _this;
        }
        var _proto = PoseGraphNodeShell.prototype;
        _proto.getBindings = function getBindings() {
          return this._bindings;
        };
        _proto.addBinding = function addBinding(inputPath, producer, outputIndex) {
          this._emplaceBinding(new PoseGraphNodeInputBinding(inputPath, producer, outputIndex));
        };
        _proto.deleteBinding = function deleteBinding(inputPath) {
          var index = this._findBindingIndex(inputPath);
          if (index >= 0) {
            this._bindings.splice(index, 1);
          }
        };
        _proto.moveArrayElementBindingForward = function moveArrayElementBindingForward(propertyKey, firstIndex, forward) {
          var bindings = this._bindings;
          var oldBindings = [];
          for (var iBinding = 0; iBinding < bindings.length; ++iBinding) {
            var binding = bindings[iBinding];
            var _binding$inputPath = binding.inputPath,
              consumerPropertyKey = _binding$inputPath[0],
              _binding$inputPath$ = _binding$inputPath[1],
              consumerElementIndex = _binding$inputPath$ === void 0 ? -1 : _binding$inputPath$;
            if (consumerPropertyKey === propertyKey && consumerElementIndex >= firstIndex) {
              oldBindings.push(binding);
              bindings.splice(iBinding, 1);
            }
          }
          for (var _i = 0, _oldBindings = oldBindings; _i < _oldBindings.length; _i++) {
            var oldBinding = _oldBindings[_i];
            var _oldBinding$inputPath = oldBinding.inputPath,
              _consumerPropertyKey = _oldBinding$inputPath[0],
              _oldBinding$inputPath2 = _oldBinding$inputPath[1],
              _consumerElementIndex = _oldBinding$inputPath2 === void 0 ? -1 : _oldBinding$inputPath2;
            this.addBinding([_consumerPropertyKey, _consumerElementIndex + (forward ? -1 : 1)], oldBinding.producer, oldBinding.outputIndex);
          }
        };
        _proto.deleteBindingTo = function deleteBindingTo(producer) {
          var bindings = this._bindings;
          for (var iBinding = 0; iBinding < bindings.length; ++iBinding) {
            var binding = bindings[iBinding];
            if (binding.producer === producer) {
              bindings.splice(iBinding, 1);
            }
          }
        };
        _proto.findBinding = function findBinding(inputPath) {
          var bindingIndex = this._findBindingIndex(inputPath);
          return bindingIndex >= 0 ? this._bindings[bindingIndex] : undefined;
        };
        _proto._findBindingIndex = function _findBindingIndex(inputPath) {
          return this._bindings.findIndex(function (searchElement) {
            return isEqualNodeInputPath(searchElement.inputPath, inputPath);
          });
        };
        _proto._emplaceBinding = function _emplaceBinding(binding) {
          var index = this._bindings.findIndex(function (searchElement) {
            return isEqualNodeInputPath(searchElement.inputPath, binding.inputPath);
          });
          if (index >= 0) {
            this._bindings[index] = binding;
          } else {
            this._bindings.push(binding);
          }
        };
        return PoseGraphNodeShell;
      }(EditorExtendable), (_initializer$1a = applyDecoratedInitializer(_class2$1j.prototype, "_bindings", [serializable$j], function () {
        return [];
      })), _class2$1j)) || _class$1r);
      function isEqualNodeInputPath(lhs, rhs) {
        var lhsPropertyKey = lhs[0],
          lhsElementIndex = lhs[1];
        var rhsPropertyKey = rhs[0],
          rhsElementIndex = rhs[1];
        return lhsPropertyKey === rhsPropertyKey && lhsElementIndex === rhsElementIndex;
      }
      var PoseGraphNodeInputBinding = (_dec2$1f = ccclass$n(CLASS_NAME_PREFIX_ANIM + "PoseGraphNodeInputBinding"), _dec2$1f(_class4$h = (_class5$j = function () {
        function PoseGraphNodeInputBinding(inputPath, producer, outputIndex) {
          this._inputPath = _initializer2$_ && _initializer2$_();
          this._producer = _initializer3$F && _initializer3$F();
          this._outputIndex = _initializer4$u && _initializer4$u();
          this._inputPath = inputPath;
          this._producer = producer;
          if (typeof outputIndex !== 'undefined') {
            this._outputIndex = outputIndex;
          }
        }
        _createClass(PoseGraphNodeInputBinding, [{
          key: "inputPath",
          get: function get() {
            return this._inputPath;
          }
        }, {
          key: "producer",
          get: function get() {
            return this._producer;
          }
        }, {
          key: "outputIndex",
          get: function get() {
            return this._outputIndex;
          }
        }]);
        return PoseGraphNodeInputBinding;
      }(), (_initializer2$_ = applyDecoratedInitializer(_class5$j.prototype, "_inputPath", [serializable$j], null), _initializer3$F = applyDecoratedInitializer(_class5$j.prototype, "_producer", [serializable$j], null), _initializer4$u = applyDecoratedInitializer(_class5$j.prototype, "_outputIndex", [serializable$j], function () {
        return 0;
      })), _class5$j)) || _class4$h);

      var AddNonFreestandingNodeError = function (_Error) {
        _inheritsLoose(AddNonFreestandingNodeError, _Error);
        function AddNonFreestandingNodeError(node) {
          return _Error.call(this, "Can not add the specified " + node.toString() + " since it has already been added into another graph.") || this;
        }
        return AddNonFreestandingNodeError;
      }(_wrapNativeSuper(Error));
      var OperationOnFreestandingNodeError = function (_Error2) {
        _inheritsLoose(OperationOnFreestandingNodeError, _Error2);
        function OperationOnFreestandingNodeError(node) {
          return _Error2.call(this, "Can not perform specified operation on " + node.toString() + " since it has not been added in to graph.") || this;
        }
        return OperationOnFreestandingNodeError;
      }(_wrapNativeSuper(Error));

      var PoseGraphType;
      (function (PoseGraphType) {
        PoseGraphType[PoseGraphType["FLOAT"] = 0] = "FLOAT";
        PoseGraphType[PoseGraphType["INTEGER"] = 1] = "INTEGER";
        PoseGraphType[PoseGraphType["BOOLEAN"] = 2] = "BOOLEAN";
        PoseGraphType[PoseGraphType["VEC3"] = 3] = "VEC3";
        PoseGraphType[PoseGraphType["QUAT"] = 4] = "QUAT";
        PoseGraphType[PoseGraphType["POSE"] = 5] = "POSE";
      })(PoseGraphType || (PoseGraphType = {}));

      var PoseGraphNode = function (_EditorExtendable) {
        _inheritsLoose(PoseGraphNode, _EditorExtendable);
        function PoseGraphNode() {
          return _EditorExtendable.apply(this, arguments) || this;
        }
        return PoseGraphNode;
      }(EditorExtendable);

      var nodeEditorMetadataMap = new WeakMap();
      function getOrCreateNodeEditorMetadata(constructor) {
        var existing = nodeEditorMetadataMap.get(constructor);
        if (existing) {
          return existing;
        } else {
          var metadata = {};
          nodeEditorMetadataMap.set(constructor, metadata);
          return metadata;
        }
      }

      function makeNodeEditorMetadataModifier(edit) {
        return function (target) {
          if (!checkDecoratingClass(target)) {
            return;
          }
          var metadata = getOrCreateNodeEditorMetadata(target);
          edit(metadata);
        };
      }
      var poseGraphNodeCategory = function poseGraphNodeCategory(category) {
        return makeNodeEditorMetadataModifier(function (metadata) {
          metadata.category = category;
        });
      };
      var poseGraphCreateNodeFactory = function poseGraphCreateNodeFactory(factory) {
        return makeNodeEditorMetadataModifier(function (metadata) {
          metadata.factory = factory;
        });
      };
      var poseGraphNodeHide = function poseGraphNodeHide(hide) {
        if (hide === void 0) {
          hide = true;
        }
        return makeNodeEditorMetadataModifier(function (metadata) {
          metadata.hide = hide;
        });
      };
      var poseGraphNodeAppearance = function poseGraphNodeAppearance(appearance) {
        return makeNodeEditorMetadataModifier(function (metadata) {
          var _metadata$appearance;
          Object.assign((_metadata$appearance = metadata.appearance) !== null && _metadata$appearance !== void 0 ? _metadata$appearance : metadata.appearance = {}, appearance);
        });
      };
      function checkDecoratingClass(fn) {
        if (!isChildClassOf(fn, PoseGraphNode)) {
          error("This kind of decorator should only be applied to pose graph node classes.");
          return false;
        }
        return true;
      }

      var _excluded = ["arraySyncGroup"];
      var PoseGraphNodeInputManager = function () {
        function PoseGraphNodeInputManager() {
          this._classInputMap = new WeakMap();
        }
        var _proto = PoseGraphNodeInputManager.prototype;
        _proto.setPropertyNodeInputRecord = function setPropertyNodeInputRecord(constructor, propertyKey, options) {
          var classInputRecord = this._classInputMap.get(constructor);
          if (!classInputRecord) {
            classInputRecord = {
              properties: {}
            };
            this._classInputMap.set(constructor, classInputRecord);
          }
          options.arraySyncGroup;
            var unchanged = _objectWithoutPropertiesLoose(options, _excluded);
          var record = unchanged;
          var arraySyncGroupName = options.arraySyncGroup;
          if (arraySyncGroupName) {
            var _classInputRecord$arr, _classInputRecord$arr2;
            if (!classInputRecord.arraySyncGroups) {
              classInputRecord.arraySyncGroups = {};
            }
            var group = (_classInputRecord$arr2 = (_classInputRecord$arr = classInputRecord.arraySyncGroups)[arraySyncGroupName]) !== null && _classInputRecord$arr2 !== void 0 ? _classInputRecord$arr2 : _classInputRecord$arr[arraySyncGroupName] = {
              members: []
            };
            if (!group.members.includes(propertyKey)) {
              group.members.push(propertyKey);
            }
            record.arraySyncGroup = group;
          }
          classInputRecord.properties[propertyKey] = Object.freeze(record);
        };
        _proto.getInputKeys = function getInputKeys(object) {
          var _this = this;
          var result = [];
          var getInputKeysRecurse = function getInputKeysRecurse(constructor) {
            if (!constructor) {
              return;
            }
            getInputKeysRecurse(getSuper(constructor));
            var record = _this._classInputMap.get(constructor);
            if (!record) {
              return;
            }
            var _loop = function _loop() {
              var _Object$entries$_i = _Object$entries[_i],
                propertyKey = _Object$entries$_i[0];
              if (result.findIndex(function (_ref) {
                var subClassPropertyKey = _ref[0];
                return propertyKey === subClassPropertyKey;
              }) >= 0) {
                return 1;
              }
              var field = object[propertyKey];
              if (Array.isArray(field)) {
                for (var iElement = 0; iElement < field.length; ++iElement) {
                  result.push([propertyKey, iElement]);
                }
              } else {
                result.push([propertyKey]);
              }
            };
            for (var _i = 0, _Object$entries = Object.entries(record.properties); _i < _Object$entries.length; _i++) {
              if (_loop()) continue;
            }
          };
          getInputKeysRecurse(object.constructor);
          return result;
        };
        _proto.isPoseInput = function isPoseInput(object, key) {
          var propertyKey = key[0];
          var propertyInputRecord = this._getPropertyNodeInputRecord(object.constructor, propertyKey);
          if (!propertyInputRecord) {
            return false;
          }
          return propertyInputRecord.type === PoseGraphType.POSE;
        };
        _proto.getInputMetadata = function getInputMetadata(object, key) {
          var propertyKey = key[0],
            _key$ = key[1],
            elementIndex = _key$ === void 0 ? -1 : _key$;
          var propertyInputRecord = this._getPropertyNodeInputRecord(object.constructor, propertyKey);
          if (!propertyInputRecord) {
            return undefined;
          }
          var field = object[propertyKey];
          if (Array.isArray(field)) {
            if (elementIndex < 0 || elementIndex >= field.length) {
              return undefined;
            } else {
              var _propertyInputRecord$, _propertyInputRecord$2;
              var displayName = (_propertyInputRecord$ = (_propertyInputRecord$2 = propertyInputRecord.getArrayElementDisplayName) === null || _propertyInputRecord$2 === void 0 ? void 0 : _propertyInputRecord$2.call(object, elementIndex)) !== null && _propertyInputRecord$ !== void 0 ? _propertyInputRecord$ : propertyInputRecord.displayName;
              return {
                type: propertyInputRecord.type,
                displayName: displayName,
                deletable: !(propertyInputRecord.arraySyncGroup && propertyInputRecord.arraySyncGroupFollower),
                insertPoint: true
              };
            }
          }
          return {
            type: propertyInputRecord.type,
            displayName: propertyInputRecord.displayName
          };
        };
        _proto.hasInput = function hasInput(object, key) {
          var propertyKey = key[0],
            _key$2 = key[1],
            elementIndex = _key$2 === void 0 ? -1 : _key$2;
          var record = this._getPropertyNodeInputRecord(object.constructor, propertyKey);
          if (!record) {
            return false;
          }
          var field = object[propertyKey];
          if (Array.isArray(field)) {
            if (elementIndex < 0 || elementIndex >= field.length) {
              return false;
            }
          }
          return true;
        };
        _proto.getInputInsertInfos = function getInputInsertInfos(object) {
          var result = {};
          for (var _constructor = object.constructor; _constructor; _constructor = getSuper(_constructor)) {
            var classInputRecord = this._classInputMap.get(_constructor);
            if (!classInputRecord) {
              continue;
            }
            for (var propertyKey in classInputRecord.properties) {
              var propertyInputRecord = classInputRecord.properties[propertyKey];
              var property = object[propertyKey];
              if (Array.isArray(property)) {
                if (propertyInputRecord.arraySyncGroup && propertyInputRecord.arraySyncGroupFollower) {
                  continue;
                }
                result[propertyKey] = {
                  displayName: propertyKey
                };
              }
            }
          }
          return result;
        };
        _proto.deleteInput = function deleteInput(graph, node, key) {
          var propertyKey = key[0],
            _key$3 = key[1],
            elementIndex = _key$3 === void 0 ? -1 : _key$3;
          var propertyInputRecord = this._getPropertyNodeInputRecord(node.constructor, propertyKey);
          if (!propertyInputRecord) {
            return;
          }
          var property = node[propertyKey];
          if (!Array.isArray(property)) {
            return;
          }
          if (elementIndex < 0 || elementIndex >= property.length) {
            return;
          }
          {
            var arraySyncGroup = propertyInputRecord.arraySyncGroup;
            if (arraySyncGroup) {
              this._deleteInputInArraySyncGroup(graph, node, arraySyncGroup, property.length, elementIndex);
              return;
            }
          }
          deletePoseGraphNodeArrayElement(graph, node, key);
        };
        _proto.insertInput = function insertInput(graph, node, insertId) {
          var propertyKey = insertId;
          var propertyInputRecord = this._getPropertyNodeInputRecord(node.constructor, propertyKey);
          if (!propertyInputRecord) {
            return;
          }
          var property = node[propertyKey];
          if (!Array.isArray(property)) {
            return;
          }
          var hint = property.length;
          {
            var arraySyncGroup = propertyInputRecord.arraySyncGroup;
            if (arraySyncGroup) {
              this._insertInputInArraySyncGroup(graph, node, arraySyncGroup, property.length, hint);
              return;
            }
          }
          insertPoseGraphNodeArrayElement(graph, node, [propertyKey, hint], createDefaultInputValueByType(propertyInputRecord.type));
        };
        _proto._getPropertyNodeInputRecord = function _getPropertyNodeInputRecord(constructor, propertyKey) {
          if (!constructor) {
            return undefined;
          }
          var classInputRecord = this._classInputMap.get(constructor);
          if (classInputRecord) {
            var record = classInputRecord.properties[propertyKey];
            if (record) {
              return record;
            }
          }
          return this._getPropertyNodeInputRecord(getSuper(constructor), propertyKey);
        };
        _proto._insertInputInArraySyncGroup = function _insertInputInArraySyncGroup(graph, node, syncGroup, expectedOriginalSyncLength, insertHint) {
          for (var iGroupMember = 0; iGroupMember < syncGroup.members.length; ++iGroupMember) {
            var syncedPropertyKey = syncGroup.members[iGroupMember];
            var syncedPropertyInputRecord = this._getPropertyNodeInputRecord(node.constructor, syncedPropertyKey);
            assertIsTrue(syncedPropertyInputRecord);
            var syncedProperty = node[syncedPropertyKey];
            if (!Array.isArray(syncedProperty) || syncedProperty.length !== expectedOriginalSyncLength) {
              continue;
            }
            insertPoseGraphNodeArrayElement(graph, node, [syncedPropertyKey, insertHint], createDefaultInputValueByType(syncedPropertyInputRecord.type));
          }
        };
        _proto._deleteInputInArraySyncGroup = function _deleteInputInArraySyncGroup(graph, node, syncGroup, expectedOriginalSyncLength, index) {
          for (var iGroupMember = 0; iGroupMember < syncGroup.members.length; ++iGroupMember) {
            var syncedPropertyKey = syncGroup.members[iGroupMember];
            var syncedPropertyInputRecord = this._getPropertyNodeInputRecord(node.constructor, syncedPropertyKey);
            assertIsTrue(syncedPropertyInputRecord);
            var syncedProperty = node[syncedPropertyKey];
            if (!Array.isArray(syncedProperty) || syncedProperty.length !== expectedOriginalSyncLength) {
              continue;
            }
            deletePoseGraphNodeArrayElement(graph, node, [syncedPropertyKey, index]);
          }
        };
        return PoseGraphNodeInputManager;
      }();
      function insertPoseGraphNodeArrayElement(graph, node, inputKey, value) {
        var shell = graph.getShell(node);
        if (!shell) {
          throw new OperationOnFreestandingNodeError(node);
        }
        var propertyKey = inputKey[0],
          _inputKey$ = inputKey[1],
          elementIndex = _inputKey$ === void 0 ? -1 : _inputKey$;
        var property = node[propertyKey];
        if (!Array.isArray(property)) {
          return;
        }
        property.splice(elementIndex, 0, value);
        shell.moveArrayElementBindingForward(propertyKey, elementIndex + 1, false);
      }
      function deletePoseGraphNodeArrayElement(graph, node, inputKey) {
        var shell = graph.getShell(node);
        if (!shell) {
          throw new OperationOnFreestandingNodeError(node);
        }
        var propertyKey = inputKey[0],
          _inputKey$2 = inputKey[1],
          elementIndex = _inputKey$2 === void 0 ? -1 : _inputKey$2;
        var property = node[propertyKey];
        if (!Array.isArray(property)) {
          return;
        }
        if (elementIndex < 0 || elementIndex >= property.length) {
          return;
        }
        shell.deleteBinding(inputKey);
        property.splice(elementIndex, 1);
        shell.moveArrayElementBindingForward(propertyKey, elementIndex + 1, true);
      }
      function createDefaultInputValueByType(type) {
        switch (type) {
          default:
            assertIsTrue(false);
          case PoseGraphType.FLOAT:
          case PoseGraphType.INTEGER:
            return 0;
          case PoseGraphType.BOOLEAN:
            return false;
          case PoseGraphType.POSE:
            return null;
          case PoseGraphType.VEC3:
            return new Vec3();
          case PoseGraphType.QUAT:
            return new Quat();
        }
      }
      var globalPoseGraphNodeInputManager = new PoseGraphNodeInputManager();

      var _class$1q;
      var CACHE_VECTOR_A = new Vec3();
      var CACHE_VECTOR_B = new Vec3();
      var CACHE_QUAT_A = new Quat();
      new Quat();
      var Transform = function () {
        function Transform() {
          this._position = new Vec3();
          this._rotation = new Quat();
          this._scale = Vec3.clone(Vec3.ONE);
        }
        Transform.clone = function clone(src) {
          var transform = new Transform();
          Transform.copy(transform, src);
          return transform;
        };
        Transform.setIdentity = function setIdentity(out) {
          Vec3.copy(out._position, Vec3.ZERO);
          Quat.copy(out._rotation, Quat.IDENTITY);
          Vec3.copy(out._scale, Vec3.ONE);
          return out;
        };
        Transform.copy = function copy(out, src) {
          Vec3.copy(out._position, src._position);
          Quat.copy(out._rotation, src._rotation);
          Vec3.copy(out._scale, src._scale);
          return out;
        };
        Transform.equals = function equals(a, b, epsilon) {
          return Vec3.equals(a._position, b._position, epsilon) && Quat.equals(a._rotation, b._rotation, epsilon) && Vec3.equals(a._scale, b._scale, epsilon);
        };
        Transform.strictEquals = function strictEquals(a, b) {
          return Vec3.strictEquals(a._position, b._position) && Quat.strictEquals(a._rotation, b._rotation) && Vec3.strictEquals(a._scale, b._scale);
        };
        Transform.lerp = function lerp(out, from, to, t) {
          if (t === 0.0) {
            return Transform.copy(out, from);
          }
          if (t === 1.0) {
            return Transform.copy(out, to);
          }
          Vec3.lerp(out._position, from._position, to._position, t);
          Quat.slerp(out._rotation, from._rotation, to._rotation, t);
          Vec3.lerp(out._scale, from._scale, to._scale, t);
          return out;
        };
        Transform.multiply = function multiply(out, second, first) {
          var cacheRotation = Quat.multiply(CACHE_QUAT_A, second._rotation, first._rotation);
          var cacheScale = Vec3.multiply(CACHE_VECTOR_A, first._scale, second._scale);
          var cachePosition = Vec3.multiply(CACHE_VECTOR_B, first._position, second._scale);
          Vec3.transformQuat(cachePosition, cachePosition, second._rotation);
          Vec3.add(cachePosition, cachePosition, second._position);
          Vec3.copy(out._position, cachePosition);
          Quat.copy(out._rotation, cacheRotation);
          Vec3.copy(out._scale, cacheScale);
          return out;
        };
        Transform.invert = function invert(out, transform) {
          var invRotation = out._rotation,
            invScale = out._scale,
            invPosition = out._position;
          Quat.invert(invRotation, transform._rotation);
          invScaleOrZero(invScale, transform._scale, EPSILON$3);
          Vec3.negate(invPosition, transform._position);
          Vec3.multiply(invPosition, invPosition, invScale);
          Vec3.transformQuat(invPosition, invPosition, invRotation);
          return out;
        };
        Transform.fromMatrix = function fromMatrix(out, matrix) {
          Mat4.toSRT(matrix, out._rotation, out._position, out._scale);
          return out;
        };
        Transform.toMatrix = function toMatrix(out, transform) {
          return Mat4.fromSRT(out, transform._rotation, transform._position, transform._scale);
        };
        _createClass(Transform, [{
          key: "position",
          get: function get() {
            return this._position;
          },
          set: function set(value) {
            Vec3.copy(this._position, value);
          }
        }, {
          key: "rotation",
          get: function get() {
            return this._rotation;
          },
          set: function set(value) {
            Quat.copy(this._rotation, value);
          }
        }, {
          key: "scale",
          get: function get() {
            return this._scale;
          },
          set: function set(value) {
            Vec3.copy(this._scale, value);
          }
        }]);
        return Transform;
      }();
      _class$1q = Transform;
      Transform.IDENTITY = Object.freeze(new _class$1q());
      Transform.ZERO = Object.freeze(function () {
        var transform = new _class$1q();
        Vec3.copy(transform._position, Vec3.ZERO);
        Quat.set(transform._rotation, 0.0, 0.0, 0.0, 0.0);
        Vec3.copy(transform._scale, Vec3.ZERO);
        return transform;
      }());
      Transform.calculateRelative = function () {
        var cacheInvRotation = new Quat();
        var cacheInvScale = new Vec3();
        return function (out, first, second) {
          var invSecondRotation = Quat.invert(cacheInvRotation, second._rotation);
          var invScale = invScaleOrZero(cacheInvScale, second._scale, EPSILON$3);
          var cachePosition = Vec3.subtract(CACHE_VECTOR_B, first._position, second._position);
          Vec3.transformQuat(cachePosition, cachePosition, invSecondRotation);
          Vec3.multiply(cachePosition, cachePosition, invScale);
          Vec3.copy(out._position, cachePosition);
          Quat.multiply(out._rotation, invSecondRotation, first._rotation);
          Vec3.multiply(out._scale, first._scale, invScale);
          return out;
        };
      }();
      function invScaleOrZero(out, scale, epsilon) {
        var x = scale.x,
          y = scale.y,
          z = scale.z;
        return Vec3.set(out, Math.abs(x) <= epsilon ? 0.0 : 1.0 / x, Math.abs(y) <= epsilon ? 0.0 : 1.0 / y, Math.abs(z) <= epsilon ? 0.0 : 1.0 / z);
      }
      function __calculateDeltaTransform(out, target, base) {
        Vec3.subtract(out.position, target.position, base.position);
        deltaQuat(out.rotation, base.rotation, target.rotation);
        Vec3.subtract(out.scale, target.scale, base.scale);
        return out;
      }
      var __applyDeltaTransform = function () {
        var cacheQuat = new Quat();
        return function (out, base, delta, alpha) {
          Vec3.scaleAndAdd(out.position, base.position, delta.position, alpha);
          var weightedDeltaRotation = Quat.slerp(cacheQuat, Quat.IDENTITY, delta.rotation, alpha);
          Quat.multiply(out.rotation, weightedDeltaRotation, base.rotation);
          Vec3.scaleAndAdd(out.scale, base.scale, delta.scale, alpha);
          return out;
        };
      }();
      var deltaQuat = function () {
        var quatMultiInvInverseCache = new Quat();
        return function (out, from, to) {
          var fromInv = Quat.invert(quatMultiInvInverseCache, from);
          return Quat.multiply(out, to, fromInv);
        };
      }();
      var ZERO_DELTA_TRANSFORM = Object.freeze(function () {
        var transform = new Transform();
        transform.position = Vec3.ZERO;
        transform.rotation = Quat.IDENTITY;
        transform.scale = Vec3.ZERO;
        return transform;
      }());

      var Pose = function () {
        function Pose(transforms, auxiliaryCurves) {
          this.transforms = void 0;
          this.auxiliaryCurves = void 0;
          this._poseTransformSpace = PoseTransformSpace.LOCAL;
          this.transforms = transforms;
          this.auxiliaryCurves = auxiliaryCurves;
        }
        Pose._create = function _create(transforms, auxiliaryCurves) {
          return new Pose(transforms, auxiliaryCurves);
        };
        return Pose;
      }();
      var PoseTransformSpace;
      (function (PoseTransformSpace) {
        PoseTransformSpace[PoseTransformSpace["LOCAL"] = 0] = "LOCAL";
        PoseTransformSpace[PoseTransformSpace["COMPONENT"] = 1] = "COMPONENT";
      })(PoseTransformSpace || (PoseTransformSpace = {}));
      var TransformFilter = function () {
        function TransformFilter(involvedTransforms) {
          {
            assertIsTrue(involvedTransforms.every(function (transformIndex) {
              return transformIndex < Math.pow(2, 16);
            }), 'The number of transforms exceeds the max allowed(2 ** 16)');
          }
          this._involvedTransforms = new Uint16Array(involvedTransforms);
        }
        _createClass(TransformFilter, [{
          key: "involvedTransforms",
          get: function get() {
            return this._involvedTransforms;
          }
        }]);
        return TransformFilter;
      }();
      function blendPoseInto(target, source, alpha, transformFilter) {
        if (transformFilter === void 0) {
          transformFilter = undefined;
        }
        blendTransformsInto(target.transforms, source.transforms, alpha, transformFilter);
        blendAuxiliaryCurvesInto(target.auxiliaryCurves, source.auxiliaryCurves, alpha);
      }
      function blendTransformsInto(target, source, alpha, transformFilter) {
        if (transformFilter === void 0) {
          transformFilter = undefined;
        }
        var nTransforms = target.length;
        assertIsTrue(nTransforms === target.length);
        if (alpha === 0) {
          return;
        } else if (alpha === 1) {
          if (!transformFilter) {
            target.set(source);
          } else {
            copyTransformsWithFilter(target, source, transformFilter);
          }
          return;
        }
        if (!transformFilter) {
          for (var iTransform = 0; iTransform < nTransforms; ++iTransform) {
            blendIntoTransformArrayAt(target, source, alpha, iTransform);
          }
        } else {
          for (var index = 0; index < transformFilter.involvedTransforms.length; ++index) {
            var involvedTransformIndex = transformFilter.involvedTransforms[index];
            blendIntoTransformArrayAt(target, source, alpha, involvedTransformIndex);
          }
        }
      }
      function copyTransformsWithFilter(target, source, filter) {
        var nTransforms = target.length;
        assertIsTrue(nTransforms === target.length);
        for (var index = 0; index < filter.involvedTransforms.length; ++index) {
          var involvedTransformIndex = filter.involvedTransforms[index];
          target.copyRange(involvedTransformIndex, source, involvedTransformIndex, 1);
        }
      }
      var blendIntoTransformArrayAt = function () {
        var cacheTransformSource = new Transform();
        var cacheTransformTarget = new Transform();
        return function (target, source, alpha, transformIndex) {
          var transformTarget = target.getTransform(transformIndex, cacheTransformTarget);
          var transformSource = source.getTransform(transformIndex, cacheTransformSource);
          Transform.lerp(transformTarget, transformTarget, transformSource, alpha);
          target.setTransform(transformIndex, transformTarget);
        };
      }();
      function blendAuxiliaryCurvesInto(target, source, alpha) {
        var nValues = source.length;
        assertIsTrue(nValues === target.length);
        for (var iValue = 0; iValue < nValues; ++iValue) {
          target[iValue] = lerp(target[iValue], source[iValue], alpha);
        }
      }
      function calculateDeltaPose(target, base) {
        calculateDeltaTransforms(target.transforms, base.transforms);
        calculateDeltaAuxiliaryCurves(target.auxiliaryCurves, base.auxiliaryCurves);
      }
      var calculateDeltaTransformArrayAt = function () {
        var cacheTransformBase = new Transform();
        var cacheTransformTarget = new Transform();
        return function (target, base, transformIndex) {
          var baseTransform = base.getTransform(transformIndex, cacheTransformBase);
          var targetTransform = target.getTransform(transformIndex, cacheTransformTarget);
          __calculateDeltaTransform(targetTransform, targetTransform, baseTransform);
          target.setTransform(transformIndex, targetTransform);
        };
      }();
      function calculateDeltaTransforms(target, base) {
        var nTransforms = target.length;
        assertIsTrue(nTransforms === base.length);
        for (var iTransform = 0; iTransform < nTransforms; ++iTransform) {
          calculateDeltaTransformArrayAt(target, base, iTransform);
        }
      }
      function calculateDeltaAuxiliaryCurves(target, base) {
        var nAuxiliaryCurves = target.length;
        assertIsTrue(nAuxiliaryCurves === base.length);
        for (var i = 0; i < target.length; ++i) {
          target[i] -= base[i];
        }
      }
      function applyDeltaPose(target, base, alpha, transformFilter) {
        if (transformFilter === void 0) {
          transformFilter = undefined;
        }
        applyDeltaTransforms(target.transforms, base.transforms, alpha, transformFilter);
        applyDeltaAuxiliaryCurves(target.auxiliaryCurves, base.auxiliaryCurves, alpha);
      }
      var applyDeltaTransformArrayAt = function () {
        var cacheTransformDelta = new Transform();
        var cacheTransformTarget = new Transform();
        return function (target, delta, alpha, transformIndex) {
          var deltaTransform = delta.getTransform(transformIndex, cacheTransformDelta);
          var targetTransform = target.getTransform(transformIndex, cacheTransformTarget);
          __applyDeltaTransform(targetTransform, targetTransform, deltaTransform, alpha);
          target.setTransform(transformIndex, targetTransform);
        };
      }();
      function applyDeltaTransforms(target, delta, alpha, transformFilter) {
        if (transformFilter === void 0) {
          transformFilter = undefined;
        }
        var nTransforms = target.length;
        assertIsTrue(nTransforms === delta.length);
        if (!transformFilter) {
          for (var iTransform = 0; iTransform < nTransforms; ++iTransform) {
            applyDeltaTransformArrayAt(target, delta, alpha, iTransform);
          }
        } else {
          for (var index = 0; index < transformFilter.involvedTransforms.length; ++index) {
            var _transformIndex = transformFilter.involvedTransforms[index];
            applyDeltaTransformArrayAt(target, delta, alpha, _transformIndex);
          }
        }
      }
      function applyDeltaAuxiliaryCurves(target, delta, alpha) {
        var nAuxiliaryCurves = target.length;
        assertIsTrue(nAuxiliaryCurves === delta.length);
        for (var i = 0; i < target.length; ++i) {
          target[i] += delta[i] * alpha;
        }
      }

      var _dec$1r, _class$1p;
      var PoseTransformSpaceRequirement;
      (function (PoseTransformSpaceRequirement) {
        PoseTransformSpaceRequirement[PoseTransformSpaceRequirement["NO"] = 0] = "NO";
        PoseTransformSpaceRequirement[PoseTransformSpaceRequirement["LOCAL"] = 1] = "LOCAL";
        PoseTransformSpaceRequirement[PoseTransformSpaceRequirement["COMPONENT"] = 2] = "COMPONENT";
      })(PoseTransformSpaceRequirement || (PoseTransformSpaceRequirement = {}));
      ccenum(PoseTransformSpaceRequirement);
      var PoseNode = (_dec$1r = ccclass$n(CLASS_NAME_PREFIX_ANIM + "PoseNode"), _dec$1r(_class$1p = function (_PoseGraphNode) {
        _inheritsLoose(PoseNode, _PoseGraphNode);
        function PoseNode() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _PoseGraphNode.call.apply(_PoseGraphNode, [this].concat(args)) || this;
          _this._dependencyEvaluation = undefined;
          return _this;
        }
        var _proto = PoseNode.prototype;
        _proto.update = function update(context) {
          var _this$_dependencyEval;
          (_this$_dependencyEval = this._dependencyEvaluation) === null || _this$_dependencyEval === void 0 ? void 0 : _this$_dependencyEval.evaluate();
          this.doUpdate(context);
        };
        _proto.evaluate = function evaluate(context, poseTransformSpaceRequirement) {
          var pose = this.doEvaluate(context);
          var currentSpace = pose._poseTransformSpace;
          switch (poseTransformSpaceRequirement) {
            default:
              assertIsTrue(false);
            case PoseTransformSpaceRequirement.NO:
              break;
            case PoseTransformSpaceRequirement.LOCAL:
              {
                if (currentSpace === PoseTransformSpace.COMPONENT) {
                  context._poseTransformsSpaceComponentToLocal(pose);
                }
                assertIsTrue(pose._poseTransformSpace === PoseTransformSpace.LOCAL);
                break;
              }
            case PoseTransformSpaceRequirement.COMPONENT:
              {
                if (currentSpace === PoseTransformSpace.LOCAL) {
                  context._poseTransformsSpaceLocalToComponent(pose);
                }
                assertIsTrue(pose._poseTransformSpace === PoseTransformSpace.COMPONENT);
                break;
              }
          }
          return pose;
        };
        PoseNode.evaluateDefaultPose = function evaluateDefaultPose(context, poseTransformSpaceRequirement) {
          switch (poseTransformSpaceRequirement) {
            default:
              assertIsTrue(false);
            case PoseTransformSpaceRequirement.NO:
            case PoseTransformSpaceRequirement.LOCAL:
              return context.pushDefaultedPose();
            case PoseTransformSpaceRequirement.COMPONENT:
              return context.pushDefaultedPoseInComponentSpace();
          }
        };
        _proto._setDependencyEvaluation = function _setDependencyEvaluation(dependency) {
          this._dependencyEvaluation = dependency;
        };
        _proto._forceEvaluateEvaluation = function _forceEvaluateEvaluation() {
          var _this$_dependencyEval2;
          (_this$_dependencyEval2 = this._dependencyEvaluation) === null || _this$_dependencyEval2 === void 0 ? void 0 : _this$_dependencyEval2.evaluate();
        };
        return PoseNode;
      }(PoseGraphNode)) || _class$1p);

      var PureValueNode = function (_PoseGraphNode) {
        _inheritsLoose(PureValueNode, _PoseGraphNode);
        function PureValueNode(outputTypes) {
          var _this;
          _this = _PoseGraphNode.call(this) || this;
          _this._outputTypes = [];
          _this._outputTypes = outputTypes;
          return _this;
        }
        var _proto = PureValueNode.prototype;
        _proto.getOutputType = function getOutputType(outputIndex) {
          return this._outputTypes[outputIndex];
        };
        _proto.link = function link(context) {};
        _createClass(PureValueNode, [{
          key: "outputCount",
          get: function get() {
            return this._outputTypes.length;
          }
        }]);
        return PureValueNode;
      }(PoseGraphNode);
      var SingleOutputPVNode = function (_PureValueNode) {
        _inheritsLoose(SingleOutputPVNode, _PureValueNode);
        function SingleOutputPVNode(outputType) {
          return _PureValueNode.call(this, [outputType]) || this;
        }
        var _proto2 = SingleOutputPVNode.prototype;
        _proto2.selfEvaluate = function selfEvaluate(outputs) {
          outputs[0] = this.selfEvaluateDefaultOutput();
        };
        return SingleOutputPVNode;
      }(PureValueNode);

      function input(options) {
        return function (target, propertyKey) {
          var targetConstructor = target.constructor;
          if (options.type === PoseGraphType.POSE) {
            if (!isChildClassOf(targetConstructor, PoseNode)) {
              error("@input specifying pose input can be only applied to fields of subclasses of PoseNode.");
              return;
            }
          }
          if (!isChildClassOf(targetConstructor, PoseNode) && !isChildClassOf(targetConstructor, PureValueNode)) {
            error("@input can be only applied to fields of subclasses of PoseNode or PureValueNode.");
            return;
          }
          inputUnchecked(options)(target, propertyKey);
        };
      }
      function inputUnchecked(options) {
        return function (target, propertyKey) {
          if (typeof propertyKey !== 'string') {
            error("@input can be only applied to string-named fields.");
            return;
          }
          var targetConstructor = target.constructor;
          globalPoseGraphNodeInputManager.setPropertyNodeInputRecord(targetConstructor, propertyKey, options);
          var propertyStash = getOrCreatePropertyStash(target, propertyKey);
          propertyStash.__internalFlags |= PropertyStashInternalFlag.STANDALONE | PropertyStashInternalFlag.IMPLICIT_VISIBLE;
        };
      }

      var _dec$1q, _dec2$1e, _dec3$T, _class$1o, _class2$1i, _descriptor$a;
      var PoseGraphOutputNode = (_dec$1q = ccclass$n(CLASS_NAME_PREFIX_ANIM + "PoseGraphOutputNode"), _dec2$1e = poseGraphNodeAppearance({
        themeColor: '#CD3A58',
        inline: true
      }), _dec3$T = inputUnchecked({
        type: PoseGraphType.POSE
      }), _dec$1q(_class$1o = _dec2$1e(_class$1o = (_class2$1i = function (_PoseGraphNode) {
        _inheritsLoose(PoseGraphOutputNode, _PoseGraphNode);
        function PoseGraphOutputNode() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _PoseGraphNode.call.apply(_PoseGraphNode, [this].concat(args)) || this;
          _initializerDefineProperty(_this, "pose", _descriptor$a, _assertThisInitialized(_this));
          return _this;
        }
        return PoseGraphOutputNode;
      }(PoseGraphNode), (_descriptor$a = _applyDecoratedDescriptor(_class2$1i.prototype, "pose", [serializable$j, _dec3$T], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return null;
        }
      })), _class2$1i)) || _class$1o) || _class$1o);

      var _dec$1p, _class$1n, _class2$1h, _initializer$19, _initializer2$Z, _initializer3$E, _initializer4$t;
      var PoseGraph = (_dec$1p = ccclass$n(CLASS_NAME_PREFIX_ANIM + "PoseGraph"), _dec$1p(_class$1n = (_class2$1h = function (_EditorExtendable) {
        _inheritsLoose(PoseGraph, _EditorExtendable);
        function PoseGraph() {
          var _this;
          _this = _EditorExtendable.call(this) || this;
          _this._outputNode = _initializer$19 && _initializer$19();
          _this._nodes = _initializer2$Z && _initializer2$Z();
          _this._shells = _initializer3$E && _initializer3$E();
          _this._shellMap = _initializer4$t && _initializer4$t();
          _this.addNode(_this._outputNode);
          return _this;
        }
        var _proto = PoseGraph.prototype;
        _proto.__callOnAfterDeserializeRecursive = function __callOnAfterDeserializeRecursive() {
          assertIsTrue(this._nodes.length === this._shells.length);
          for (var iNode = 0; iNode < this._nodes.length; ++iNode) {
            var _node$__callOnAfterDe;
            var node = this._nodes[iNode];
            var shell = this._shells[iNode];
            this._shellMap.set(node, shell);
            (_node$__callOnAfterDe = node.__callOnAfterDeserializeRecursive) === null || _node$__callOnAfterDe === void 0 ? void 0 : _node$__callOnAfterDe.call(node);
          }
        };
        _proto.nodes = function nodes() {
          return this._nodes.values();
        };
        _proto.addNode = function addNode(node) {
          if (this._shellMap.has(node)) {
            throw new AddNonFreestandingNodeError(node);
          }
          var shell = new PoseGraphNodeShell();
          this._shells.push(shell);
          this._nodes.push(node);
          this._shellMap.set(node, shell);
          return node;
        };
        _proto.removeNode = function removeNode(removal) {
          if (removal === this._outputNode) {
            error("Can not remove the output node.");
            return;
          }
          var nodeIndex = this._nodes.indexOf(removal);
          if (nodeIndex < 0) {
            return;
          }
          assertIsTrue(this._shellMap.has(removal));
          for (var _iterator = _createForOfIteratorHelperLoose(this._shells), _step; !(_step = _iterator()).done;) {
            var shell = _step.value;
            shell.deleteBindingTo(removal);
          }
          removeAt(this._shells, nodeIndex);
          removeAt(this._nodes, nodeIndex);
          this._shellMap["delete"](removal);
        };
        _proto.getShell = function getShell(node) {
          return this._shellMap.get(node);
        };
        _createClass(PoseGraph, [{
          key: "outputNode",
          get: function get() {
            return this._outputNode;
          }
        }]);
        return PoseGraph;
      }(EditorExtendable), (_initializer$19 = applyDecoratedInitializer(_class2$1h.prototype, "_outputNode", [serializable$j], function () {
        return new PoseGraphOutputNode();
      }), _initializer2$Z = applyDecoratedInitializer(_class2$1h.prototype, "_nodes", [serializable$j], function () {
        return [];
      }), _initializer3$E = applyDecoratedInitializer(_class2$1h.prototype, "_shells", [serializable$j], function () {
        return [];
      }), _initializer4$t = applyDecoratedInitializer(_class2$1h.prototype, "_shellMap", [serializable$j], function () {
        return new Map();
      })), _class2$1h)) || _class$1n);

      var _dec$1o, _class$1m, _class2$1g, _initializer$18, _initializer2$Y, _initializer3$D, _dec2$1d, _class4$g, _class5$i, _initializer4$s, _initializer5$k, _initializer6$e, _initializer7$d, _dec3$S, _class7$6, _class8$6, _initializer8$c, _initializer9$b, _initializer10$a, _initializer11$a, _dec4$F, _class10$2, _dec5$y, _class11$2, _class12$1, _initializer12$8, _dec6$j, _class14$1, _class15, _initializer13$7, _initializer14$5, _initializer15$3, _dec7$e, _class17, _class18, _initializer16$3, _dec8$9, _class20$1, _class21$1, _initializer17$2, _initializer18$2, _initializer19$1, _initializer20$1, _initializer21$1, _dec9$8, _class23, _class24, _initializer22$1, _dec10$5, _class26, _class27, _initializer23$1, _dec11$4, _class29, _class30, _initializer24$1, _initializer25$1, _initializer26$1, _initializer27$1, _initializer28$1, _initializer29$1, _dec12$4, _class32, _class33, _initializer30$1, _initializer31$1;
      var Transition$1 = (_dec$1o = ccclass$n(CLASS_NAME_PREFIX_ANIM + "Transition"), _dec$1o(_class$1m = (_class2$1g = function (_EditorExtendable) {
        _inheritsLoose(Transition, _EditorExtendable);
        function Transition(from, to, conditions) {
          var _this;
          _this = _EditorExtendable.call(this) || this;
          _this.from = _initializer$18 && _initializer$18();
          _this.to = _initializer2$Y && _initializer2$Y();
          _this.conditions = _initializer3$D && _initializer3$D();
          _this[ownerSymbol] = void 0;
          _this.from = from;
          _this.to = to;
          if (conditions) {
            _this.conditions = conditions;
          }
          return _this;
        }
        var _proto = Transition.prototype;
        _proto.copyTo = function copyTo(that) {
          that.conditions = this.conditions.map(function (condition) {
            return condition.clone();
          });
        };
        return Transition;
      }(EditorExtendable), (_initializer$18 = applyDecoratedInitializer(_class2$1g.prototype, "from", [serializable$j], null), _initializer2$Y = applyDecoratedInitializer(_class2$1g.prototype, "to", [serializable$j], null), _initializer3$D = applyDecoratedInitializer(_class2$1g.prototype, "conditions", [serializable$j], function () {
        return [];
      })), _class2$1g)) || _class$1m);
      var DurationalTransition = (_dec2$1d = ccclass$n(CLASS_NAME_PREFIX_ANIM + "DurationalTransition"), _dec2$1d(_class4$g = (_class5$i = function (_Transition) {
        _inheritsLoose(DurationalTransition, _Transition);
        function DurationalTransition() {
          var _this2;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this2 = _Transition.call.apply(_Transition, [this].concat(args)) || this;
          _this2.destinationStart = _initializer4$s && _initializer4$s();
          _this2.relativeDestinationStart = _initializer5$k && _initializer5$k();
          _this2.startEventBinding = _initializer6$e && _initializer6$e();
          _this2.endEventBinding = _initializer7$d && _initializer7$d();
          _this2[ownerSymbol] = void 0;
          return _this2;
        }
        var _proto2 = DurationalTransition.prototype;
        _proto2.copyTo = function copyTo(that) {
          _Transition.prototype.copyTo.call(this, that);
          that.destinationStart = this.destinationStart;
          that.relativeDestinationStart = this.relativeDestinationStart;
          this.startEventBinding.copyTo(that.startEventBinding);
          this.endEventBinding.copyTo(that.endEventBinding);
        };
        return DurationalTransition;
      }(Transition$1), (_initializer4$s = applyDecoratedInitializer(_class5$i.prototype, "destinationStart", [serializable$j], function () {
        return 0.0;
      }), _initializer5$k = applyDecoratedInitializer(_class5$i.prototype, "relativeDestinationStart", [serializable$j], function () {
        return false;
      }), _initializer6$e = applyDecoratedInitializer(_class5$i.prototype, "startEventBinding", [serializable$j], function () {
        return new AnimationGraphEventBinding();
      }), _initializer7$d = applyDecoratedInitializer(_class5$i.prototype, "endEventBinding", [serializable$j], function () {
        return new AnimationGraphEventBinding();
      })), _class5$i)) || _class4$g);
      var AnimationTransition = (_dec3$S = ccclass$n(CLASS_NAME_PREFIX_ANIM + "AnimationTransition"), _dec3$S(_class7$6 = (_class8$6 = function (_DurationalTransition) {
        _inheritsLoose(AnimationTransition, _DurationalTransition);
        function AnimationTransition() {
          var _this3;
          for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
            args[_key2] = arguments[_key2];
          }
          _this3 = _DurationalTransition.call.apply(_DurationalTransition, [this].concat(args)) || this;
          _this3.duration = _initializer8$c && _initializer8$c();
          _this3.relativeDuration = _initializer9$b && _initializer9$b();
          _this3.exitConditionEnabled = _initializer10$a && _initializer10$a();
          _this3._exitCondition = _initializer11$a && _initializer11$a();
          return _this3;
        }
        var _proto3 = AnimationTransition.prototype;
        _proto3.copyTo = function copyTo(that) {
          _DurationalTransition.prototype.copyTo.call(this, that);
          that.duration = this.duration;
          that.relativeDuration = this.relativeDuration;
          that.exitConditionEnabled = this.exitConditionEnabled;
          that.exitCondition = this.exitCondition;
        };
        _createClass(AnimationTransition, [{
          key: "exitCondition",
          get: function get() {
            return this._exitCondition;
          },
          set: function set(value) {
            assertIsTrue(value >= 0.0);
            this._exitCondition = value;
          }
        }]);
        return AnimationTransition;
      }(DurationalTransition), (_initializer8$c = applyDecoratedInitializer(_class8$6.prototype, "duration", [serializable$j], function () {
        return 0.3;
      }), _initializer9$b = applyDecoratedInitializer(_class8$6.prototype, "relativeDuration", [serializable$j], function () {
        return false;
      }), _initializer10$a = applyDecoratedInitializer(_class8$6.prototype, "exitConditionEnabled", [serializable$j], function () {
        return true;
      }), _initializer11$a = applyDecoratedInitializer(_class8$6.prototype, "_exitCondition", [serializable$j], function () {
        return 1.0;
      })), _class8$6)) || _class7$6);
      function isAnimationTransition(transition) {
        return transition instanceof AnimationTransition;
      }
      var EmptyState = (_dec4$F = ccclass$n(CLASS_NAME_PREFIX_ANIM + "EmptyState"), _dec4$F(_class10$2 = function (_State) {
        _inheritsLoose(EmptyState, _State);
        function EmptyState() {
          return _State.apply(this, arguments) || this;
        }
        return EmptyState;
      }(State$1)) || _class10$2);
      var EmptyStateTransition = (_dec5$y = ccclass$n(CLASS_NAME_PREFIX_ANIM + "EmptyStateTransition"), _dec5$y(_class11$2 = (_class12$1 = function (_DurationalTransition2) {
        _inheritsLoose(EmptyStateTransition, _DurationalTransition2);
        function EmptyStateTransition() {
          var _this4;
          for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
            args[_key3] = arguments[_key3];
          }
          _this4 = _DurationalTransition2.call.apply(_DurationalTransition2, [this].concat(args)) || this;
          _this4.duration = _initializer12$8 && _initializer12$8();
          return _this4;
        }
        var _proto4 = EmptyStateTransition.prototype;
        _proto4.copyTo = function copyTo(that) {
          _DurationalTransition2.prototype.copyTo.call(this, that);
          that.duration = this.duration;
        };
        return EmptyStateTransition;
      }(DurationalTransition), (_initializer12$8 = applyDecoratedInitializer(_class12$1.prototype, "duration", [serializable$j], function () {
        return 0.3;
      })), _class12$1)) || _class11$2);
      var ProceduralPoseState = (_dec6$j = ccclass$n(CLASS_NAME_PREFIX_ANIM + "ProceduralPoseState"), _dec6$j(_class14$1 = (_class15 = function (_State2) {
        _inheritsLoose(ProceduralPoseState, _State2);
        function ProceduralPoseState() {
          var _this5;
          for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
            args[_key4] = arguments[_key4];
          }
          _this5 = _State2.call.apply(_State2, [this].concat(args)) || this;
          _this5.graph = _initializer13$7 && _initializer13$7();
          _this5.transitionInEventBinding = _initializer14$5 && _initializer14$5();
          _this5.transitionOutEventBinding = _initializer15$3 && _initializer15$3();
          return _this5;
        }
        var _proto5 = ProceduralPoseState.prototype;
        _proto5.__callOnAfterDeserializeRecursive = function __callOnAfterDeserializeRecursive() {
          this.graph.__callOnAfterDeserializeRecursive();
        };
        _proto5.copyTo = function copyTo(that) {
          _State2.prototype.copyTo.call(this, that);
          this.transitionInEventBinding.copyTo(that.transitionInEventBinding);
          this.transitionOutEventBinding.copyTo(that.transitionOutEventBinding);
          return this;
        };
        return ProceduralPoseState;
      }(State$1), (_initializer13$7 = applyDecoratedInitializer(_class15.prototype, "graph", [serializable$j], function () {
        return new PoseGraph();
      }), _initializer14$5 = applyDecoratedInitializer(_class15.prototype, "transitionInEventBinding", [serializable$j], function () {
        return new AnimationGraphEventBinding();
      }), _initializer15$3 = applyDecoratedInitializer(_class15.prototype, "transitionOutEventBinding", [serializable$j], function () {
        return new AnimationGraphEventBinding();
      })), _class15)) || _class14$1);
      var ProceduralPoseState_ = createInstanceofProxy(ProceduralPoseState);
      var ProceduralPoseTransition = (_dec7$e = ccclass$n(CLASS_NAME_PREFIX_ANIM + "ProceduralPoseTransition"), _dec7$e(_class17 = (_class18 = function (_DurationalTransition3) {
        _inheritsLoose(ProceduralPoseTransition, _DurationalTransition3);
        function ProceduralPoseTransition() {
          var _this6;
          for (var _len5 = arguments.length, args = new Array(_len5), _key5 = 0; _key5 < _len5; _key5++) {
            args[_key5] = arguments[_key5];
          }
          _this6 = _DurationalTransition3.call.apply(_DurationalTransition3, [this].concat(args)) || this;
          _this6.duration = _initializer16$3 && _initializer16$3();
          return _this6;
        }
        var _proto6 = ProceduralPoseTransition.prototype;
        _proto6.copyTo = function copyTo(that) {
          _DurationalTransition3.prototype.copyTo.call(this, that);
          that.duration = this.duration;
        };
        return ProceduralPoseTransition;
      }(DurationalTransition), (_initializer16$3 = applyDecoratedInitializer(_class18.prototype, "duration", [serializable$j], function () {
        return 0.3;
      })), _class18)) || _class17);
      var ProceduralPoseTransition_ = createInstanceofProxy(ProceduralPoseTransition);
      var StateMachine = (_dec8$9 = ccclass$n('cc.animation.StateMachine'), _dec8$9(_class20$1 = (_class21$1 = function (_EditorExtendable2) {
        _inheritsLoose(StateMachine, _EditorExtendable2);
        var _proto7 = StateMachine.prototype;
        _proto7.__callOnAfterDeserializeRecursive = function __callOnAfterDeserializeRecursive() {
          this[onAfterDeserializedTag]();
          var nStates = this._states.length;
          for (var iState = 0; iState < nStates; ++iState) {
            var state = this._states[iState];
            if (state instanceof SubStateMachine) {
              state.stateMachine.__callOnAfterDeserializeRecursive();
            } else if (state instanceof ProceduralPoseState) {
              state.__callOnAfterDeserializeRecursive();
            } else if (state instanceof MotionState) {
              state.__callOnAfterDeserializeRecursive();
            }
          }
        };
        function StateMachine(allowEmptyStates) {
          var _this7;
          _this7 = _EditorExtendable2.call(this) || this;
          _this7._states = _initializer17$2 && _initializer17$2();
          _this7._transitions = _initializer18$2 && _initializer18$2();
          _this7._entryState = _initializer19$1 && _initializer19$1();
          _this7._exitState = _initializer20$1 && _initializer20$1();
          _this7._anyState = _initializer21$1 && _initializer21$1();
          _this7._allowEmptyStates = true;
          _this7._allowEmptyStates = allowEmptyStates !== null && allowEmptyStates !== void 0 ? allowEmptyStates : false;
          _this7._entryState = _this7._addState(new State$1());
          _this7._entryState.name = 'Entry';
          _this7._exitState = _this7._addState(new State$1());
          _this7._exitState.name = 'Exit';
          _this7._anyState = _this7._addState(new State$1());
          _this7._anyState.name = 'Any';
          return _this7;
        }
        _proto7[onAfterDeserializedTag] = function () {
          var _this8 = this;
          this._states.forEach(function (state) {
            return own(state, _this8);
          });
          this._transitions.forEach(function (transition) {
            transition.from[outgoingsSymbol].push(transition);
            transition.to[incomingsSymbol].push(transition);
          });
        };
        _proto7.states = function states() {
          return this._states;
        };
        _proto7.transitions = function transitions() {
          return this._transitions;
        };
        _proto7.getTransitionsBetween = function getTransitionsBetween(from, to) {
          assertsOwnedBy(from, this);
          assertsOwnedBy(to, this);
          return from[outgoingsSymbol].filter(function (transition) {
            return transition.to === to;
          });
        };
        _proto7.getOutgoings = function getOutgoings(from) {
          assertsOwnedBy(from, this);
          return from[outgoingsSymbol];
        };
        _proto7.getIncomings = function getIncomings(to) {
          assertsOwnedBy(to, this);
          return to[incomingsSymbol];
        };
        _proto7.addMotion = function addMotion() {
          return this._addState(new MotionState());
        };
        _proto7.addSubStateMachine = function addSubStateMachine() {
          return this._addState(new SubStateMachine(this._allowEmptyStates));
        };
        _proto7.addEmpty = function addEmpty() {
          if (!this._allowEmptyStates) {
            throw new Error("Empty states are now allowed in this state machine.");
          }
          return this._addState(new EmptyState());
        };
        _proto7.addProceduralPoseState = function addProceduralPoseState() {
          return this._addState(new ProceduralPoseState());
        };
        _proto7.remove = function remove$1(state) {
          assertsOwnedBy(state, this);
          if (state === this.entryState || state === this.exitState || state === this.anyState) {
            return;
          }
          this.eraseTransitionsIncludes(state);
          remove(this._states, state);
          markAsDangling(state);
        };
        _proto7.connect = function connect(from, to, conditions) {
          assertsOwnedBy(from, this);
          assertsOwnedBy(to, this);
          if (to === this.entryState) {
            throw new InvalidTransitionError('to-entry');
          }
          if (to === this.anyState) {
            throw new InvalidTransitionError('to-any');
          }
          if (from === this.exitState) {
            throw new InvalidTransitionError('from-exit');
          }
          var transition = from instanceof MotionState || from === this._anyState ? new AnimationTransition(from, to, conditions) : from instanceof EmptyState ? new EmptyStateTransition(from, to, conditions) : from instanceof ProceduralPoseState ? new ProceduralPoseTransition(from, to, conditions) : new Transition$1(from, to, conditions);
          own(transition, this);
          this._transitions.push(transition);
          from[outgoingsSymbol].push(transition);
          to[incomingsSymbol].push(transition);
          return transition;
        };
        _proto7.disconnect = function disconnect(from, to) {
          assertsOwnedBy(from, this);
          assertsOwnedBy(to, this);
          var oTransitions = from[outgoingsSymbol];
          var iTransitions = to[incomingsSymbol];
          var transitions = this._transitions;
          var oTransitionsToRemove = oTransitions.filter(function (oTransition) {
            return oTransition.to === to;
          });
          var nOTransitionToRemove = oTransitionsToRemove.length;
          var _loop = function _loop() {
            var oTransition = oTransitionsToRemove[iOTransitionToRemove];
            remove(oTransitions, oTransition);
            assertIsTrue(remove(transitions, oTransition));
            assertIsNonNullable(removeIf(iTransitions, function (transition) {
              return transition === oTransition;
            }));
            markAsDangling(oTransition);
          };
          for (var iOTransitionToRemove = 0; iOTransitionToRemove < nOTransitionToRemove; ++iOTransitionToRemove) {
            _loop();
          }
        };
        _proto7.removeTransition = function removeTransition(removal) {
          assertIsTrue(remove(this._transitions, removal));
          assertIsNonNullable(removeIf(removal.from[outgoingsSymbol], function (transition) {
            return transition === removal;
          }));
          assertIsNonNullable(removeIf(removal.to[incomingsSymbol], function (transition) {
            return transition === removal;
          }));
          markAsDangling(removal);
        };
        _proto7.eraseOutgoings = function eraseOutgoings(from) {
          var _this9 = this;
          assertsOwnedBy(from, this);
          var oTransitions = from[outgoingsSymbol];
          var _loop2 = function _loop2() {
            var oTransition = oTransitions[iOTransition];
            var to = oTransition.to;
            assertIsTrue(remove(_this9._transitions, oTransition));
            assertIsNonNullable(removeIf(to[incomingsSymbol], function (transition) {
              return transition === oTransition;
            }));
            markAsDangling(oTransition);
          };
          for (var iOTransition = 0; iOTransition < oTransitions.length; ++iOTransition) {
            _loop2();
          }
          oTransitions.length = 0;
        };
        _proto7.eraseIncomings = function eraseIncomings(to) {
          var _this10 = this;
          assertsOwnedBy(to, this);
          var iTransitions = to[incomingsSymbol];
          var _loop3 = function _loop3() {
            var iTransition = iTransitions[iITransition];
            var from = iTransition.from;
            assertIsTrue(remove(_this10._transitions, iTransition));
            assertIsNonNullable(removeIf(from[outgoingsSymbol], function (transition) {
              return transition === iTransition;
            }));
            markAsDangling(iTransition);
          };
          for (var iITransition = 0; iITransition < iTransitions.length; ++iITransition) {
            _loop3();
          }
          iTransitions.length = 0;
        };
        _proto7.eraseTransitionsIncludes = function eraseTransitionsIncludes(state) {
          this.eraseIncomings(state);
          this.eraseOutgoings(state);
        };
        _proto7.adjustTransitionPriority = function adjustTransitionPriority(adjusting, diff) {
          var from = adjusting.from;
          if (diff === 0) {
            return;
          }
          var outgoings = from[outgoingsSymbol];
          var iAdjusting = outgoings.indexOf(adjusting);
          assertIsTrue(iAdjusting >= 0);
          var iNew = clamp$1(iAdjusting + diff, 0, outgoings.length - 1);
          {
            var globalTransitions = this._transitions;
            var adjustingIndexInGlobal = globalTransitions.indexOf(adjusting);
            assertIsTrue(adjustingIndexInGlobal >= 0);
            var lastPlaceholder = adjustingIndexInGlobal;
            if (iNew > iAdjusting) {
              for (var iOutgoing = iAdjusting + 1; iOutgoing <= iNew; ++iOutgoing) {
                var outgoing = outgoings[iOutgoing];
                var indexInGlobal = globalTransitions.indexOf(outgoing);
                assertIsTrue(indexInGlobal >= 0);
                globalTransitions[lastPlaceholder] = outgoing;
                lastPlaceholder = indexInGlobal;
              }
            } else if (iAdjusting > iNew) {
              for (var _iOutgoing = iAdjusting - 1; _iOutgoing >= iNew; --_iOutgoing) {
                var _outgoing = outgoings[_iOutgoing];
                var _indexInGlobal = globalTransitions.indexOf(_outgoing);
                assertIsTrue(_indexInGlobal >= 0);
                globalTransitions[lastPlaceholder] = _outgoing;
                lastPlaceholder = _indexInGlobal;
              }
            }
            globalTransitions[lastPlaceholder] = adjusting;
          }
          {
            shift(outgoings, iAdjusting, iNew);
          }
        };
        _proto7.copyTo = function copyTo(that) {
          var thatStatesOld = that._states.filter(function (state) {
            switch (state) {
              case that._entryState:
              case that._exitState:
              case that._anyState:
                return true;
              default:
                return false;
            }
          });
          for (var _iterator = _createForOfIteratorHelperLoose(thatStatesOld), _step; !(_step = _iterator()).done;) {
            var thatStateOld = _step.value;
            that.remove(thatStateOld);
          }
          var stateMap = new Map();
          for (var _iterator2 = _createForOfIteratorHelperLoose(this._states), _step2; !(_step2 = _iterator2()).done;) {
            var state = _step2.value;
            switch (state) {
              case this._entryState:
                stateMap.set(state, that._entryState);
                break;
              case this._exitState:
                stateMap.set(state, that._exitState);
                break;
              case this._anyState:
                stateMap.set(state, that._anyState);
                break;
              default:
                if (state instanceof MotionState || state instanceof SubStateMachine || state instanceof EmptyState || state instanceof ProceduralPoseState) {
                  if (state instanceof EmptyState && !that._allowEmptyStates) {
                    continue;
                  }
                  var thatState = instantiate(state);
                  that._addState(thatState);
                  stateMap.set(state, thatState);
                } else {
                  assertIsTrue(false);
                }
                break;
            }
          }
          for (var _iterator3 = _createForOfIteratorHelperLoose(this._transitions), _step3; !(_step3 = _iterator3()).done;) {
            var transition = _step3.value;
            if (!that._allowEmptyStates) {
              if (transition.from instanceof EmptyState || transition.to instanceof EmptyState) {
                continue;
              }
            }
            var thatFrom = stateMap.get(transition.from);
            var thatTo = stateMap.get(transition.to);
            assertIsTrue(thatFrom && thatTo);
            var thatTransition = that.connect(thatFrom, thatTo);
            thatTransition.conditions = transition.conditions.map(function (condition) {
              return condition.clone();
            });
            if (thatTransition instanceof AnimationTransition) {
              assertIsTrue(transition instanceof AnimationTransition);
              transition.copyTo(thatTransition);
            } else if (thatTransition instanceof EmptyStateTransition) {
              assertIsTrue(transition instanceof EmptyStateTransition);
              transition.copyTo(thatTransition);
            } else if (thatTransition instanceof ProceduralPoseState) {
              assertIsTrue(transition instanceof ProceduralPoseState);
              transition.copyTo(thatTransition);
            } else {
              transition.copyTo(thatTransition);
            }
          }
        };
        _proto7.clone = function clone() {
          var that = new StateMachine(this._allowEmptyStates);
          this.copyTo(that);
          return that;
        };
        _proto7._addState = function _addState(state) {
          own(state, this);
          this._states.push(state);
          return state;
        };
        _createClass(StateMachine, [{
          key: "allowEmptyStates",
          get: function get() {
            return this._allowEmptyStates;
          }
        }, {
          key: "entryState",
          get: function get() {
            return this._entryState;
          }
        }, {
          key: "exitState",
          get: function get() {
            return this._exitState;
          }
        }, {
          key: "anyState",
          get: function get() {
            return this._anyState;
          }
        }]);
        return StateMachine;
      }(EditorExtendable), (_initializer17$2 = applyDecoratedInitializer(_class21$1.prototype, "_states", [serializable$j], function () {
        return [];
      }), _initializer18$2 = applyDecoratedInitializer(_class21$1.prototype, "_transitions", [serializable$j], function () {
        return [];
      }), _initializer19$1 = applyDecoratedInitializer(_class21$1.prototype, "_entryState", [serializable$j], null), _initializer20$1 = applyDecoratedInitializer(_class21$1.prototype, "_exitState", [serializable$j], null), _initializer21$1 = applyDecoratedInitializer(_class21$1.prototype, "_anyState", [serializable$j], null)), _class21$1)) || _class20$1);
      var SubStateMachine = (_dec9$8 = ccclass$n('cc.animation.SubStateMachine'), _dec9$8(_class23 = (_class24 = function (_InteractiveState) {
        _inheritsLoose(SubStateMachine, _InteractiveState);
        function SubStateMachine(allowEmptyStates) {
          var _this11;
          _this11 = _InteractiveState.call(this) || this;
          _this11._stateMachine = _initializer22$1 && _initializer22$1();
          _this11._stateMachine = new StateMachine(allowEmptyStates);
          return _this11;
        }
        var _proto8 = SubStateMachine.prototype;
        _proto8.copyTo = function copyTo(that) {
          _InteractiveState.prototype.copyTo.call(this, that);
          this._stateMachine.copyTo(that._stateMachine);
        };
        _createClass(SubStateMachine, [{
          key: "stateMachine",
          get: function get() {
            return this._stateMachine;
          }
        }]);
        return SubStateMachine;
      }(InteractiveState), (_initializer22$1 = applyDecoratedInitializer(_class24.prototype, "_stateMachine", [serializable$j], null)), _class24)) || _class23);
      var PoseGraphStash = (_dec10$5 = ccclass$n(CLASS_NAME_PREFIX_ANIM + "PoseGraphStash"), _dec10$5(_class26 = (_class27 = function (_EditorExtendable3) {
        _inheritsLoose(PoseGraphStash, _EditorExtendable3);
        function PoseGraphStash() {
          var _this12;
          for (var _len6 = arguments.length, args = new Array(_len6), _key6 = 0; _key6 < _len6; _key6++) {
            args[_key6] = arguments[_key6];
          }
          _this12 = _EditorExtendable3.call.apply(_EditorExtendable3, [this].concat(args)) || this;
          _this12.graph = _initializer23$1 && _initializer23$1();
          return _this12;
        }
        return PoseGraphStash;
      }(EditorExtendable), (_initializer23$1 = applyDecoratedInitializer(_class27.prototype, "graph", [serializable$j], function () {
        return new PoseGraph();
      })), _class27)) || _class26);
      var Layer = (_dec11$4 = ccclass$n('cc.animation.Layer'), _dec11$4(_class29 = (_class30 = function () {
        var _proto9 = Layer.prototype;
        _proto9.__callOnAfterDeserializeRecursive = function __callOnAfterDeserializeRecursive() {
          this.stateMachine._allowEmptyStates = true;
          this.stateMachine.__callOnAfterDeserializeRecursive();
          for (var stashId in this._stashes) {
            var stash = this._stashes[stashId];
            stash.graph.__callOnAfterDeserializeRecursive();
          }
        };
        _proto9.stashes = function stashes() {
          return Object.entries(this._stashes);
        };
        _proto9.getStash = function getStash(id) {
          return this._stashes[id];
        };
        _proto9.addStash = function addStash(id) {
          return this._stashes[id] = new PoseGraphStash();
        };
        _proto9.removeStash = function removeStash(id) {
          delete this._stashes[id];
        };
        _proto9.renameStash = function renameStash(id, newId) {
          this._stashes = renameObjectProperty(this._stashes, id, newId);
        };
        function Layer() {
          this[ownerSymbol] = void 0;
          this._stateMachine = _initializer24$1 && _initializer24$1();
          this.name = _initializer25$1 && _initializer25$1();
          this.weight = _initializer26$1 && _initializer26$1();
          this.mask = _initializer27$1 && _initializer27$1();
          this.additive = _initializer28$1 && _initializer28$1();
          this._stashes = _initializer29$1 && _initializer29$1();
          this._stateMachine = new StateMachine(true);
        }
        _createClass(Layer, [{
          key: "stateMachine",
          get: function get() {
            return this._stateMachine;
          }
        }]);
        return Layer;
      }(), (_initializer24$1 = applyDecoratedInitializer(_class30.prototype, "_stateMachine", [serializable$j], null), _initializer25$1 = applyDecoratedInitializer(_class30.prototype, "name", [serializable$j], function () {
        return '';
      }), _initializer26$1 = applyDecoratedInitializer(_class30.prototype, "weight", [serializable$j], function () {
        return 1.0;
      }), _initializer27$1 = applyDecoratedInitializer(_class30.prototype, "mask", [serializable$j], function () {
        return null;
      }), _initializer28$1 = applyDecoratedInitializer(_class30.prototype, "additive", [serializable$j], function () {
        return false;
      }), _initializer29$1 = applyDecoratedInitializer(_class30.prototype, "_stashes", [serializable$j], function () {
        return {};
      })), _class30)) || _class29);
      var LayerBlending;
      (function (LayerBlending) {
        LayerBlending[LayerBlending["override"] = 0] = "override";
        LayerBlending[LayerBlending["additive"] = 1] = "additive";
      })(LayerBlending || (LayerBlending = {}));
      var AnimationGraph = (_dec12$4 = ccclass$n('cc.animation.AnimationGraph'), _dec12$4(_class32 = (_class33 = function (_AnimationGraphLike) {
        _inheritsLoose(AnimationGraph, _AnimationGraphLike);
        function AnimationGraph() {
          var _this13;
          _this13 = _AnimationGraphLike.call(this) || this;
          _this13._layers = _initializer30$1 && _initializer30$1();
          _this13._variables = _initializer31$1 && _initializer31$1();
          return _this13;
        }
        var _proto10 = AnimationGraph.prototype;
        _proto10.onLoaded = function onLoaded() {
          var layers = this._layers;
          var nLayers = layers.length;
          for (var iLayer = 0; iLayer < nLayers; ++iLayer) {
            layers[iLayer].__callOnAfterDeserializeRecursive();
          }
        };
        _proto10.addLayer = function addLayer() {
          var layer = new Layer();
          this._layers.push(layer);
          return layer;
        };
        _proto10.removeLayer = function removeLayer(index) {
          removeAt(this._layers, index);
        };
        _proto10.moveLayer = function moveLayer(index, newIndex) {
          shift(this._layers, index, newIndex);
        };
        _proto10.addVariable = function addVariable(name, type, initialValue) {
          var variable = createVariable(type, initialValue);
          this._variables[name] = variable;
          return variable;
        };
        _proto10.removeVariable = function removeVariable(name) {
          delete this._variables[name];
        };
        _proto10.getVariable = function getVariable(name) {
          return this._variables[name];
        };
        _proto10.renameVariable = function renameVariable(name, newName) {
          this._variables = renameObjectProperty(this._variables, name, newName);
        };
        _createClass(AnimationGraph, [{
          key: "layers",
          get: function get() {
            return this._layers;
          }
        }, {
          key: "variables",
          get: function get() {
            return Object.entries(this._variables);
          }
        }]);
        return AnimationGraph;
      }(AnimationGraphLike), (_initializer30$1 = applyDecoratedInitializer(_class33.prototype, "_layers", [serializable$j], function () {
        return [];
      }), _initializer31$1 = applyDecoratedInitializer(_class33.prototype, "_variables", [serializable$j], function () {
        return {};
      })), _class33)) || _class32);

      var createEval = Symbol('[[createEval]]');

      var _dec$1n, _class$1l;
      var Motion = (_dec$1n = ccclass$n(CLASS_NAME_PREFIX_ANIM + "MotionBase"), _dec$1n(_class$1l = function (_EditorExtendable) {
        _inheritsLoose(Motion, _EditorExtendable);
        function Motion() {
          return _EditorExtendable.apply(this, arguments) || this;
        }
        var _proto = Motion.prototype;
        _proto.__callOnAfterDeserializeRecursive = function __callOnAfterDeserializeRecursive() {};
        return Motion;
      }(EditorExtendable)) || _class$1l);

      var RatioSampler = exports('am', function () {
        function RatioSampler(ratios) {
          this.ratios = void 0;
          this._findRatio = void 0;
          this.ratios = ratios;
          var currRatioDif;
          var lastRatioDif;
          var canOptimize = true;
          var EPSILON = 1e-6;
          for (var i = 1, l = ratios.length; i < l; i++) {
            currRatioDif = ratios[i] - ratios[i - 1];
            if (i === 1) {
              lastRatioDif = currRatioDif;
            } else if (Math.abs(currRatioDif - lastRatioDif) > EPSILON) {
              canOptimize = false;
              break;
            }
          }
          this._findRatio = canOptimize ? quickFindIndex : binarySearchEpsilon;
        }
        var _proto = RatioSampler.prototype;
        _proto.sample = function sample(ratio) {
          return this._findRatio(this.ratios, ratio);
        };
        return RatioSampler;
      }());
      legacyCC.RatioSampler = RatioSampler;
      var AnimCurve = exports('an', function () {
        AnimCurve.Bezier = function Bezier(controlPoints) {
          return controlPoints;
        };
        function AnimCurve(propertyCurveData, duration) {
          this.types = undefined;
          this.type = null;
          this._values = [];
          this._lerp = undefined;
          this._duration = void 0;
          this._array = void 0;
          this._duration = duration;
          this._values = propertyCurveData.values;
          var getCurveType = function getCurveType(easingMethod) {
            if (typeof easingMethod === 'string') {
              return easingMethod;
            } else if (Array.isArray(easingMethod)) {
              if (easingMethod[0] === easingMethod[1] && easingMethod[2] === easingMethod[3]) {
                return AnimCurve.Linear;
              } else {
                return AnimCurve.Bezier(easingMethod);
              }
            } else {
              return AnimCurve.Linear;
            }
          };
          if (propertyCurveData.easingMethod !== undefined) {
            this.type = getCurveType(propertyCurveData.easingMethod);
          } else if (Array.isArray(propertyCurveData.easingMethods)) {
            this.types = propertyCurveData.easingMethods.map(getCurveType);
          } else if (propertyCurveData.easingMethods !== undefined) {
            this.types = new Array(this._values.length).fill(null);
            for (var _i = 0, _Object$keys = Object.keys(propertyCurveData.easingMethods); _i < _Object$keys.length; _i++) {
              var index = _Object$keys[_i];
              this.types[index] = getCurveType(propertyCurveData.easingMethods[index]);
            }
          } else {
            this.type = null;
          }
          var firstValue = propertyCurveData.values[0];
          var interpolate = propertyCurveData.interpolate === undefined ? true : propertyCurveData.interpolate;
          if (interpolate) {
            this._lerp = selectLerpFx(firstValue);
          }
          if (propertyCurveData._arrayLength !== undefined) {
            this._array = new Array(propertyCurveData._arrayLength);
          }
        }
        var _proto2 = AnimCurve.prototype;
        _proto2.hasLerp = function hasLerp() {
          return !!this._lerp;
        };
        _proto2.valueAt = function valueAt(index) {
          if (this._array === undefined) {
            var _value = this._values[index];
            if (_value && _value.getNoLerp) {
              return _value.getNoLerp();
            } else {
              return _value;
            }
          } else {
            for (var i = 0; i < this._array.length; ++i) {
              this._array[i] = this._values[this._array.length * index + i];
            }
            return this._array;
          }
        };
        _proto2.valueBetween = function valueBetween(ratio, from, fromRatio, to, toRatio) {
          if (this._lerp) {
            var type = this.types ? this.types[from] : this.type;
            var dRatio = toRatio - fromRatio;
            var ratioBetweenFrames = (ratio - fromRatio) / dRatio;
            if (type) {
              ratioBetweenFrames = computeRatioByType(ratioBetweenFrames, type);
            }
            if (this._array === undefined) {
              var fromVal = this._values[from];
              var toVal = this._values[to];
              var _value2 = this._lerp(fromVal, toVal, ratioBetweenFrames, dRatio * this._duration);
              return _value2;
            } else {
              for (var i = 0; i < this._array.length; ++i) {
                var _fromVal = this._values[this._array.length * from + i];
                var _toVal = this._values[this._array.length * to + i];
                this._array[i] = this._lerp(_fromVal, _toVal, ratioBetweenFrames, dRatio * this._duration);
              }
              return this._array;
            }
          } else if (this._array === undefined) {
            return this.valueAt(from);
          } else {
            for (var _i2 = 0; _i2 < this._array.length; ++_i2) {
              this._array[_i2] = this._values[this._array.length * from + _i2];
            }
            return this._array;
          }
        };
        _proto2.empty = function empty() {
          return this._values.length === 0;
        };
        _proto2.constant = function constant() {
          return this._values.length === 1;
        };
        return AnimCurve;
      }());
      AnimCurve.Linear = null;
      legacyCC.AnimCurve = AnimCurve;
      var EventInfo = exports('ao', function () {
        function EventInfo() {
          this.events = [];
        }
        var _proto3 = EventInfo.prototype;
        _proto3.add = function add(func, params) {
          this.events.push({
            func: func || '',
            params: params || []
          });
        };
        return EventInfo;
      }());
      function sampleAnimationCurve(curve, sampler, ratio) {
        var index = sampler.sample(ratio);
        if (index < 0) {
          index = ~index;
          if (index <= 0) {
            index = 0;
          } else if (index >= sampler.ratios.length) {
            index = sampler.ratios.length - 1;
          } else {
            return curve.valueBetween(ratio, index - 1, sampler.ratios[index - 1], index, sampler.ratios[index]);
          }
        }
        return curve.valueAt(index);
      }
      legacyCC.sampleAnimationCurve = sampleAnimationCurve;
      function computeRatioByType(ratio, type) {
        if (typeof type === 'string') {
          var func = easing[type];
          if (func) {
            ratio = func(ratio);
          } else {
            errorID(3906, type);
          }
        } else if (Array.isArray(type)) {
          ratio = bezierByTime(type, ratio);
        }
        return ratio;
      }
      function quickFindIndex(ratios, ratio) {
        var length = ratios.length - 1;
        if (length === 0) {
          return 0;
        }
        var start = ratios[0];
        if (ratio < start) {
          return 0;
        }
        var end = ratios[length];
        if (ratio > end) {
          return length;
        }
        ratio = (ratio - start) / (end - start);
        var eachLength = 1 / length;
        var index = ratio / eachLength;
        var floorIndex = index | 0;
        var EPSILON = 1e-6;
        if (index - floorIndex < EPSILON) {
          return floorIndex;
        } else if (floorIndex + 1 - index < EPSILON) {
          return floorIndex + 1;
        }
        return ~(floorIndex + 1);
      }
      var selectLerpFx = function () {
        function makeValueTypeLerpFx(constructor) {
          var tempValue = new constructor();
          return function (from, to, ratio) {
            constructor.lerp(tempValue, from, to, ratio);
            return tempValue;
          };
        }
        function callLerpable(from, to, t, dt) {
          return from.lerp(to, t, dt);
        }
        function makeQuatSlerpFx() {
          var tempValue = new Quat();
          return function (from, to, t, dt) {
            return Quat.slerp(tempValue, from, to, t);
          };
        }
        return function (value) {
          if (value === null) {
            return undefined;
          }
          if (typeof value === 'number') {
            return lerp;
          } else if (typeof value === 'object' && value.constructor) {
            if (value instanceof Quat) {
              return makeQuatSlerpFx();
            } else if (value instanceof ValueType) {
              return makeValueTypeLerpFx(value.constructor);
            } else if (value.constructor === Number) {
              return lerp;
            } else if (isLerpable(value)) {
              return callLerpable;
            }
          }
          return undefined;
        };
      }();

      var _dec$1m, _class$1k, _class2$1f, _initializer$17, _dec2$1c, _class4$f, _class5$h, _initializer2$X;
      var UntypedTrackChannel = (_dec$1m = ccclass$n(CLASS_NAME_PREFIX_ANIM + "UntypedTrackChannel"), _dec$1m(_class$1k = (_class2$1f = function (_Channel) {
        _inheritsLoose(UntypedTrackChannel, _Channel);
        function UntypedTrackChannel() {
          var _this;
          _this = _Channel.call(this, new RealCurve()) || this;
          _this.property = _initializer$17 && _initializer$17();
          return _this;
        }
        return UntypedTrackChannel;
      }(Channel), (_initializer$17 = applyDecoratedInitializer(_class2$1f.prototype, "property", [serializable$j], function () {
        return '';
      })), _class2$1f)) || _class$1k);
      var UntypedTrack = (_dec2$1c = ccclass$n(CLASS_NAME_PREFIX_ANIM + "UntypedTrack"), _dec2$1c(_class4$f = (_class5$h = function (_Track) {
        _inheritsLoose(UntypedTrack, _Track);
        function UntypedTrack() {
          var _this2;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this2 = _Track.call.apply(_Track, [this].concat(args)) || this;
          _this2._channels = _initializer2$X && _initializer2$X();
          return _this2;
        }
        var _proto = UntypedTrack.prototype;
        _proto.channels = function channels() {
          return this._channels;
        };
        _proto[createEvalSymbol] = function () {
          throw new Error("UntypedTrack should be handled specially. Please file an issue.");
        };
        _proto.createLegacyEval = function createLegacyEval(hintValue) {
          var _this3 = this;
          var trySearchCurve = function trySearchCurve(property) {
            var _this3$_channels$find;
            return (_this3$_channels$find = _this3._channels.find(function (channel) {
              return channel.property === property;
            })) === null || _this3$_channels$find === void 0 ? void 0 : _this3$_channels$find.curve;
          };
          switch (true) {
            default:
              throw new Error(getError(3931));
            case hintValue instanceof Vec2:
              return new Vec2TrackEval(trySearchCurve('x'), trySearchCurve('y'));
            case hintValue instanceof Vec3:
              return new Vec3TrackEval(trySearchCurve('x'), trySearchCurve('y'), trySearchCurve('z'));
            case hintValue instanceof Vec4:
              return new Vec4TrackEval(trySearchCurve('x'), trySearchCurve('y'), trySearchCurve('z'), trySearchCurve('w'));
            case hintValue instanceof Color$1:
              return new ColorTrackEval(trySearchCurve('r'), trySearchCurve('g'), trySearchCurve('b'), trySearchCurve('a'));
            case hintValue instanceof Size$1:
              return new SizeTrackEval(trySearchCurve('width'), trySearchCurve('height'));
          }
        };
        _proto.addChannel = function addChannel(property) {
          var channel = new UntypedTrackChannel();
          channel.property = property;
          this._channels.push(channel);
          return channel;
        };
        _proto.upgrade = function upgrade(refine) {
          var _this4 = this;
          var trySearchChannel = function trySearchChannel(property, outChannel) {
            var untypedChannel = _this4.channels().find(function (channel) {
              return channel.property === property;
            });
            if (untypedChannel) {
              outChannel.name = untypedChannel.name;
              outChannel.curve.assignSorted(Array.from(untypedChannel.curve.times()), Array.from(untypedChannel.curve.values()));
            }
          };
          var kind = refine(this.path, this.proxy);
          switch (kind) {
            default:
              break;
            case 'vec2':
            case 'vec3':
            case 'vec4':
              {
                var track = new VectorTrack();
                track.path = this.path;
                track.proxy = this.proxy;
                track.componentsCount = kind === 'vec2' ? 2 : kind === 'vec3' ? 3 : 4;
                var _track$channels = track.channels(),
                  x = _track$channels[0],
                  y = _track$channels[1],
                  z = _track$channels[2],
                  w = _track$channels[3];
                switch (kind) {
                  case 'vec4':
                    trySearchChannel('w', w);
                  case 'vec3':
                    trySearchChannel('z', z);
                  default:
                  case 'vec2':
                    trySearchChannel('x', x);
                    trySearchChannel('y', y);
                }
                return track;
              }
            case 'color':
              {
                var _track = new ColorTrack();
                var _track$channels2 = _track.channels(),
                  r = _track$channels2[0],
                  g = _track$channels2[1],
                  b = _track$channels2[2],
                  a = _track$channels2[3];
                trySearchChannel('r', r);
                trySearchChannel('g', g);
                trySearchChannel('b', b);
                trySearchChannel('a', a);
                trySearchChannel('x', r);
                trySearchChannel('y', g);
                trySearchChannel('z', b);
                trySearchChannel('w', a);
                return _track;
              }
            case 'size':
              break;
          }
          return null;
        };
        return UntypedTrack;
      }(Track), (_initializer2$X = applyDecoratedInitializer(_class5$h.prototype, "_channels", [serializable$j], function () {
        return [];
      })), _class5$h)) || _class4$f);

      var AnimationClipLegacyData = function () {
        function AnimationClipLegacyData(duration) {
          this._keys = [];
          this._curves = [];
          this._commonTargets = [];
          this._ratioSamplers = [];
          this._runtimeCurves = void 0;
          this._data = null;
          this._duration = void 0;
          this._duration = duration;
        }
        var _proto = AnimationClipLegacyData.prototype;
        _proto.getPropertyCurves = function getPropertyCurves() {
          if (!this._runtimeCurves) {
            this._createPropertyCurves();
          }
          return this._runtimeCurves;
        };
        _proto.toTracks = function toTracks() {
          var newTracks = [];
          var legacyKeys = this.keys,
            legacyCurves = this.curves,
            legacyCommonTargets = this.commonTargets;
          var convertTrackPath = function convertTrackPath(track, modifiers, valueAdapter) {
            var trackPath = new TrackPath();
            for (var _iterator = _createForOfIteratorHelperLoose(modifiers), _step; !(_step = _iterator()).done;) {
              var modifier = _step.value;
              if (typeof modifier === 'string') {
                trackPath.toProperty(modifier);
              } else if (typeof modifier === 'number') {
                trackPath.toElement(modifier);
              } else if (modifier instanceof HierarchyPath) {
                trackPath.toHierarchy(modifier.path);
              } else if (modifier instanceof ComponentPath) {
                trackPath.toComponent(modifier.component);
              } else {
                trackPath.toCustomized(modifier);
              }
            }
            track.path = trackPath;
            track.proxy = valueAdapter;
          };
          var untypedTracks = legacyCommonTargets.map(function (legacyCommonTarget) {
            var track = new UntypedTrack();
            convertTrackPath(track, legacyCommonTarget.modifiers, legacyCommonTarget.valueAdapter);
            newTracks.push(track);
            return track;
          });
          var _loop = function _loop() {
              var _legacyCurveData$inte;
              var legacyCurve = _step2.value;
              var legacyCurveData = legacyCurve.data;
              var legacyValues = legacyCurveData.values;
              if (legacyValues.length === 0) {
                return 0;
              }
              var legacyKeysIndex = legacyCurveData.keys;
              var times = legacyKeysIndex < 0 ? [0.0] : legacyKeys[legacyCurveData.keys];
              var firstValue = legacyValues[0];
              var interpolate = (_legacyCurveData$inte = legacyCurveData.interpolate) !== null && _legacyCurveData$inte !== void 0 ? _legacyCurveData$inte : true;
              assertIsTrue(typeof legacyCurveData._arrayLength !== 'number' || typeof firstValue === 'number');
              var legacyEasingMethodConverter = new LegacyEasingMethodConverter(legacyCurveData, times.length);
              var installPathAndSetter = function installPathAndSetter(track) {
                convertTrackPath(track, legacyCurve.modifiers, legacyCurve.valueAdapter);
              };
              var legacyCommonTargetCurve;
              if (typeof legacyCurve.commonTarget === 'number') {
                if (!legacyValues.every(function (value) {
                  return typeof value === 'number';
                })) {
                  warnID(3932);
                  return 0;
                }
                if (legacyCurve.valueAdapter || legacyCurve.modifiers.length !== 1 || typeof legacyCurve.modifiers[0] !== 'string') {
                  warnID(3933);
                  return 0;
                }
                var _propertyName = legacyCurve.modifiers[0];
                var untypedTrack = untypedTracks[legacyCurve.commonTarget];
                var _untypedTrack$addChan = untypedTrack.addChannel(_propertyName),
                  curve = _untypedTrack$addChan.curve;
                legacyCommonTargetCurve = curve;
              }
              var convertCurve = function convertCurve() {
                if (typeof firstValue === 'number') {
                  if (!legacyValues.every(function (value) {
                    return typeof value === 'number';
                  })) {
                    warnID(3934);
                    return;
                  }
                  var realCurve;
                  if (legacyCommonTargetCurve) {
                    realCurve = legacyCommonTargetCurve;
                  } else {
                    var track = new RealTrack();
                    installPathAndSetter(track);
                    newTracks.push(track);
                    realCurve = track.channel.curve;
                  }
                  var interpolationMethod = interpolate ? RealInterpolationMode.LINEAR : RealInterpolationMode.CONSTANT;
                  realCurve.assignSorted(times, legacyValues.map(function (value) {
                    return {
                      value: value,
                      interpolationMode: interpolationMethod
                    };
                  }));
                  legacyEasingMethodConverter.convert(realCurve);
                  return;
                } else if (typeof firstValue === 'object') {
                  switch (true) {
                    default:
                      break;
                    case everyInstanceOf(legacyValues, Vec2):
                    case everyInstanceOf(legacyValues, Vec3):
                    case everyInstanceOf(legacyValues, Vec4):
                      {
                        var components = firstValue instanceof Vec2 ? 2 : firstValue instanceof Vec3 ? 3 : 4;
                        var _track = new VectorTrack();
                        installPathAndSetter(_track);
                        _track.componentsCount = components;
                        var _track$channels = _track.channels(),
                          x = _track$channels[0].curve,
                          y = _track$channels[1].curve,
                          z = _track$channels[2].curve,
                          w = _track$channels[3].curve;
                        var interpolationMode = interpolate ? RealInterpolationMode.LINEAR : RealInterpolationMode.CONSTANT;
                        var valueToFrame = function valueToFrame(value) {
                          return {
                            value: value,
                            interpolationMode: interpolationMode
                          };
                        };
                        switch (components) {
                          case 4:
                            w.assignSorted(times, legacyValues.map(function (value) {
                              return valueToFrame(value.w);
                            }));
                            legacyEasingMethodConverter.convert(w);
                          case 3:
                            z.assignSorted(times, legacyValues.map(function (value) {
                              return valueToFrame(value.z);
                            }));
                            legacyEasingMethodConverter.convert(z);
                          default:
                            x.assignSorted(times, legacyValues.map(function (value) {
                              return valueToFrame(value.x);
                            }));
                            legacyEasingMethodConverter.convert(x);
                            y.assignSorted(times, legacyValues.map(function (value) {
                              return valueToFrame(value.y);
                            }));
                            legacyEasingMethodConverter.convert(y);
                            break;
                        }
                        newTracks.push(_track);
                        return;
                      }
                    case everyInstanceOf(legacyValues, Quat):
                      {
                        var _track2 = new QuatTrack();
                        installPathAndSetter(_track2);
                        var _interpolationMode = interpolate ? QuatInterpolationMode.SLERP : QuatInterpolationMode.CONSTANT;
                        _track2.channel.curve.assignSorted(times, legacyValues.map(function (value) {
                          return {
                            value: Quat.clone(value),
                            interpolationMode: _interpolationMode
                          };
                        }));
                        legacyEasingMethodConverter.convertQuatCurve(_track2.channel.curve);
                        newTracks.push(_track2);
                        return;
                      }
                    case everyInstanceOf(legacyValues, Color$1):
                      {
                        var _track3 = new ColorTrack();
                        installPathAndSetter(_track3);
                        var _track3$channels = _track3.channels(),
                          r = _track3$channels[0].curve,
                          g = _track3$channels[1].curve,
                          b = _track3$channels[2].curve,
                          a = _track3$channels[3].curve;
                        var _interpolationMode2 = interpolate ? RealInterpolationMode.LINEAR : RealInterpolationMode.CONSTANT;
                        var _valueToFrame = function _valueToFrame(value) {
                          return {
                            value: value,
                            interpolationMode: _interpolationMode2
                          };
                        };
                        r.assignSorted(times, legacyValues.map(function (value) {
                          return _valueToFrame(value.r);
                        }));
                        legacyEasingMethodConverter.convert(r);
                        g.assignSorted(times, legacyValues.map(function (value) {
                          return _valueToFrame(value.g);
                        }));
                        legacyEasingMethodConverter.convert(g);
                        b.assignSorted(times, legacyValues.map(function (value) {
                          return _valueToFrame(value.b);
                        }));
                        legacyEasingMethodConverter.convert(b);
                        a.assignSorted(times, legacyValues.map(function (value) {
                          return _valueToFrame(value.a);
                        }));
                        legacyEasingMethodConverter.convert(a);
                        newTracks.push(_track3);
                        return;
                      }
                    case everyInstanceOf(legacyValues, Size$1):
                      {
                        var _track4 = new SizeTrack();
                        installPathAndSetter(_track4);
                        var _track4$channels = _track4.channels(),
                          width = _track4$channels[0].curve,
                          height = _track4$channels[1].curve;
                        var _interpolationMode3 = interpolate ? RealInterpolationMode.LINEAR : RealInterpolationMode.CONSTANT;
                        var _valueToFrame2 = function _valueToFrame2(value) {
                          return {
                            value: value,
                            interpolationMode: _interpolationMode3
                          };
                        };
                        width.assignSorted(times, legacyValues.map(function (value) {
                          return _valueToFrame2(value.width);
                        }));
                        legacyEasingMethodConverter.convert(width);
                        height.assignSorted(times, legacyValues.map(function (value) {
                          return _valueToFrame2(value.height);
                        }));
                        legacyEasingMethodConverter.convert(height);
                        newTracks.push(_track4);
                        return;
                      }
                    case everyInstanceOf(legacyValues, CubicSplineNumberValue):
                      {
                        assertIsTrue(legacyEasingMethodConverter.nil);
                        var _track5 = new RealTrack();
                        installPathAndSetter(_track5);
                        var _interpolationMode4 = interpolate ? RealInterpolationMode.CUBIC : RealInterpolationMode.CONSTANT;
                        _track5.channel.curve.assignSorted(times, legacyValues.map(function (value) {
                          return {
                            value: value.dataPoint,
                            leftTangent: value.inTangent,
                            rightTangent: value.outTangent,
                            interpolationMode: _interpolationMode4
                          };
                        }));
                        newTracks.push(_track5);
                        return;
                      }
                    case everyInstanceOf(legacyValues, CubicSplineVec2Value):
                    case everyInstanceOf(legacyValues, CubicSplineVec3Value):
                    case everyInstanceOf(legacyValues, CubicSplineVec4Value):
                      {
                        assertIsTrue(legacyEasingMethodConverter.nil);
                        var _components = firstValue instanceof CubicSplineVec2Value ? 2 : firstValue instanceof CubicSplineVec3Value ? 3 : 4;
                        var _track6 = new VectorTrack();
                        installPathAndSetter(_track6);
                        _track6.componentsCount = _components;
                        var _track6$channels = _track6.channels(),
                          _x = _track6$channels[0],
                          _y = _track6$channels[1],
                          _z = _track6$channels[2],
                          _w = _track6$channels[3];
                        var _interpolationMode5 = interpolate ? RealInterpolationMode.LINEAR : RealInterpolationMode.CONSTANT;
                        var _valueToFrame3 = function _valueToFrame3(value, inTangent, outTangent) {
                          return {
                            value: value,
                            leftTangent: inTangent,
                            rightTangent: outTangent,
                            interpolationMode: _interpolationMode5
                          };
                        };
                        switch (_components) {
                          case 4:
                            _w.curve.assignSorted(times, legacyValues.map(function (value) {
                              return _valueToFrame3(value.dataPoint.w, value.inTangent.w, value.outTangent.w);
                            }));
                          case 3:
                            _z.curve.assignSorted(times, legacyValues.map(function (value) {
                              return _valueToFrame3(value.dataPoint.z, value.inTangent.z, value.outTangent.z);
                            }));
                          default:
                            _x.curve.assignSorted(times, legacyValues.map(function (value) {
                              return _valueToFrame3(value.dataPoint.y, value.inTangent.y, value.outTangent.y);
                            }));
                            _y.curve.assignSorted(times, legacyValues.map(function (value) {
                              return _valueToFrame3(value.dataPoint.x, value.inTangent.x, value.outTangent.x);
                            }));
                            break;
                        }
                        newTracks.push(_track6);
                        return;
                      }
                    case legacyValues.every(function (value) {
                      return value instanceof CubicSplineQuatValue;
                    }):
                      {
                        warnID(3935);
                        break;
                      }
                  }
                }
                var objectTrack = new ObjectTrack();
                installPathAndSetter(objectTrack);
                objectTrack.channel.curve.assignSorted(times, legacyValues);
                newTracks.push(objectTrack);
              };
              convertCurve();
            },
            _ret;
          for (var _iterator2 = _createForOfIteratorHelperLoose(legacyCurves), _step2; !(_step2 = _iterator2()).done;) {
            _ret = _loop();
            if (_ret === 0) continue;
          }
          return newTracks;
        };
        _proto._createPropertyCurves = function _createPropertyCurves() {
          var _this = this;
          this._ratioSamplers = this._keys.map(function (keys) {
            return new RatioSampler(keys.map(function (key) {
              return key / _this._duration;
            }));
          });
          this._runtimeCurves = this._curves.map(function (targetCurve) {
            return {
              curve: new AnimCurve(targetCurve.data, _this._duration),
              modifiers: targetCurve.modifiers,
              valueAdapter: targetCurve.valueAdapter,
              sampler: _this._ratioSamplers[targetCurve.data.keys],
              commonTarget: targetCurve.commonTarget
            };
          });
        };
        _createClass(AnimationClipLegacyData, [{
          key: "keys",
          get: function get() {
            return this._keys;
          },
          set: function set(value) {
            this._keys = value;
          }
        }, {
          key: "curves",
          get: function get() {
            return this._curves;
          },
          set: function set(value) {
            this._curves = value;
            delete this._runtimeCurves;
          }
        }, {
          key: "commonTargets",
          get: function get() {
            return this._commonTargets;
          },
          set: function set(value) {
            this._commonTargets = value;
          }
        }, {
          key: "data",
          get: function get() {
            return this._data;
          }
        }]);
        return AnimationClipLegacyData;
      }();
      function everyInstanceOf(array, constructor) {
        return array.every(function (element) {
          return element instanceof constructor;
        });
      }
      var LegacyEasingMethodConverter = function () {
        function LegacyEasingMethodConverter(legacyCurveData, keyframesCount) {
          this._easingMethods = void 0;
          var easingMethods = legacyCurveData.easingMethods;
          if (Array.isArray(easingMethods)) {
            if (easingMethods.length === 0 && keyframesCount !== 0) {
              this._easingMethods = new Array(keyframesCount).fill(null);
            } else {
              this._easingMethods = easingMethods;
            }
          } else if (easingMethods === undefined) {
            this._easingMethods = new Array(keyframesCount).fill(legacyCurveData.easingMethod);
          } else {
            this._easingMethods = Array.from({
              length: keyframesCount
            }, function (_, index) {
              var _easingMethods$index;
              return (_easingMethods$index = easingMethods[index]) !== null && _easingMethods$index !== void 0 ? _easingMethods$index : null;
            });
          }
        }
        var _proto2 = LegacyEasingMethodConverter.prototype;
        _proto2.convert = function convert(curve) {
          var easingMethods = this._easingMethods;
          if (!easingMethods) {
            return;
          }
          var nKeyframes = curve.keyFramesCount;
          if (curve.keyFramesCount < 2) {
            return;
          }
          if (Array.isArray(easingMethods)) {
            assertIsTrue(nKeyframes === easingMethods.length);
          }
          var iLastKeyframe = nKeyframes - 1;
          for (var iKeyframe = 0; iKeyframe < iLastKeyframe; ++iKeyframe) {
            var easingMethod = easingMethods[iKeyframe];
            if (!easingMethod) {
              continue;
            }
            if (Array.isArray(easingMethod)) {
              timeBezierToTangents(easingMethod, curve.getKeyframeTime(iKeyframe), curve.getKeyframeValue(iKeyframe), curve.getKeyframeTime(iKeyframe + 1), curve.getKeyframeValue(iKeyframe + 1));
            } else {
              applyLegacyEasingMethodName(easingMethod, curve, iKeyframe);
            }
          }
        };
        _proto2.convertQuatCurve = function convertQuatCurve(curve) {
          var easingMethods = this._easingMethods;
          if (!easingMethods) {
            return;
          }
          var nKeyframes = curve.keyFramesCount;
          if (curve.keyFramesCount < 2) {
            return;
          }
          if (Array.isArray(easingMethods)) {
            assertIsTrue(nKeyframes === easingMethods.length);
          }
          var iLastKeyframe = nKeyframes - 1;
          for (var iKeyframe = 0; iKeyframe < iLastKeyframe; ++iKeyframe) {
            var easingMethod = easingMethods[iKeyframe];
            if (!easingMethod) {
              continue;
            }
            if (Array.isArray(easingMethod)) {
              curve.getKeyframeValue(iKeyframe).easingMethod = easingMethod.slice();
            } else {
              applyLegacyEasingMethodNameIntoQuatCurve(easingMethod, curve, iKeyframe);
            }
          }
        };
        _createClass(LegacyEasingMethodConverter, [{
          key: "nil",
          get: function get() {
            return !this._easingMethods || this._easingMethods.every(function (easingMethod) {
              return easingMethod === null || easingMethod === undefined;
            });
          }
        }]);
        return LegacyEasingMethodConverter;
      }();
      function applyLegacyEasingMethodName(easingMethodName, curve, keyframeIndex) {
        assertIsTrue(keyframeIndex !== curve.keyFramesCount - 1);
        assertIsTrue(easingMethodName in easingMethodNameMap);
        var keyframeValue = curve.getKeyframeValue(keyframeIndex);
        var easingMethod = easingMethodNameMap[easingMethodName];
        if (easingMethod === EasingMethod.CONSTANT) {
          keyframeValue.interpolationMode = RealInterpolationMode.CONSTANT;
        } else {
          keyframeValue.interpolationMode = RealInterpolationMode.LINEAR;
          keyframeValue.easingMethod = easingMethod;
        }
      }
      function applyLegacyEasingMethodNameIntoQuatCurve(easingMethodName, curve, keyframeIndex) {
        assertIsTrue(keyframeIndex !== curve.keyFramesCount - 1);
        assertIsTrue(easingMethodName in easingMethodNameMap);
        var keyframeValue = curve.getKeyframeValue(keyframeIndex);
        var easingMethod = easingMethodNameMap[easingMethodName];
        keyframeValue.easingMethod = easingMethod;
      }
      var easingMethodNameMap = {
        constant: EasingMethod.CONSTANT,
        linear: EasingMethod.LINEAR,
        quadIn: EasingMethod.QUAD_IN,
        quadOut: EasingMethod.QUAD_OUT,
        quadInOut: EasingMethod.QUAD_IN_OUT,
        quadOutIn: EasingMethod.QUAD_OUT_IN,
        cubicIn: EasingMethod.CUBIC_IN,
        cubicOut: EasingMethod.CUBIC_OUT,
        cubicInOut: EasingMethod.CUBIC_IN_OUT,
        cubicOutIn: EasingMethod.CUBIC_OUT_IN,
        quartIn: EasingMethod.QUART_IN,
        quartOut: EasingMethod.QUART_OUT,
        quartInOut: EasingMethod.QUART_IN_OUT,
        quartOutIn: EasingMethod.QUART_OUT_IN,
        quintIn: EasingMethod.QUINT_IN,
        quintOut: EasingMethod.QUINT_OUT,
        quintInOut: EasingMethod.QUINT_IN_OUT,
        quintOutIn: EasingMethod.QUINT_OUT_IN,
        sineIn: EasingMethod.SINE_IN,
        sineOut: EasingMethod.SINE_OUT,
        sineInOut: EasingMethod.SINE_IN_OUT,
        sineOutIn: EasingMethod.SINE_OUT_IN,
        expoIn: EasingMethod.EXPO_IN,
        expoOut: EasingMethod.EXPO_OUT,
        expoInOut: EasingMethod.EXPO_IN_OUT,
        expoOutIn: EasingMethod.EXPO_OUT_IN,
        circIn: EasingMethod.CIRC_IN,
        circOut: EasingMethod.CIRC_OUT,
        circInOut: EasingMethod.CIRC_IN_OUT,
        circOutIn: EasingMethod.CIRC_OUT_IN,
        elasticIn: EasingMethod.ELASTIC_IN,
        elasticOut: EasingMethod.ELASTIC_OUT,
        elasticInOut: EasingMethod.ELASTIC_IN_OUT,
        elasticOutIn: EasingMethod.ELASTIC_OUT_IN,
        backIn: EasingMethod.BACK_IN,
        backOut: EasingMethod.BACK_OUT,
        backInOut: EasingMethod.BACK_IN_OUT,
        backOutIn: EasingMethod.BACK_OUT_IN,
        bounceIn: EasingMethod.BOUNCE_IN,
        bounceOut: EasingMethod.BOUNCE_OUT,
        bounceInOut: EasingMethod.BOUNCE_IN_OUT,
        bounceOutIn: EasingMethod.BOUNCE_OUT_IN,
        smooth: EasingMethod.SMOOTH,
        fade: EasingMethod.FADE
      };
      function timeBezierToTangents(timeBezierPoints, previousTime, previousKeyframe, nextTime, nextKeyframe) {
        var p1X = timeBezierPoints[0],
          p1Y = timeBezierPoints[1],
          p2X = timeBezierPoints[2],
          p2Y = timeBezierPoints[3];
        var previousValue = previousKeyframe.value;
        var nextValue = nextKeyframe.value;
        var dValue = nextValue - previousValue;
        var dTime = nextTime - previousTime;
        var fx = 3 * dTime;
        var fy = 3 * dValue;
        var t1x = p1X * fx;
        var t1y = p1Y * fy;
        var t2x = (1.0 - p2X) * fx;
        var t2y = (1.0 - p2Y) * fy;
        var ONE_THIRD = 1.0 / 3.0;
        var previousTangent = t1y / t1x;
        var previousTangentWeight = Math.sqrt(t1x * t1x + t1y * t1y) * ONE_THIRD;
        var nextTangent = t2y / t2x;
        var nextTangentWeight = Math.sqrt(t2x * t2x + t2y * t2y) * ONE_THIRD;
        previousKeyframe.interpolationMode = RealInterpolationMode.CUBIC;
        previousKeyframe.tangentWeightMode = ensureRightTangentWeightMode(previousKeyframe.tangentWeightMode);
        previousKeyframe.rightTangent = previousTangent;
        previousKeyframe.rightTangentWeight = previousTangentWeight;
        nextKeyframe.tangentWeightMode = ensureLeftTangentWeightMode(nextKeyframe.tangentWeightMode);
        nextKeyframe.leftTangent = nextTangent;
        nextKeyframe.leftTangentWeight = nextTangentWeight;
      }
      function ensureLeftTangentWeightMode(tangentWeightMode) {
        if (tangentWeightMode === TangentWeightMode.NONE) {
          return TangentWeightMode.LEFT;
        } else if (tangentWeightMode === TangentWeightMode.RIGHT) {
          return TangentWeightMode.BOTH;
        } else {
          return tangentWeightMode;
        }
      }
      function ensureRightTangentWeightMode(tangentWeightMode) {
        if (tangentWeightMode === TangentWeightMode.NONE) {
          return TangentWeightMode.RIGHT;
        } else if (tangentWeightMode === TangentWeightMode.LEFT) {
          return TangentWeightMode.BOTH;
        } else {
          return tangentWeightMode;
        }
      }

      var _dec$1l, _class$1j, _class2$1e, _initializer$16, _dec2$1b, _class4$e, _class5$g, _initializer2$W, _initializer3$C, _initializer4$r, _initializer5$j, _dec3$R, _class7$5, _class8$5, _initializer6$d, _initializer7$c, _dec4$E, _class10$1, _dec5$x, _class11$1, _dec6$i, _class12, _class13$1, _initializer8$b, _initializer9$a, _dec7$d, _class20, _class21, _initializer10$9, _initializer11$9, _initializer12$7, _initializer13$6;
      var ccclass$e = ccclass$n,
        serializable$b = serializable$j;
      function throwIfSplitMethodIsNotValid() {
        throw new Error("split() only valid in Editor.");
      }
      (_dec$1l = ccclass$e(CLASS_NAME_PREFIX_ANIM + "ExoticAnimation"), _dec$1l(_class$1j = (_class2$1e = function () {
        function ExoticAnimation() {
          this._nodeAnimations = _initializer$16 && _initializer$16();
        }
        var _proto = ExoticAnimation.prototype;
        _proto.createEvaluator = function createEvaluator(binder) {
          return new ExoticTrsAnimationEvaluator(this._nodeAnimations, binder);
        };
        _proto.createEvaluatorForAnimationGraph = function createEvaluatorForAnimationGraph(context) {
          return new ExoticTrsAGEvaluation(this._nodeAnimations, context);
        };
        _proto.addNodeAnimation = function addNodeAnimation(path) {
          var nodeAnimation = new ExoticNodeAnimation(path);
          this._nodeAnimations.push(nodeAnimation);
          return nodeAnimation;
        };
        _proto.collectAnimatedJoints = function collectAnimatedJoints() {
          return Array.from(new Set(this._nodeAnimations.map(function (_ref) {
            var path = _ref.path;
            return path;
          })));
        };
        _proto.split = function split(from, to) {
          {
            return throwIfSplitMethodIsNotValid();
          }
        };
        _proto.toHashString = function toHashString() {
          return this._nodeAnimations.map(function (nodeAnimation) {
            return nodeAnimation.toHashString();
          }).join('\n');
        };
        return ExoticAnimation;
      }(), (_initializer$16 = applyDecoratedInitializer(_class2$1e.prototype, "_nodeAnimations", [serializable$b], function () {
        return [];
      })), _class2$1e)) || _class$1j);
      var ExoticNodeAnimation = (_dec2$1b = ccclass$e(CLASS_NAME_PREFIX_ANIM + "ExoticNodeAnimation"), _dec2$1b(_class4$e = (_class5$g = function () {
        function ExoticNodeAnimation(path) {
          this._path = _initializer2$W && _initializer2$W();
          this._position = _initializer3$C && _initializer3$C();
          this._rotation = _initializer4$r && _initializer4$r();
          this._scale = _initializer5$j && _initializer5$j();
          this._path = path;
        }
        var _proto2 = ExoticNodeAnimation.prototype;
        _proto2.createPosition = function createPosition(times, values) {
          this._position = new ExoticTrack(times, new ExoticVec3TrackValues(values));
        };
        _proto2.createRotation = function createRotation(times, values) {
          this._rotation = new ExoticTrack(times, new ExoticQuatTrackValues(values));
        };
        _proto2.createScale = function createScale(times, values) {
          this._scale = new ExoticTrack(times, new ExoticVec3TrackValues(values));
        };
        _proto2.createEvaluator = function createEvaluator(binder) {
          return new ExoticNodeAnimationEvaluator(this._path, this._position, this._rotation, this._scale, binder);
        };
        _proto2.createEvaluatorForAnimationGraph = function createEvaluatorForAnimationGraph(context) {
          var transformHandle = context.bindTransform(this._path);
          if (!transformHandle) {
            return null;
          }
          return new ExoticNodeAnimationAGEvaluation(transformHandle, this._position, this._rotation, this._scale);
        };
        _proto2.split = function split(from, to, splitInfoCache) {
          {
            return throwIfSplitMethodIsNotValid();
          }
        };
        _proto2.toHashString = function toHashString() {
          var _this$_position$toHas, _this$_position, _this$_scale$toHashSt, _this$_scale, _this$_rotation$toHas, _this$_rotation;
          return this._path + "\n" + ((_this$_position$toHas = (_this$_position = this._position) === null || _this$_position === void 0 ? void 0 : _this$_position.toHashString()) !== null && _this$_position$toHas !== void 0 ? _this$_position$toHas : '') + ((_this$_scale$toHashSt = (_this$_scale = this._scale) === null || _this$_scale === void 0 ? void 0 : _this$_scale.toHashString()) !== null && _this$_scale$toHashSt !== void 0 ? _this$_scale$toHashSt : '') + ((_this$_rotation$toHas = (_this$_rotation = this._rotation) === null || _this$_rotation === void 0 ? void 0 : _this$_rotation.toHashString()) !== null && _this$_rotation$toHas !== void 0 ? _this$_rotation$toHas : '');
        };
        _createClass(ExoticNodeAnimation, [{
          key: "path",
          get: function get() {
            return this._path;
          }
        }]);
        return ExoticNodeAnimation;
      }(), (_initializer2$W = applyDecoratedInitializer(_class5$g.prototype, "_path", [serializable$b], function () {
        return '';
      }), _initializer3$C = applyDecoratedInitializer(_class5$g.prototype, "_position", [serializable$b], function () {
        return null;
      }), _initializer4$r = applyDecoratedInitializer(_class5$g.prototype, "_rotation", [serializable$b], function () {
        return null;
      }), _initializer5$j = applyDecoratedInitializer(_class5$g.prototype, "_scale", [serializable$b], function () {
        return null;
      })), _class5$g)) || _class4$e);
      function floatToHashString(value) {
        return value.toPrecision(2);
      }
      function floatArrayToHashString(values) {
        return values.map(function (v) {
          return Number.parseFloat(floatToHashString(v));
        }).join(' ');
      }
      var ExoticVectorLikeTrackValues = (_dec3$R = ccclass$e(CLASS_NAME_PREFIX_ANIM + "ExoticVectorLikeTrackValues"), _dec3$R(_class7$5 = (_class8$5 = function () {
        function ExoticVectorLikeTrackValues(values) {
          this._values = _initializer6$d && _initializer6$d();
          this._isQuantized = _initializer7$c && _initializer7$c();
          this._values = values;
        }
        var _proto3 = ExoticVectorLikeTrackValues.prototype;
        _proto3.quantize = function quantize(type) {
          assertIsTrue(!this._isQuantized);
          this._values = _quantize(this._values, type);
          this._isQuantized = true;
        };
        _proto3.toHashString = function toHashString() {
          var isQuantized = this._isQuantized,
            values = this._values;
          return isQuantized + " " + (isQuantized ? values.toHashString() : floatArrayToHashString(values));
        };
        _createClass(ExoticVectorLikeTrackValues, [{
          key: "precision",
          get: function get() {
            return this._isQuantized ? this._values.originalPrecision : getFloatArrayPrecision(this._values);
          }
        }]);
        return ExoticVectorLikeTrackValues;
      }(), (_initializer6$d = applyDecoratedInitializer(_class8$5.prototype, "_values", [serializable$b], null), _initializer7$c = applyDecoratedInitializer(_class8$5.prototype, "_isQuantized", [serializable$b], function () {
        return false;
      })), _class8$5)) || _class7$5);
      var ExoticVec3TrackValues = (_dec4$E = ccclass$e(CLASS_NAME_PREFIX_ANIM + "ExoticVec3TrackValues"), _dec4$E(_class10$1 = function (_ExoticVectorLikeTrac) {
        _inheritsLoose(ExoticVec3TrackValues, _ExoticVectorLikeTrac);
        function ExoticVec3TrackValues() {
          return _ExoticVectorLikeTrac.apply(this, arguments) || this;
        }
        ExoticVec3TrackValues.imitate = function imitate(values, model) {
          var trackValues = new ExoticVec3TrackValues(values);
          if (model._isQuantized) {
            trackValues.quantize(model._values.quantizationType);
          }
          return trackValues;
        };
        var _proto4 = ExoticVec3TrackValues.prototype;
        _proto4.get = function get(index, resultValue) {
          var values = this._values,
            isQuantized = this._isQuantized;
          if (isQuantized) {
            loadVec3FromQuantized(values, index, resultValue);
          } else {
            Vec3.fromArray(resultValue, values, index * 3);
          }
        };
        _proto4.lerp = function lerp(prevIndex, nextIndex, ratio, prevValue, nextValue, resultValue) {
          var values = this._values,
            isQuantized = this._isQuantized;
          if (isQuantized) {
            loadVec3FromQuantized(values, prevIndex, prevValue);
            loadVec3FromQuantized(values, nextIndex, nextValue);
          } else {
            Vec3.fromArray(prevValue, values, prevIndex * 3);
            Vec3.fromArray(nextValue, values, nextIndex * 3);
          }
          Vec3.lerp(resultValue, prevValue, nextValue, ratio);
        };
        return ExoticVec3TrackValues;
      }(ExoticVectorLikeTrackValues)) || _class10$1);
      var ExoticQuatTrackValues = (_dec5$x = ccclass$e(CLASS_NAME_PREFIX_ANIM + "ExoticQuatTrackValues"), _dec5$x(_class11$1 = function (_ExoticVectorLikeTrac2) {
        _inheritsLoose(ExoticQuatTrackValues, _ExoticVectorLikeTrac2);
        function ExoticQuatTrackValues() {
          return _ExoticVectorLikeTrac2.apply(this, arguments) || this;
        }
        ExoticQuatTrackValues.imitate = function imitate(values, model) {
          var trackValues = new ExoticQuatTrackValues(values);
          if (model._isQuantized) {
            trackValues.quantize(model._values.quantizationType);
          }
          return trackValues;
        };
        var _proto5 = ExoticQuatTrackValues.prototype;
        _proto5.get = function get(index, resultValue) {
          var values = this._values,
            isQuantized = this._isQuantized;
          if (isQuantized) {
            loadQuatFromQuantized(values, index, resultValue);
          } else {
            Quat.fromArray(resultValue, values, index * 4);
          }
        };
        _proto5.lerp = function lerp(prevIndex, nextIndex, ratio, prevValue, nextValue, resultValue) {
          var values = this._values,
            isQuantized = this._isQuantized;
          if (isQuantized) {
            loadQuatFromQuantized(values, prevIndex, prevValue);
            loadQuatFromQuantized(values, nextIndex, nextValue);
          } else {
            Quat.fromArray(prevValue, values, prevIndex * 4);
            Quat.fromArray(nextValue, values, nextIndex * 4);
          }
          Quat.slerp(resultValue, prevValue, nextValue, ratio);
        };
        return ExoticQuatTrackValues;
      }(ExoticVectorLikeTrackValues)) || _class11$1);
      var ExoticTrack = (_dec6$i = ccclass$e(CLASS_NAME_PREFIX_ANIM + "ExoticTrack"), _dec6$i(_class12 = (_class13$1 = function () {
        function ExoticTrack(times, values) {
          this.times = _initializer8$b && _initializer8$b();
          this.values = _initializer9$a && _initializer9$a();
          this.times = times;
          this.values = values;
        }
        var _proto6 = ExoticTrack.prototype;
        _proto6.toHashString = function toHashString() {
          var times = this.times,
            values = this.values;
          return "times: " + floatArrayToHashString(times) + "; values: " + values.toHashString();
        };
        return ExoticTrack;
      }(), (_initializer8$b = applyDecoratedInitializer(_class13$1.prototype, "times", [serializable$b], null), _initializer9$a = applyDecoratedInitializer(_class13$1.prototype, "values", [serializable$b], null)), _class13$1)) || _class12);
      (function () {
        function SplitInfo() {
          this._reset();
        }
        var _proto7 = SplitInfo.prototype;
        _proto7.calculate = function calculate(times, from, to) {
          this._reset();
          if (from > to) {
            return;
          }
          var nKeyframes = times.length;
          if (!nKeyframes) {
            return;
          }
          var firstTime = times[0];
          var lastTime = times[nKeyframes - 1];
          var fromIndex = 0;
          var fromRatio = 0.0;
          if (from < firstTime) ; else if (from >= lastTime) {
            fromIndex = nKeyframes - 1;
            fromRatio = 0.0;
          } else {
            var _binarySearchRatio = binarySearchRatio(times, from);
            fromIndex = _binarySearchRatio.index;
            fromRatio = _binarySearchRatio.ratio;
          }
          var toIndex = 0;
          var toRatio = 0.0;
          if (to < firstTime) ; else if (to >= lastTime) {
            toIndex = nKeyframes - 1;
            toRatio = 0.0;
          } else {
            var _binarySearchRatio2 = binarySearchRatio(times, to);
            toIndex = _binarySearchRatio2.index;
            toRatio = _binarySearchRatio2.ratio;
          }
          assertIsTrue(toIndex >= fromIndex);
          var fromJust = !fromRatio;
          var toJust = !toRatio;
          if (fromIndex === toIndex && fromRatio === toRatio) {
            if (!fromJust) {
              this.preLerpIndex = fromIndex;
              this.preLerpRatio = fromRatio;
            } else {
              this.directKeyframesBegin = fromIndex;
              this.directKeyframesEnd = fromIndex + 1;
            }
            return;
          }
          if (!fromJust) {
            this.preLerpIndex = fromIndex;
            this.preLerpRatio = fromRatio;
          }
          this.directKeyframesBegin = fromJust ? fromIndex : fromIndex + 1;
          this.directKeyframesEnd = toIndex + 1;
          if (!toJust) {
            this.postLerpIndex = toIndex;
            this.postLerpRatio = toRatio;
          }
        };
        _proto7._reset = function _reset() {
          this.preLerpIndex = -1;
          this.preLerpRatio = 0.0;
          this.directKeyframesBegin = 0;
          this.directKeyframesEnd = 0;
          this.postLerpIndex = -1;
          this.postLerpRatio = 0.0;
        };
        _createClass(SplitInfo, [{
          key: "keyframesCount",
          get: function get() {
            var preLerpIndex = this.preLerpIndex,
              directKeyframesBegin = this.directKeyframesBegin,
              directKeyframesEnd = this.directKeyframesEnd,
              postLerpIndex = this.postLerpIndex;
            return 0 + (preLerpIndex < 0 ? 0 : 1) + (directKeyframesEnd - directKeyframesBegin) + (postLerpIndex < 0 ? 0 : 1);
          }
        }]);
        return SplitInfo;
      })();
      function binarySearchRatio(values, value) {
        var nValues = values.length;
        assertIsTrue(values.length !== 0);
        var resultIndex = 0;
        var resultRatio = 0.0;
        var index0 = binarySearchEpsilon(values, value);
        if (index0 >= 0) {
          resultIndex = index0;
        } else {
          var iNext = ~index0;
          assertIsTrue(iNext !== 0 && iNext !== nValues && nValues > 1);
          var iPrev = iNext - 1;
          resultIndex = iPrev;
          var next = values[iNext];
          var prev = values[iPrev];
          resultRatio = (value - prev) / (next - prev);
        }
        return {
          index: resultIndex,
          ratio: resultRatio
        };
      }
      var ExoticTrsAnimationEvaluator = function () {
        function ExoticTrsAnimationEvaluator(nodeAnimations, binder) {
          this._nodeEvaluations = void 0;
          this._nodeEvaluations = nodeAnimations.map(function (nodeAnimation) {
            return nodeAnimation.createEvaluator(binder);
          });
        }
        var _proto8 = ExoticTrsAnimationEvaluator.prototype;
        _proto8.evaluate = function evaluate(time) {
          this._nodeEvaluations.forEach(function (nodeEvaluator) {
            nodeEvaluator.evaluate(time);
          });
        };
        return ExoticTrsAnimationEvaluator;
      }();
      var ExoticNodeAnimationEvaluator = function () {
        function ExoticNodeAnimationEvaluator(path, position, rotation, scale, binder) {
          this._position = null;
          this._rotation = null;
          this._scale = null;
          if (position) {
            this._position = createExoticTrackEvaluationRecord(position.times, position.values, Vec3, path, 'position', binder);
          }
          if (rotation) {
            this._rotation = createExoticTrackEvaluationRecord(rotation.times, rotation.values, Quat, path, 'rotation', binder);
          }
          if (scale) {
            this._scale = createExoticTrackEvaluationRecord(scale.times, scale.values, Vec3, path, 'scale', binder);
          }
        }
        var _proto9 = ExoticNodeAnimationEvaluator.prototype;
        _proto9.evaluate = function evaluate(time) {
          if (this._position) {
            var _value = this._position.evaluator.evaluate(time);
            this._position.runtimeBinding.setValue(_value);
          }
          if (this._rotation) {
            var _value2 = this._rotation.evaluator.evaluate(time);
            this._rotation.runtimeBinding.setValue(_value2);
          }
          if (this._scale) {
            var _value3 = this._scale.evaluator.evaluate(time);
            this._scale.runtimeBinding.setValue(_value3);
          }
        };
        return ExoticNodeAnimationEvaluator;
      }();
      var ExoticTrackEvaluator = function () {
        function ExoticTrackEvaluator(times, values, ValueConstructor) {
          this._times = void 0;
          this._inputSampleResultCache = {
            just: false,
            index: -1,
            nextIndex: -1,
            ratio: 0.0
          };
          this._values = void 0;
          this._prevValue = void 0;
          this._nextValue = void 0;
          this._resultValue = void 0;
          this._times = times;
          this._values = values;
          this._prevValue = new ValueConstructor();
          this._nextValue = new ValueConstructor();
          this._resultValue = new ValueConstructor();
        }
        var _proto10 = ExoticTrackEvaluator.prototype;
        _proto10.evaluate = function evaluate(time) {
          var times = this._times,
            values = this._values,
            resultValue = this._resultValue;
          var nFrames = times.length;
          if (nFrames === 0) {
            return resultValue;
          }
          var inputSampleResult = sampleInput(times, time, this._inputSampleResultCache);
          if (inputSampleResult.just) {
            values.get(inputSampleResult.index, resultValue);
          } else {
            values.lerp(inputSampleResult.index, inputSampleResult.nextIndex, inputSampleResult.ratio, this._prevValue, this._nextValue, resultValue);
          }
          return resultValue;
        };
        return ExoticTrackEvaluator;
      }();
      var ExoticTrsAGEvaluation = function () {
        function ExoticTrsAGEvaluation(nodeAnimations, context) {
          this._nodeEvaluations = void 0;
          this._nodeEvaluations = nodeAnimations.map(function (nodeAnimation) {
            return nodeAnimation.createEvaluatorForAnimationGraph(context);
          }).filter(function (x) {
            return !!x;
          });
        }
        var _proto11 = ExoticTrsAGEvaluation.prototype;
        _proto11.destroy = function destroy() {
          var nodeEvaluations = this._nodeEvaluations;
          var nNodeEvaluations = nodeEvaluations.length;
          for (var iNodeEvaluation = 0; iNodeEvaluation < nNodeEvaluations; ++iNodeEvaluation) {
            nodeEvaluations[iNodeEvaluation].destroy();
          }
        };
        _proto11.evaluate = function evaluate(time, pose) {
          var nodeEvaluations = this._nodeEvaluations;
          var nNodeEvaluations = nodeEvaluations.length;
          for (var iNodeEvaluation = 0; iNodeEvaluation < nNodeEvaluations; ++iNodeEvaluation) {
            nodeEvaluations[iNodeEvaluation].evaluate(time, pose);
          }
        };
        return ExoticTrsAGEvaluation;
      }();
      var ExoticNodeAnimationAGEvaluation = function () {
        function ExoticNodeAnimationAGEvaluation(transformHandle, position, rotation, scale) {
          this._position = null;
          this._rotation = null;
          this._scale = null;
          this._transformHandle = void 0;
          this._transformHandle = transformHandle;
          if (position) {
            this._position = new ExoticTrackEvaluator(position.times, position.values, Vec3);
          }
          if (rotation) {
            this._rotation = new ExoticTrackEvaluator(rotation.times, rotation.values, Quat);
          }
          if (scale) {
            this._scale = new ExoticTrackEvaluator(scale.times, scale.values, Vec3);
          }
        }
        var _proto12 = ExoticNodeAnimationAGEvaluation.prototype;
        _proto12.destroy = function destroy() {
          this._transformHandle.destroy();
        };
        _proto12.evaluate = function evaluate(time, pose) {
          var transformIndex = this._transformHandle.index,
            position = this._position,
            rotation = this._rotation,
            scale = this._scale;
          var poseTransforms = pose.transforms;
          if (position) {
            var _value4 = position.evaluate(time);
            poseTransforms.setPosition(transformIndex, _value4);
          }
          if (rotation) {
            var rotationAbs = rotation.evaluate(time);
            poseTransforms.setRotation(transformIndex, rotationAbs);
          }
          if (scale) {
            var _value5 = scale.evaluate(time);
            poseTransforms.setScale(transformIndex, _value5);
          }
        };
        return ExoticNodeAnimationAGEvaluation;
      }();
      function sampleInput(values, time, result) {
        var nFrames = values.length;
        assertIsTrue(nFrames !== 0);
        var firstTime = values[0];
        var lastTime = values[nFrames - 1];
        if (time < firstTime) {
          result.just = true;
          result.index = 0;
        } else if (time > lastTime) {
          result.just = true;
          result.index = nFrames - 1;
        } else {
          var _index2 = binarySearchEpsilon(values, time);
          if (_index2 >= 0) {
            result.just = true;
            result.index = _index2;
          } else {
            var _nextIndex = ~_index2;
            assertIsTrue(_nextIndex !== 0 && _nextIndex !== nFrames && nFrames > 1);
            var _prevIndex = _nextIndex - 1;
            var prevTime = values[_prevIndex];
            var nextTime = values[_nextIndex];
            var _ratio = (time - values[_prevIndex]) / (nextTime - prevTime);
            result.just = false;
            result.index = _prevIndex;
            result.nextIndex = _nextIndex;
            result.ratio = _ratio;
          }
        }
        return result;
      }
      var QUANTIZATION_TYPE_TO_ARRAY_VIEW_CONSTRUCTOR_MAP = {
        uint8: Uint8Array,
        uint16: Uint16Array
      };
      var FloatPrecision;
      (function (FloatPrecision) {
        FloatPrecision[FloatPrecision["FLOAT_32"] = 0] = "FLOAT_32";
        FloatPrecision[FloatPrecision["FLOAT_64"] = 1] = "FLOAT_64";
      })(FloatPrecision || (FloatPrecision = {}));
      function getFloatArrayPrecision(array) {
        switch (array.BYTES_PER_ELEMENT) {
          default:
            assertIsTrue(false);
          case 4:
            return FloatPrecision.FLOAT_32;
          case 8:
            return FloatPrecision.FLOAT_64;
        }
      }
      var QuantizedFloatArray = (_dec7$d = ccclass$e(CLASS_NAME_PREFIX_ANIM + "QuantizedFloatArray"), _dec7$d(_class20 = (_class21 = function () {
        function QuantizedFloatArray(originalPrecision, values, extent, min) {
          if (min === void 0) {
            min = 0.0;
          }
          this.originalPrecision = _initializer10$9 && _initializer10$9();
          this.min = _initializer11$9 && _initializer11$9();
          this.extent = _initializer12$7 && _initializer12$7();
          this.values = _initializer13$6 && _initializer13$6();
          this.originalPrecision = originalPrecision;
          this.values = values;
          this.extent = extent;
          this.min = min;
        }
        var _proto13 = QuantizedFloatArray.prototype;
        _proto13.toHashString = function toHashString() {
          var originalPrecision = this.originalPrecision,
            min = this.min,
            extent = this.extent,
            values = this.values;
          return originalPrecision + " " + floatToHashString(min) + " " + floatToHashString(extent) + " " + values.join(' ');
        };
        _createClass(QuantizedFloatArray, [{
          key: "quantizationType",
          get: function get() {
            switch (this.values.BYTES_PER_ELEMENT) {
              default:
              case 1:
                return 'uint8';
              case 2:
                return 'uint16';
            }
          }
        }]);
        return QuantizedFloatArray;
      }(), (_initializer10$9 = applyDecoratedInitializer(_class21.prototype, "originalPrecision", [serializable$b], null), _initializer11$9 = applyDecoratedInitializer(_class21.prototype, "min", [serializable$b], null), _initializer12$7 = applyDecoratedInitializer(_class21.prototype, "extent", [serializable$b], null), _initializer13$6 = applyDecoratedInitializer(_class21.prototype, "values", [serializable$b], null)), _class21)) || _class20);
      function _quantize(values, type) {
        var TypedArrayViewConstructor = QUANTIZATION_TYPE_TO_ARRAY_VIEW_CONSTRUCTOR_MAP[type];
        var MAX = 1 << TypedArrayViewConstructor.BYTES_PER_ELEMENT;
        var min = Number.POSITIVE_INFINITY;
        var max = Number.NEGATIVE_INFINITY;
        values.forEach(function (value) {
          min = Math.min(value, min);
          max = Math.max(value, max);
        });
        var extent = max - min;
        var normalized = TypedArrayViewConstructor.from(values, function (value) {
          return (value - min) / extent * MAX;
        });
        return new QuantizedFloatArray(getFloatArrayPrecision(values), normalized, extent, min);
      }
      function indexQuantized(quantized, index) {
        var quantizedValue = quantized.values[index];
        var MAX_VALUE = 1 << quantized.values.BYTES_PER_ELEMENT;
        return quantizedValue / MAX_VALUE * quantized.extent + quantized.min;
      }
      function createExoticTrackEvaluationRecord(times, values, ValueConstructor, path, property, binder) {
        var trackBinding = new TrackBinding();
        trackBinding.path = new TrackPath().toHierarchy(path).toProperty(property);
        var runtimeBinding = binder(trackBinding);
        if (!runtimeBinding) {
          return null;
        }
        var evaluator = new ExoticTrackEvaluator(times, values, ValueConstructor);
        return {
          runtimeBinding: runtimeBinding,
          evaluator: evaluator
        };
      }
      function loadVec3FromQuantized(values, index, out) {
        Vec3.set(out, indexQuantized(values, 3 * index + 0), indexQuantized(values, 3 * index + 1), indexQuantized(values, 3 * index + 2));
      }
      function loadQuatFromQuantized(values, index, out) {
        Quat.set(out, indexQuantized(values, 4 * index + 0), indexQuantized(values, 4 * index + 1), indexQuantized(values, 4 * index + 2), indexQuantized(values, 4 * index + 3));
      }

      var _dec$1k, _class$1i, _class2$1d, _initializer$15, _initializer2$V;
      var AuxiliaryCurveEntry = (_dec$1k = ccclass$n(CLASS_NAME_PREFIX_ANIM + "AuxiliaryCurveEntry"), _dec$1k(_class$1i = (_class2$1d = function AuxiliaryCurveEntry() {
        this.name = _initializer$15 && _initializer$15();
        this.curve = _initializer2$V && _initializer2$V();
      }, (_initializer$15 = applyDecoratedInitializer(_class2$1d.prototype, "name", [serializable$j], function () {
        return '';
      }), _initializer2$V = applyDecoratedInitializer(_class2$1d.prototype, "curve", [serializable$j], function () {
        return new RealCurve();
      })), _class2$1d)) || _class$1i);

      var _dec$1j, _class$1h, _class2$1c, _initializer$14, _initializer2$U, _initializer3$B, _initializer4$q, _initializer5$i, _initializer6$c, _initializer7$b, _initializer8$a, _initializer9$9, _initializer10$8, _initializer11$8, _initializer12$6, _class3$p, _dec2$1a, _class4$d, _class5$f, _initializer13$5, _initializer14$4;
      var searchForRootBonePathSymbol = Symbol('SearchForRootBonePath');
      var exoticAnimationTag = Symbol('ExoticAnimation');
      var embeddedPlayerCountTag = Symbol('[[EmbeddedPlayerCount]]');
      var getEmbeddedPlayersTag = Symbol('[[GetEmbeddedPlayers]]');
      var addEmbeddedPlayerTag = Symbol('[[AddEmbeddedPlayer]]');
      var removeEmbeddedPlayerTag = Symbol('[[RemoveEmbeddedPlayer]]');
      var clearEmbeddedPlayersTag = Symbol('[[ClearEmbeddedPlayers]]');
      var additiveSettingsTag = Symbol('[[Additive Settings]]');
      var AnimationClip = exports('aj', (_dec$1j = ccclass$n('cc.AnimationClip'), _dec$1j(_class$1h = (_class2$1c = (_class3$p = function (_Asset) {
        _inheritsLoose(AnimationClip, _Asset);
        function AnimationClip() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Asset.call.apply(_Asset, [this].concat(args)) || this;
          _this.sample = _initializer$14 && _initializer$14();
          _this.speed = _initializer2$U && _initializer2$U();
          _this.wrapMode = _initializer3$B && _initializer3$B();
          _this.enableTrsBlending = _initializer4$q && _initializer4$q();
          _this._duration = _initializer5$i && _initializer5$i();
          _this._hash = _initializer6$c && _initializer6$c();
          _this.frameRate = 0;
          _this._tracks = _initializer7$b && _initializer7$b();
          _this._exoticAnimation = _initializer8$a && _initializer8$a();
          _this._legacyData = undefined;
          _this._legacyDataDirty = false;
          _this._events = _initializer9$9 && _initializer9$9();
          _this._embeddedPlayers = _initializer10$8 && _initializer10$8();
          _this._additiveSettings = _initializer11$8 && _initializer11$8();
          _this._auxiliaryCurveEntries = _initializer12$6 && _initializer12$6();
          _this._runtimeEvents = {
            ratios: [],
            eventGroups: []
          };
          return _this;
        }
        AnimationClip.createWithSpriteFrames = function createWithSpriteFrames(spriteFrames, sample) {
          var clip = new AnimationClip();
          clip.sample = sample || clip.sample;
          clip.duration = spriteFrames.length / clip.sample;
          var step = 1 / clip.sample;
          var track = new ObjectTrack();
          track.path = new TrackPath().toComponent('cc.Sprite').toProperty('spriteFrame');
          var curve = track.channels()[0].curve;
          curve.assignSorted(spriteFrames.map(function (spriteFrame, index) {
            return [step * index, spriteFrame];
          }));
          clip.addTrack(track);
          return clip;
        };
        var _proto = AnimationClip.prototype;
        _proto.onLoaded = function onLoaded() {
          this.frameRate = this.sample;
          this.events = this._events;
        };
        _proto.range = function range() {
          var range = {
            min: Infinity,
            max: -Infinity
          };
          var tracks = this._tracks;
          var nTracks = tracks.length;
          for (var iTrack = 0; iTrack < nTracks; ++iTrack) {
            var track = tracks[iTrack];
            var trackRange = track.range();
            range.min = Math.min(range.min, trackRange.min);
            range.max = Math.max(range.max, trackRange.max);
          }
          return range;
        };
        _proto.getTrack = function getTrack(index) {
          return this._tracks[index];
        };
        _proto.addTrack = function addTrack(track) {
          var index = this._tracks.length;
          this._tracks.push(track);
          return index;
        };
        _proto.removeTrack = function removeTrack(index) {
          this._tracks.splice(index, 1);
        };
        _proto.clearTracks = function clearTracks() {
          this._tracks.length = 0;
        };
        _proto.containsAnyEvent = function containsAnyEvent() {
          return this._events.length !== 0;
        };
        _proto.createEventEvaluator = function createEventEvaluator(targetNode) {
          return new EventEvaluator(targetNode, this._runtimeEvents.ratios, this._runtimeEvents.eventGroups, this.wrapMode);
        };
        _proto.containsAnyEmbeddedPlayer = function containsAnyEmbeddedPlayer() {
          return this._embeddedPlayers.length !== 0;
        };
        _proto.createEmbeddedPlayerEvaluator = function createEmbeddedPlayerEvaluator(targetNode) {
          return new EmbeddedPlayerEvaluation(this._embeddedPlayers, targetNode);
        };
        _proto.createEvaluator = function createEvaluator(context) {
          var _this2 = this;
          var target = context.target;
          var binder = function binder(binding) {
            if (context.mask && binding.isMaskedOff(context.mask)) {
              return undefined;
            }
            var trackTarget = binding.createRuntimeBinding(target, _this2.enableTrsBlending ? context.pose : undefined, false);
            if (!trackTarget) {
              warnID(3937, _this2.name, context.target instanceof Node$1 ? context.target.name : context.target);
            }
            return trackTarget !== null && trackTarget !== void 0 ? trackTarget : undefined;
          };
          return this._createEvalWithBinder(target, binder, context.rootMotion);
        };
        _proto.destroy = function destroy() {
          var _cclegacy$director$ro;
          if ((_cclegacy$director$ro = legacyCC.director.root) !== null && _cclegacy$director$ro !== void 0 && _cclegacy$director$ro.dataPoolManager) {
            legacyCC.director.root.dataPoolManager.releaseAnimationClip(this);
          }
          SkelAnimDataHub.destroy(this);
          return _Asset.prototype.destroy.call(this);
        };
        _proto[BAKE_SKELETON_CURVE_SYMBOL] = function (start, samples, frames) {
          var step = 1.0 / samples;
          var animatedJoints = this._collectAnimatedJoints();
          var nAnimatedJoints = animatedJoints.length;
          var jointsBakeInfo = {};
          for (var iAnimatedJoint = 0; iAnimatedJoint < nAnimatedJoints; ++iAnimatedJoint) {
            var joint = animatedJoints[iAnimatedJoint];
            jointsBakeInfo[joint] = {
              transforms: Array.from({
                length: frames
              }, function () {
                return new Mat4();
              })
            };
          }
          var skeletonFrames = animatedJoints.reduce(function (result, joint) {
            result[joint] = new BoneGlobalTransform();
            return result;
          }, {});
          for (var _joint in skeletonFrames) {
            var skeletonFrame = skeletonFrames[_joint];
            var parentJoint = _joint.lastIndexOf('/');
            if (parentJoint >= 0) {
              var parentJointName = _joint.substring(0, parentJoint);
              var parentJointFrame = skeletonFrames[parentJointName];
              if (parentJointFrame) {
                skeletonFrame.parent = parentJointFrame;
              }
            }
          }
          var binder = function binder(binding) {
            var trsPath = binding.parseTrsPath();
            if (!trsPath) {
              return undefined;
            }
            var jointFrame = skeletonFrames[trsPath.node];
            if (!jointFrame) {
              return undefined;
            }
            return createBoneTransformBinding(jointFrame, trsPath.property);
          };
          var evaluator = this._createEvalWithBinder(undefined, binder, undefined);
          for (var iFrame = 0; iFrame < frames; ++iFrame) {
            var time = start + step * iFrame;
            evaluator.evaluate(time);
            for (var _iAnimatedJoint = 0; _iAnimatedJoint < nAnimatedJoints; ++_iAnimatedJoint) {
              var _joint2 = animatedJoints[_iAnimatedJoint];
              Mat4.copy(jointsBakeInfo[_joint2].transforms[iFrame], skeletonFrames[_joint2].globalTransform);
            }
            for (var _iAnimatedJoint2 = 0; _iAnimatedJoint2 < nAnimatedJoints; ++_iAnimatedJoint2) {
              var _joint3 = animatedJoints[_iAnimatedJoint2];
              skeletonFrames[_joint3].invalidate();
            }
          }
          return {
            samples: samples,
            frames: frames,
            joints: jointsBakeInfo
          };
        };
        _proto.upgradeUntypedTracks = function upgradeUntypedTracks(refine) {
          var newTracks = [];
          var removals = [];
          var tracks = this._tracks;
          var nTracks = tracks.length;
          for (var iTrack = 0; iTrack < nTracks; ++iTrack) {
            var track = tracks[iTrack];
            if (!(track instanceof UntypedTrack)) {
              continue;
            }
            var newTrack = track.upgrade(refine);
            if (newTrack) {
              newTracks.push(newTrack);
              removals.push(track);
            }
          }
          var nRemovalTracks = removals.length;
          for (var iRemovalTrack = 0; iRemovalTrack < nRemovalTracks; ++iRemovalTrack) {
            remove(tracks, removals[iRemovalTrack]);
          }
          tracks.push.apply(tracks, newTracks);
        };
        _proto[searchForRootBonePathSymbol] = function () {
          return this._searchForRootBonePath();
        };
        _proto.getPropertyCurves = function getPropertyCurves() {
          return this._getLegacyData().getPropertyCurves();
        };
        _proto.updateEventDatas = function updateEventDatas() {
          this.events = this._events;
        };
        _proto.hasEvents = function hasEvents() {
          return this.events.length !== 0;
        };
        _proto.syncLegacyData = function syncLegacyData() {
          if (this._legacyData) {
            this._fromLegacy(this._legacyData);
            this._legacyData = undefined;
          }
        };
        _proto[getEmbeddedPlayersTag] = function () {
          return this._embeddedPlayers;
        };
        _proto[addEmbeddedPlayerTag] = function (embeddedPlayer) {
          this._embeddedPlayers.push(embeddedPlayer);
        };
        _proto[removeEmbeddedPlayerTag] = function (embeddedPlayer) {
          var iEmbeddedPlayer = this._embeddedPlayers.indexOf(embeddedPlayer);
          if (iEmbeddedPlayer >= 0) {
            this._embeddedPlayers.splice(iEmbeddedPlayer, 1);
          }
        };
        _proto[clearEmbeddedPlayersTag] = function () {
          this._embeddedPlayers.length = 0;
        };
        _proto.getAuxiliaryCurveNames_experimental = function getAuxiliaryCurveNames_experimental() {
          return this._auxiliaryCurveEntries.map(function (entry) {
            return entry.name;
          });
        };
        _proto.hasAuxiliaryCurve_experimental = function hasAuxiliaryCurve_experimental(name) {
          return !!this._findAuxiliaryCurveEntry(name);
        };
        _proto.addAuxiliaryCurve_experimental = function addAuxiliaryCurve_experimental(name) {
          var entry = this._findAuxiliaryCurveEntry(name);
          if (!entry) {
            entry = new AuxiliaryCurveEntry();
            entry.name = name;
            this._auxiliaryCurveEntries.push(entry);
          }
          return entry.curve;
        };
        _proto.getAuxiliaryCurve_experimental = function getAuxiliaryCurve_experimental(name) {
          var entry = this._findAuxiliaryCurveEntry(name);
          assertIsTrue(entry);
          return entry.curve;
        };
        _proto.renameAuxiliaryCurve_experimental = function renameAuxiliaryCurve_experimental(name, newName) {
          var entry = this._findAuxiliaryCurveEntry(name);
          if (entry) {
            entry.name = newName;
          }
        };
        _proto.removeAuxiliaryCurve_experimental = function removeAuxiliaryCurve_experimental(name) {
          removeIf(this._auxiliaryCurveEntries, function (entry) {
            return entry.name === name;
          });
        };
        _proto._trySyncLegacyData = function _trySyncLegacyData() {
          if (this._legacyDataDirty) {
            this._legacyDataDirty = false;
            this.syncLegacyData();
          }
        };
        _proto._createEvalWithBinder = function _createEvalWithBinder(target, binder, rootMotionOptions) {
          if (this._legacyDataDirty) {
            this._legacyDataDirty = false;
            this.syncLegacyData();
          }
          var rootMotionTrackExcludes = [];
          var rootMotionEvaluation;
          if (rootMotionOptions) {
            rootMotionEvaluation = this._createRootMotionEvaluation(target, rootMotionOptions, rootMotionTrackExcludes);
          }
          var trackEvalStatues = [];
          var exoticAnimationEvaluator;
          var tracks = this._tracks;
          var nTracks = tracks.length;
          for (var iTrack = 0; iTrack < nTracks; ++iTrack) {
            var track = tracks[iTrack];
            if (rootMotionTrackExcludes.includes(track)) {
              continue;
            }
            if (Array.from(track.channels()).every(function (_ref) {
              var curve = _ref.curve;
              return curve.keyFramesCount === 0;
            })) {
              continue;
            }
            var runtimeBinding = binder(track[trackBindingTag]);
            if (!runtimeBinding) {
              continue;
            }
            var trackEval = void 0;
            if (!(track instanceof UntypedTrack)) {
              trackEval = track[createEvalSymbol]();
            } else {
              if (!runtimeBinding.getValue) {
                errorID(3930);
                continue;
              }
              var hintValue = runtimeBinding.getValue();
              trackEval = track.createLegacyEval(hintValue);
            }
            trackEvalStatues.push(new TrackEvalStatus(runtimeBinding, trackEval));
          }
          if (this._exoticAnimation) {
            exoticAnimationEvaluator = this._exoticAnimation.createEvaluator(binder);
          }
          var evaluation = new AnimationClipEvaluation(trackEvalStatues, exoticAnimationEvaluator, rootMotionEvaluation);
          return evaluation;
        };
        _proto._createRootMotionEvaluation = function _createRootMotionEvaluation(target, rootMotionOptions, rootMotionTrackExcludes) {
          if (!(target instanceof Node$1)) {
            errorID(3920);
            return undefined;
          }
          var rootBonePath = this._searchForRootBonePath();
          if (!rootBonePath) {
            warnID(3923);
            return undefined;
          }
          var rootBone = target.getChildByPath(rootBonePath);
          if (!rootBone) {
            warnID(3924);
            return undefined;
          }
          var boneTransform = new BoneTransform();
          var rootMotionsTrackEvaluations = [];
          var tracks = this._tracks;
          var nTracks = tracks.length;
          for (var iTrack = 0; iTrack < nTracks; ++iTrack) {
            var track = tracks[iTrack];
            var trackBinding = track[trackBindingTag];
            var trsPath = trackBinding.parseTrsPath();
            if (!trsPath) {
              continue;
            }
            var bonePath = trsPath.node;
            if (bonePath !== rootBonePath) {
              continue;
            }
            rootMotionTrackExcludes.push(track);
            var property = trsPath.property;
            var runtimeBinding = createBoneTransformBinding(boneTransform, property);
            if (!runtimeBinding) {
              continue;
            }
            var trackEval = track[createEvalSymbol]();
            rootMotionsTrackEvaluations.push(new TrackEvalStatus(runtimeBinding, trackEval));
          }
          var rootMotionEvaluation = new RootMotionEvaluation(rootBone, this._duration, boneTransform, rootMotionsTrackEvaluations);
          return rootMotionEvaluation;
        };
        _proto._searchForRootBonePath = function _searchForRootBonePath() {
          var paths = this._tracks.map(function (track) {
            var trsPath = track[trackBindingTag].parseTrsPath();
            if (trsPath) {
              var nodePath = trsPath.node;
              return {
                path: nodePath,
                rank: nodePath.split('/').length
              };
            } else {
              return {
                path: '',
                rank: 0
              };
            }
          });
          paths.sort(function (a, b) {
            return a.rank - b.rank;
          });
          var iNonEmptyPath = paths.findIndex(function (p) {
            return p.rank !== 0;
          });
          if (iNonEmptyPath < 0) {
            return '';
          }
          var nPaths = paths.length;
          var firstPath = paths[iNonEmptyPath];
          var highestPathsAreSame = true;
          for (var iPath = iNonEmptyPath + 1; iPath < nPaths; ++iPath) {
            var path = paths[iPath];
            if (path.rank !== firstPath.rank) {
              break;
            }
            if (path.path !== firstPath.path) {
              highestPathsAreSame = false;
              break;
            }
          }
          return highestPathsAreSame ? firstPath.path : '';
        };
        _proto._getLegacyData = function _getLegacyData() {
          if (!this._legacyData) {
            this._legacyData = this._toLegacy();
          }
          return this._legacyData;
        };
        _proto._toLegacy = function _toLegacy() {
          var keys = [];
          var legacyCurves = [];
          var commonTargets = [];
          var legacyClipData = new AnimationClipLegacyData(this._duration);
          legacyClipData.keys = keys;
          legacyClipData.curves = legacyCurves;
          legacyClipData.commonTargets = commonTargets;
          return legacyClipData;
        };
        _proto._fromLegacy = function _fromLegacy(legacyData) {
          var newTracks = legacyData.toTracks();
          var nNewTracks = newTracks.length;
          for (var iNewTrack = 0; iNewTrack < nNewTracks; ++iNewTrack) {
            this.addTrack(newTracks[iNewTrack]);
          }
        };
        _proto._collectAnimatedJoints = function _collectAnimatedJoints() {
          var joints = new Set();
          var tracks = this._tracks;
          var nTracks = tracks.length;
          for (var iTrack = 0; iTrack < nTracks; ++iTrack) {
            var track = tracks[iTrack];
            var trsPath = track[trackBindingTag].parseTrsPath();
            if (trsPath) {
              joints.add(trsPath.node);
            }
          }
          if (this._exoticAnimation) {
            var animatedJoints = this._exoticAnimation.collectAnimatedJoints();
            var nAnimatedJoints = animatedJoints.length;
            for (var iAnimatedJoint = 0; iAnimatedJoint < nAnimatedJoints; ++iAnimatedJoint) {
              joints.add(animatedJoints[iAnimatedJoint]);
            }
          }
          return Array.from(joints);
        };
        _proto._findAuxiliaryCurveEntry = function _findAuxiliaryCurveEntry(name) {
          return this._auxiliaryCurveEntries.find(function (entry) {
            return entry.name === name;
          });
        };
        _createClass(AnimationClip, [{
          key: "duration",
          get: function get() {
            return this._duration;
          },
          set: function set(value) {
            this._duration = value;
          }
        }, {
          key: "tracksCount",
          get: function get() {
            return this._tracks.length;
          }
        }, {
          key: "tracks",
          get: function get() {
            return this._tracks;
          }
        }, {
          key: "hash",
          get: function get() {
            var _this$_exoticAnimatio, _this$_exoticAnimatio2;
            if (this._hash) {
              return this._hash;
            }
            var hashString = "Exotic:" + ((_this$_exoticAnimatio = (_this$_exoticAnimatio2 = this._exoticAnimation) === null || _this$_exoticAnimatio2 === void 0 ? void 0 : _this$_exoticAnimatio2.toHashString()) !== null && _this$_exoticAnimatio !== void 0 ? _this$_exoticAnimatio : '');
            return this._hash = murmurhash2_32_gc(hashString, 666);
          }
        }, {
          key: "events",
          get: function get() {
            return this._events;
          },
          set: function set(value) {
            var _this3 = this;
            this._events = value;
            var ratios = [];
            var eventGroups = [];
            var events = this.events.sort(function (a, b) {
              return a.frame - b.frame;
            });
            var nEvents = events.length;
            var _loop = function _loop() {
              var eventData = events[iEvent];
              var ratio = eventData.frame / _this3._duration;
              var i = ratios.findIndex(function (r) {
                return r === ratio;
              });
              if (i < 0) {
                i = ratios.length;
                ratios.push(ratio);
                eventGroups.push({
                  events: []
                });
              }
              eventGroups[i].events.push({
                functionName: eventData.func,
                parameters: eventData.params
              });
            };
            for (var iEvent = 0; iEvent < nEvents; ++iEvent) {
              _loop();
            }
            this._runtimeEvents = {
              ratios: ratios,
              eventGroups: eventGroups
            };
          }
        }, {
          key: exoticAnimationTag,
          get: function get() {
            return this._exoticAnimation;
          }
        }, {
          key: exoticAnimationTag,
          set: function set(value) {
            this._exoticAnimation = value;
          }
        }, {
          key: "isAdditive_experimental",
          get: function get() {
            return this._additiveSettings.enabled;
          }
        }, {
          key: additiveSettingsTag,
          get: function get() {
            return this._additiveSettings;
          }
        }, {
          key: "keys",
          get: function get() {
            return this._getLegacyData().keys;
          }
        }, {
          key: "keys",
          set: function set(value) {
            this._legacyDataDirty = true;
            this._getLegacyData().keys = value;
          }
        }, {
          key: "curves",
          get: function get() {
            this._legacyDataDirty = true;
            return this._getLegacyData().curves;
          }
        }, {
          key: "curves",
          set: function set(value) {
            this._getLegacyData().curves = value;
          }
        }, {
          key: "commonTargets",
          get: function get() {
            return this._getLegacyData().commonTargets;
          }
        }, {
          key: "commonTargets",
          set: function set(value) {
            this._legacyDataDirty = true;
            this._getLegacyData().commonTargets = value;
          }
        }, {
          key: "data",
          get: function get() {
            return this._getLegacyData().data;
          }
        }, {
          key: "eventGroups",
          get: function get() {
            return this._runtimeEvents.eventGroups;
          }
        }, {
          key: embeddedPlayerCountTag,
          get: function get() {
            return this._embeddedPlayers.length;
          }
        }, {
          key: "auxiliaryCurveCount_experimental",
          get: function get() {
            return this._auxiliaryCurveEntries.length;
          }
        }]);
        return AnimationClip;
      }(Asset), _class3$p.WrapMode = WrapMode, _class3$p), (_initializer$14 = applyDecoratedInitializer(_class2$1c.prototype, "sample", [serializable$j], function () {
        return 60;
      }), _initializer2$U = applyDecoratedInitializer(_class2$1c.prototype, "speed", [serializable$j], function () {
        return 1;
      }), _initializer3$B = applyDecoratedInitializer(_class2$1c.prototype, "wrapMode", [serializable$j], function () {
        return WrapMode.Normal;
      }), _initializer4$q = applyDecoratedInitializer(_class2$1c.prototype, "enableTrsBlending", [serializable$j], function () {
        return false;
      }), _initializer5$i = applyDecoratedInitializer(_class2$1c.prototype, "_duration", [serializable$j], function () {
        return 0;
      }), _initializer6$c = applyDecoratedInitializer(_class2$1c.prototype, "_hash", [serializable$j], function () {
        return 0;
      }), _initializer7$b = applyDecoratedInitializer(_class2$1c.prototype, "_tracks", [serializable$j], function () {
        return [];
      }), _initializer8$a = applyDecoratedInitializer(_class2$1c.prototype, "_exoticAnimation", [serializable$j], function () {
        return null;
      }), _initializer9$9 = applyDecoratedInitializer(_class2$1c.prototype, "_events", [serializable$j], function () {
        return [];
      }), _initializer10$8 = applyDecoratedInitializer(_class2$1c.prototype, "_embeddedPlayers", [serializable$j], function () {
        return [];
      }), _initializer11$8 = applyDecoratedInitializer(_class2$1c.prototype, "_additiveSettings", [serializable$j], function () {
        return new AdditiveSettings();
      }), _initializer12$6 = applyDecoratedInitializer(_class2$1c.prototype, "_auxiliaryCurveEntries", [serializable$j], function () {
        return [];
      })), _class2$1c)) || _class$1h));
      var AdditiveSettings = (_dec2$1a = ccclass$n('cc.AnimationClipAdditiveSettings'), _dec2$1a(_class4$d = (_class5$f = function AdditiveSettings() {
        this.enabled = _initializer13$5 && _initializer13$5();
        this.refClip = _initializer14$4 && _initializer14$4();
      }, (_initializer13$5 = applyDecoratedInitializer(_class5$f.prototype, "enabled", [serializable$j], function () {
        return false;
      }), _initializer14$4 = applyDecoratedInitializer(_class5$f.prototype, "refClip", [serializable$j], function () {
        return null;
      })), _class5$f)) || _class4$d);
      legacyCC.AnimationClip = AnimationClip;
      var TrackEvalStatus = function () {
        function TrackEvalStatus(binding, trackEval) {
          this._binding = void 0;
          this._trackEval = void 0;
          this._shouldEvaluateDefault = true;
          this._binding = binding;
          this._trackEval = trackEval;
          this._shouldEvaluateDefault = !!binding.getValue && trackEval.requiresDefault;
        }
        var _proto2 = TrackEvalStatus.prototype;
        _proto2.evaluate = function evaluate(time) {
          var binding = this._binding,
            trackEval = this._trackEval;
          var defaultValue = this._shouldEvaluateDefault ? binding.getValue() : undefined;
          var value = trackEval.evaluate(time, defaultValue);
          binding.setValue(value);
        };
        return TrackEvalStatus;
      }();
      var EmbeddedPlayerEvaluation = function () {
        function EmbeddedPlayerEvaluation(embeddedPlayers, rootNode) {
          this._embeddedPlayers = embeddedPlayers;
          this._embeddedPlayerEvaluationInfos = embeddedPlayers.map(function (embeddedPlayer) {
            var player = embeddedPlayer.playable;
            if (!player) {
              return null;
            }
            var instantiatedPlayer = player.instantiate(rootNode);
            if (!instantiatedPlayer) {
              return null;
            }
            return {
              instantiatedPlayer: instantiatedPlayer,
              entered: false,
              hostPauseTime: 0.0,
              lastIterations: 0
            };
          });
        }
        var _proto3 = EmbeddedPlayerEvaluation.prototype;
        _proto3.destroy = function destroy() {
          var embeddedPlayerEvaluationInfos = this._embeddedPlayerEvaluationInfos;
          var nEmbeddedPlayers = embeddedPlayerEvaluationInfos.length;
          for (var iEmbeddedPlayer = 0; iEmbeddedPlayer < nEmbeddedPlayers; ++iEmbeddedPlayer) {
            var _embeddedPlayerEvalua;
            (_embeddedPlayerEvalua = embeddedPlayerEvaluationInfos[iEmbeddedPlayer]) === null || _embeddedPlayerEvalua === void 0 ? void 0 : _embeddedPlayerEvalua.instantiatedPlayer.destroy();
          }
          this._embeddedPlayerEvaluationInfos.length = 0;
        };
        _proto3.evaluate = function evaluate(time, iterations) {
          assertIsTrue(Number.isInteger(iterations));
          var embeddedPlayers = this._embeddedPlayers,
            embeddedPlayerEvaluationInfos = this._embeddedPlayerEvaluationInfos;
          var nEmbeddedPlayers = embeddedPlayers.length;
          for (var iEmbeddedPlayer = 0; iEmbeddedPlayer < nEmbeddedPlayers; ++iEmbeddedPlayer) {
            var embeddedPlayerEvaluationInfo = embeddedPlayerEvaluationInfos[iEmbeddedPlayer];
            if (!embeddedPlayerEvaluationInfo) {
              continue;
            }
            var entered = embeddedPlayerEvaluationInfo.entered,
              instantiatedPlayer = embeddedPlayerEvaluationInfo.instantiatedPlayer,
              lastIterations = embeddedPlayerEvaluationInfo.lastIterations;
            var _embeddedPlayers$iEmb = embeddedPlayers[iEmbeddedPlayer],
              begin = _embeddedPlayers$iEmb.begin,
              end = _embeddedPlayers$iEmb.end;
            var withinEmbeddedPlayer = time >= begin && time <= end;
            if (withinEmbeddedPlayer) {
              if (!entered) {
                instantiatedPlayer.play();
                embeddedPlayerEvaluationInfo.entered = true;
              } else if (iterations !== lastIterations) {
                instantiatedPlayer.stop();
                instantiatedPlayer.play();
                embeddedPlayerEvaluationInfo.entered = true;
              }
            } else if (entered) {
              instantiatedPlayer.stop();
              embeddedPlayerEvaluationInfo.entered = false;
            }
            embeddedPlayerEvaluationInfo.lastIterations = iterations;
            if (embeddedPlayerEvaluationInfo.entered) {
              var playerTime = time - begin;
              embeddedPlayerEvaluationInfo.instantiatedPlayer.setTime(playerTime);
            }
          }
        };
        _proto3.notifyHostSpeedChanged = function notifyHostSpeedChanged(speed) {
          var embeddedPlayers = this._embeddedPlayers,
            embeddedPlayerEvaluationInfos = this._embeddedPlayerEvaluationInfos;
          var nEmbeddedPlayers = embeddedPlayers.length;
          for (var iEmbeddedPlayer = 0; iEmbeddedPlayer < nEmbeddedPlayers; ++iEmbeddedPlayer) {
            var embeddedPlayerEvaluationInfo = embeddedPlayerEvaluationInfos[iEmbeddedPlayer];
            if (!embeddedPlayerEvaluationInfo) {
              continue;
            }
            var instantiatedPlayer = embeddedPlayerEvaluationInfo.instantiatedPlayer;
            var reconciledSpeed = embeddedPlayers[iEmbeddedPlayer].reconciledSpeed;
            if (reconciledSpeed) {
              instantiatedPlayer.setSpeed(speed);
            }
          }
        };
        _proto3.notifyHostPlay = function notifyHostPlay(time) {
          var embeddedPlayers = this._embeddedPlayers,
            embeddedPlayerEvaluationInfos = this._embeddedPlayerEvaluationInfos;
          var nEmbeddedPlayers = embeddedPlayers.length;
          for (var iEmbeddedPlayer = 0; iEmbeddedPlayer < nEmbeddedPlayers; ++iEmbeddedPlayer) {
            var embeddedPlayerEvaluationInfo = embeddedPlayerEvaluationInfos[iEmbeddedPlayer];
            if (!embeddedPlayerEvaluationInfo) {
              continue;
            }
            var _embeddedPlayers$iEmb2 = embeddedPlayers[iEmbeddedPlayer],
              begin = _embeddedPlayers$iEmb2.begin,
              end = _embeddedPlayers$iEmb2.end;
            var instantiatedPlayer = embeddedPlayerEvaluationInfo.instantiatedPlayer,
              entered = embeddedPlayerEvaluationInfo.entered;
            if (entered) {
              var hostPauseTime = embeddedPlayerEvaluationInfo.hostPauseTime;
              if (instantiatedPlayer.randomAccess || approx(hostPauseTime, time, 1e-5)) {
                var startTime = clamp$1(time, begin, end);
                instantiatedPlayer.play();
                instantiatedPlayer.setTime(startTime - begin);
              } else {
                instantiatedPlayer.stop();
              }
            }
          }
        };
        _proto3.notifyHostPause = function notifyHostPause(time) {
          var embeddedPlayers = this._embeddedPlayers,
            embeddedPlayerEvaluationInfos = this._embeddedPlayerEvaluationInfos;
          var nEmbeddedPlayers = embeddedPlayers.length;
          for (var iEmbeddedPlayer = 0; iEmbeddedPlayer < nEmbeddedPlayers; ++iEmbeddedPlayer) {
            var embeddedPlayerEvaluationInfo = embeddedPlayerEvaluationInfos[iEmbeddedPlayer];
            if (!embeddedPlayerEvaluationInfo) {
              continue;
            }
            var instantiatedPlayer = embeddedPlayerEvaluationInfo.instantiatedPlayer,
              entered = embeddedPlayerEvaluationInfo.entered;
            if (entered) {
              instantiatedPlayer.pause();
              embeddedPlayerEvaluationInfo.hostPauseTime = time;
            }
          }
        };
        _proto3.notifyHostStop = function notifyHostStop() {
          var embeddedPlayers = this._embeddedPlayers,
            embeddedPlayerEvaluationInfos = this._embeddedPlayerEvaluationInfos;
          var nEmbeddedPlayers = embeddedPlayers.length;
          for (var iEmbeddedPlayer = 0; iEmbeddedPlayer < nEmbeddedPlayers; ++iEmbeddedPlayer) {
            var embeddedPlayerEvaluationInfo = embeddedPlayerEvaluationInfos[iEmbeddedPlayer];
            if (!embeddedPlayerEvaluationInfo) {
              continue;
            }
            var instantiatedPlayer = embeddedPlayerEvaluationInfo.instantiatedPlayer,
              entered = embeddedPlayerEvaluationInfo.entered;
            if (entered) {
              embeddedPlayerEvaluationInfo.entered = false;
              instantiatedPlayer.stop();
            }
          }
        };
        return EmbeddedPlayerEvaluation;
      }();
      var AnimationClipEvaluation = function () {
        function AnimationClipEvaluation(trackEvalStatuses, exoticAnimationEvaluator, rootMotionEvaluation) {
          this._exoticAnimationEvaluator = void 0;
          this._trackEvalStatues = [];
          this._rootMotionEvaluation = undefined;
          this._trackEvalStatues = trackEvalStatuses;
          this._exoticAnimationEvaluator = exoticAnimationEvaluator;
          this._rootMotionEvaluation = rootMotionEvaluation;
        }
        var _proto4 = AnimationClipEvaluation.prototype;
        _proto4.evaluate = function evaluate(time) {
          var trackEvalStatuses = this._trackEvalStatues,
            exoticAnimationEvaluator = this._exoticAnimationEvaluator;
          var nTrackEvalStatuses = trackEvalStatuses.length;
          for (var iTrackEvalStatus = 0; iTrackEvalStatus < nTrackEvalStatuses; ++iTrackEvalStatus) {
            trackEvalStatuses[iTrackEvalStatus].evaluate(time);
          }
          if (exoticAnimationEvaluator) {
            exoticAnimationEvaluator.evaluate(time);
          }
        };
        _proto4.evaluateRootMotion = function evaluateRootMotion(time, motionLength) {
          var rootMotionEvaluation = this._rootMotionEvaluation;
          if (rootMotionEvaluation) {
            rootMotionEvaluation.evaluate(time, motionLength);
          }
        };
        return AnimationClipEvaluation;
      }();
      var BoneTransform = function () {
        function BoneTransform() {
          this.position = new Vec3();
          this.scale = new Vec3(1.0, 1.0, 1.0);
          this.rotation = new Quat();
          this.eulerAngles = new Vec3();
        }
        var _proto5 = BoneTransform.prototype;
        _proto5.getTransform = function getTransform(out) {
          Mat4.fromRTS(out, this.rotation, this.position, this.scale);
        };
        return BoneTransform;
      }();
      var BoneGlobalTransform = function (_BoneTransform) {
        _inheritsLoose(BoneGlobalTransform, _BoneTransform);
        function BoneGlobalTransform() {
          var _this4;
          for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
            args[_key2] = arguments[_key2];
          }
          _this4 = _BoneTransform.call.apply(_BoneTransform, [this].concat(args)) || this;
          _this4.parent = null;
          _this4._dirty = true;
          _this4._transform = new Mat4();
          return _this4;
        }
        var _proto6 = BoneGlobalTransform.prototype;
        _proto6.invalidate = function invalidate() {
          this._dirty = true;
        };
        _createClass(BoneGlobalTransform, [{
          key: "globalTransform",
          get: function get() {
            var transform = this._transform;
            if (this._dirty) {
              this._dirty = false;
              Mat4.fromRTS(transform, this.rotation, this.position, this.scale);
              if (this.parent) {
                Mat4.multiply(transform, this.parent.globalTransform, transform);
              }
            }
            return this._transform;
          }
        }]);
        return BoneGlobalTransform;
      }(BoneTransform);
      var motionTransformCache = new Mat4();
      var RootMotionEvaluation = function () {
        function RootMotionEvaluation(_rootBone, _duration, _boneTransform, _trackEvalStatuses) {
          this._initialTransformCache = new Mat4();
          this._clipEndTransformCache = new Mat4();
          this._startTransformCache = new Mat4();
          this._endTransformCache = new Mat4();
          this._motionTransformCache = new Mat4();
          this._translationMotionCache = new Vec3();
          this._rotationMotionCache = new Quat();
          this._scaleMotionCache = new Vec3();
          this._rootBone = _rootBone;
          this._duration = _duration;
          this._boneTransform = _boneTransform;
          this._trackEvalStatuses = _trackEvalStatuses;
        }
        var _proto7 = RootMotionEvaluation.prototype;
        _proto7.evaluate = function evaluate(time, motionLength) {
          var motionTransform = this._calcMotionTransform(time, motionLength, this._motionTransformCache);
          var translationMotion = this._translationMotionCache,
            rotationMotion = this._rotationMotionCache,
            scaleMotion = this._scaleMotionCache,
            rootBone = this._rootBone;
          Mat4.toRTS(motionTransform, rotationMotion, translationMotion, scaleMotion);
          Vec3.add(translationMotion, translationMotion, rootBone.position);
          rootBone.setPosition(translationMotion);
          Quat.multiply(rotationMotion, rotationMotion, rootBone.rotation);
          rootBone.setRotation(rotationMotion);
          Vec3.multiply(scaleMotion, scaleMotion, rootBone.scale);
          rootBone.setScale(scaleMotion);
        };
        _proto7._calcMotionTransform = function _calcMotionTransform(time, motionLength, outTransform) {
          var duration = this._duration;
          var remainLength = duration - time;
          assertIsTrue(remainLength >= 0);
          var startTransform = this._evaluateAt(time, this._startTransformCache);
          if (motionLength < remainLength) {
            var endTransform = this._evaluateAt(time + motionLength, this._endTransformCache);
            relativeTransform(outTransform, startTransform, endTransform);
          } else {
            Mat4.identity(outTransform);
            var accumulateMotionTransform = function accumulateMotionTransform(from, to) {
              relativeTransform(motionTransformCache, from, to);
              Mat4.multiply(outTransform, outTransform, motionTransformCache);
            };
            var diff = motionLength - remainLength;
            var repeatCount = Math.floor(diff / duration);
            var lastRemainTime = diff - repeatCount * duration;
            var clipStartTransform = this._evaluateAt(0, this._initialTransformCache);
            var clipEndTransform = this._evaluateAt(duration, this._clipEndTransformCache);
            var _endTransform = this._evaluateAt(lastRemainTime, this._endTransformCache);
            accumulateMotionTransform(startTransform, clipEndTransform);
            relativeTransform(motionTransformCache, clipStartTransform, clipEndTransform);
            for (var i = 0; i < repeatCount; ++i) {
              Mat4.multiply(outTransform, outTransform, motionTransformCache);
            }
            accumulateMotionTransform(clipStartTransform, _endTransform);
          }
          return outTransform;
        };
        _proto7._evaluateAt = function _evaluateAt(time, outTransform) {
          var trackEvalStatuses = this._trackEvalStatuses;
          var nTrackEvalStatuses = trackEvalStatuses.length;
          for (var iTrackEvalStatus = 0; iTrackEvalStatus < nTrackEvalStatuses; ++iTrackEvalStatus) {
            trackEvalStatuses[iTrackEvalStatus].evaluate(time);
          }
          this._boneTransform.getTransform(outTransform);
          return outTransform;
        };
        return RootMotionEvaluation;
      }();
      function relativeTransform(out, from, to) {
        Mat4.invert(out, from);
        Mat4.multiply(out, to, out);
      }
      function createBoneTransformBinding(boneTransform, property) {
        switch (property) {
          default:
            return undefined;
          case 'position':
            return {
              setValue: function setValue(value) {
                Vec3.copy(boneTransform.position, value);
              }
            };
          case 'rotation':
            return {
              setValue: function setValue(value) {
                Quat.copy(boneTransform.rotation, value);
              }
            };
          case 'scale':
            return {
              setValue: function setValue(value) {
                Vec3.copy(boneTransform.scale, value);
              }
            };
          case 'eulerAngles':
            return {
              setValue: function setValue(value) {
                Vec3.copy(boneTransform.eulerAngles, value);
              }
            };
        }
      }
      var InvalidIndex = -1;
      var EventEvaluator = function () {
        function EventEvaluator(_targetNode, _ratios, _eventGroups, _wrapMode) {
          this._lastFrameIndex = -1;
          this._lastIterations = 0.0;
          this._lastDirection = 0;
          this._ignoreIndex = InvalidIndex;
          this._sampled = false;
          this._targetNode = _targetNode;
          this._ratios = _ratios;
          this._eventGroups = _eventGroups;
          this._wrapMode = _wrapMode;
        }
        var _proto8 = EventEvaluator.prototype;
        _proto8.setWrapMode = function setWrapMode(wrapMode) {
          this._wrapMode = wrapMode;
        };
        _proto8.ignore = function ignore(ratio, direction) {
          this._ignoreIndex = InvalidIndex;
          this._sampled = false;
          var frameIndex = getEventGroupIndexAtRatio(ratio, this._ratios);
          if (frameIndex < 0) {
            frameIndex = ~frameIndex - 1;
            if (direction < 0) {
              frameIndex += 1;
            }
            this._ignoreIndex = frameIndex;
          }
        };
        _proto8.reset = function reset() {
          this._lastFrameIndex = -1;
          this._lastIterations = 0.0;
          this._lastDirection = 0;
          this._ignoreIndex = InvalidIndex;
          this._sampled = false;
        };
        _proto8.sample = function sample(ratio, direction, iterations) {
          if (this._eventGroups.length === 0) {
            return;
          }
          var length = this._eventGroups.length;
          var eventIndex = getEventGroupIndexAtRatio(ratio, this._ratios);
          if (eventIndex < 0) {
            eventIndex = ~eventIndex - 1;
            if (direction < 0) {
              eventIndex += 1;
            }
          }
          if (this._ignoreIndex !== eventIndex) {
            this._ignoreIndex = InvalidIndex;
          }
          if (!this._sampled) {
            this._sampled = true;
            this._doFire(eventIndex, false);
            this._lastFrameIndex = eventIndex;
            this._lastIterations = iterations;
            this._lastDirection = direction;
            return;
          }
          var wrapMode = this._wrapMode;
          var currentIterations = wrapIterations(iterations);
          var lastIterations = wrapIterations(this._lastIterations);
          var lastIndex = this._lastFrameIndex;
          var lastDirection = this._lastDirection;
          var iterationsChanged = lastIterations !== -1 && currentIterations !== lastIterations;
          if (lastIndex === eventIndex && iterationsChanged && length === 1) {
            this._doFire(0, false);
          } else if (lastIndex !== eventIndex || iterationsChanged) {
            direction = lastDirection;
            do {
              if (lastIndex !== eventIndex) {
                if (direction === -1 && lastIndex === 0 && eventIndex > 0) {
                  if ((wrapMode & WrapModeMask.PingPong) === WrapModeMask.PingPong) {
                    direction *= -1;
                  } else {
                    lastIndex = length;
                  }
                  lastIterations++;
                } else if (direction === 1 && lastIndex === length - 1 && eventIndex < length - 1) {
                  if ((wrapMode & WrapModeMask.PingPong) === WrapModeMask.PingPong) {
                    direction *= -1;
                  } else {
                    lastIndex = -1;
                  }
                  lastIterations++;
                }
                if (lastIndex === eventIndex) {
                  break;
                }
                if (lastIterations > currentIterations) {
                  break;
                }
              }
              lastIndex += direction;
              this._doFire(lastIndex, true);
            } while (lastIndex !== eventIndex && lastIndex > -1 && lastIndex < length);
          }
          this._lastFrameIndex = eventIndex;
          this._lastIterations = iterations;
          this._lastDirection = direction;
        };
        _proto8._doFire = function _doFire(eventIndex, delay) {
          if (delay) {
            getGlobalAnimationManager().pushDelayEvent(this._checkAndFire, this, [eventIndex]);
          } else {
            this._checkAndFire(eventIndex);
          }
        };
        _proto8._checkAndFire = function _checkAndFire(eventIndex) {
          if (!this._targetNode || !this._targetNode.isValid) {
            return;
          }
          var eventGroups = this._eventGroups;
          if (eventIndex < 0 || eventIndex >= eventGroups.length || this._ignoreIndex === eventIndex) {
            return;
          }
          var eventGroup = eventGroups[eventIndex];
          var nEvents = eventGroup.events.length;
          for (var iEvent = 0; iEvent < nEvents; ++iEvent) {
            var event = eventGroup.events[iEvent];
            invokeComponentMethodsEngagedInAnimationEvent(this._targetNode, event.functionName, event.parameters);
          }
        };
        return EventEvaluator;
      }();
      function wrapIterations(iterations) {
        if (iterations - (iterations | 0) === 0) {
          iterations -= 1;
        }
        return iterations | 0;
      }
      function getEventGroupIndexAtRatio(ratio, ratios) {
        var result = binarySearchEpsilon(ratios, ratio);
        return result;
      }

      function wrap(elapsedTime, duration, wrapMode, repeatCount, negativeSpeed, info) {
        if (duration === 0.0) {
          info.time = 0.0;
          info.ratio = 0.0;
          info.direction = 1.0;
          info.stopped = !!Number.isFinite(repeatCount);
          info.iterations = 0.0;
          return info;
        }
        var stopped = false;
        var currentIterations = elapsedTime > 0 ? elapsedTime / duration : -(elapsedTime / duration);
        if (currentIterations >= repeatCount) {
          currentIterations = repeatCount;
          stopped = true;
          var tempRatio = repeatCount - (repeatCount | 0);
          if (tempRatio === 0) {
            tempRatio = 1;
          }
          elapsedTime = tempRatio * duration * (elapsedTime > 0 ? 1 : -1);
        }
        if (elapsedTime > duration) {
          var tempTime = elapsedTime % duration;
          elapsedTime = tempTime === 0 ? duration : tempTime;
        } else if (elapsedTime < 0) {
          elapsedTime %= duration;
          if (elapsedTime !== 0) {
            elapsedTime += duration;
          }
        }
        var needReverse = false;
        var shouldWrap = wrapMode & WrapModeMask.ShouldWrap;
        if (shouldWrap) {
          needReverse = isReverseIteration(wrapMode, currentIterations);
        }
        var direction = needReverse ? -1 : 1;
        if (negativeSpeed) {
          direction *= -1;
        }
        if (shouldWrap && needReverse) {
          elapsedTime = duration - elapsedTime;
        }
        info.time = elapsedTime;
        info.ratio = info.time / duration;
        info.direction = direction;
        info.stopped = stopped;
        info.iterations = currentIterations;
        return info;
      }
      function isReverseIteration(wrapMode, currentIterations) {
        var needReverse = false;
        if ((wrapMode & WrapModeMask.PingPong) === WrapModeMask.PingPong) {
          var isEnd = currentIterations - (currentIterations | 0) === 0;
          if (isEnd && currentIterations > 0) {
            currentIterations -= 1;
          }
          var isOddIteration = currentIterations & 1;
          if (isOddIteration) {
            needReverse = !needReverse;
          }
        }
        if ((wrapMode & WrapModeMask.Reverse) === WrapModeMask.Reverse) {
          needReverse = !needReverse;
        }
        return needReverse;
      }

      var CACHE_VEC3_GET_VALUE = new Vec3();
      var CACHE_QUAT_GET_VALUE = new Quat();
      var PoseBindingBase = function () {
        function PoseBindingBase(transformHandle) {
          this._transformHandle = transformHandle;
        }
        var _proto = PoseBindingBase.prototype;
        _proto.destroy = function destroy() {
          this._transformHandle.destroy();
        };
        return PoseBindingBase;
      }();
      var PosePositionBinding = function (_PoseBindingBase) {
        _inheritsLoose(PosePositionBinding, _PoseBindingBase);
        function PosePositionBinding() {
          return _PoseBindingBase.apply(this, arguments) || this;
        }
        var _proto2 = PosePositionBinding.prototype;
        _proto2.setValue = function setValue(value, pose) {
          pose.transforms.setPosition(this._transformHandle.index, value);
        };
        _proto2.getValue = function getValue(pose) {
          return pose.transforms.getPosition(this._transformHandle.index, CACHE_VEC3_GET_VALUE);
        };
        return PosePositionBinding;
      }(PoseBindingBase);
      var PoseRotationBinding = function (_PoseBindingBase2) {
        _inheritsLoose(PoseRotationBinding, _PoseBindingBase2);
        function PoseRotationBinding() {
          return _PoseBindingBase2.apply(this, arguments) || this;
        }
        var _proto3 = PoseRotationBinding.prototype;
        _proto3.setValue = function setValue(value, pose) {
          pose.transforms.setRotation(this._transformHandle.index, value);
        };
        _proto3.getValue = function getValue(pose) {
          return pose.transforms.getRotation(this._transformHandle.index, CACHE_QUAT_GET_VALUE);
        };
        return PoseRotationBinding;
      }(PoseBindingBase);
      var PoseEulerAnglesBinding = function (_PoseBindingBase3) {
        _inheritsLoose(PoseEulerAnglesBinding, _PoseBindingBase3);
        function PoseEulerAnglesBinding() {
          return _PoseBindingBase3.apply(this, arguments) || this;
        }
        var _proto4 = PoseEulerAnglesBinding.prototype;
        _proto4.setValue = function setValue(value, pose) {
          var quat = Quat.fromEuler(PoseEulerAnglesBinding._EULER_TO_QUAT_CACHE, value.x, value.y, value.z);
          pose.transforms.setRotation(this._transformHandle.index, quat);
        };
        _proto4.getValue = function getValue(pose) {
          var q = pose.transforms.getRotation(this._transformHandle.index, CACHE_QUAT_GET_VALUE);
          return Quat.toEuler(CACHE_VEC3_GET_VALUE, q);
        };
        return PoseEulerAnglesBinding;
      }(PoseBindingBase);
      PoseEulerAnglesBinding._EULER_TO_QUAT_CACHE = new Quat();
      var PoseScaleBinding = function (_PoseBindingBase4) {
        _inheritsLoose(PoseScaleBinding, _PoseBindingBase4);
        function PoseScaleBinding() {
          return _PoseBindingBase4.apply(this, arguments) || this;
        }
        var _proto5 = PoseScaleBinding.prototype;
        _proto5.setValue = function setValue(value, pose) {
          pose.transforms.setScale(this._transformHandle.index, value);
        };
        _proto5.getValue = function getValue(pose) {
          return pose.transforms.getScale(this._transformHandle.index, CACHE_VEC3_GET_VALUE);
        };
        return PoseScaleBinding;
      }(PoseBindingBase);
      var AuxiliaryCurveBinding = function () {
        function AuxiliaryCurveBinding(_handle) {
          this._handle = _handle;
        }
        var _proto6 = AuxiliaryCurveBinding.prototype;
        _proto6.destroy = function destroy() {
          this._handle.destroy();
        };
        _proto6.setValue = function setValue(value, pose) {
          pose.auxiliaryCurves[this._handle.index] = value;
        };
        _proto6.getValue = function getValue(pose) {
          return pose.auxiliaryCurves[this._handle.index];
        };
        return AuxiliaryCurveBinding;
      }();
      function bindPoseTransform(transformHandle, propertyKey) {
        switch (propertyKey) {
          case 'position':
            return new PosePositionBinding(transformHandle);
          case 'rotation':
            return new PoseRotationBinding(transformHandle);
          case 'eulerAngles':
            return new PoseEulerAnglesBinding(transformHandle);
          case 'scale':
            return new PoseScaleBinding(transformHandle);
          default:
            assertIsTrue(false);
        }
      }
      var NonTransformPoseBinding = function () {
        function NonTransformPoseBinding(binding) {
          this.binding = binding;
        }
        var _proto7 = NonTransformPoseBinding.prototype;
        _proto7.destroy = function destroy() {};
        _proto7.setValue = function setValue(value, _pose) {
          this.binding.setValue(value);
        };
        _proto7.getValue = function getValue(pose) {
          var _this$binding$getValu, _this$binding$getValu2, _this$binding;
          return (_this$binding$getValu = (_this$binding$getValu2 = (_this$binding = this.binding).getValue) === null || _this$binding$getValu2 === void 0 ? void 0 : _this$binding$getValu2.call(_this$binding)) !== null && _this$binding$getValu !== void 0 ? _this$binding$getValu : undefined;
        };
        return NonTransformPoseBinding;
      }();
      var AGTrackEvaluation = function () {
        function AGTrackEvaluation(binding, trackEvaluation) {
          this._binding = void 0;
          this._trackSampler = void 0;
          this._binding = binding;
          this._trackSampler = trackEvaluation;
        }
        var _proto8 = AGTrackEvaluation.prototype;
        _proto8.destroy = function destroy() {
          this._binding.destroy();
        };
        _proto8.evaluate = function evaluate(time, pose) {
          var trackSampler = this._trackSampler,
            binding = this._binding;
          var defaultValue = trackSampler.requiresDefault ? binding.getValue(pose) : undefined;
          var value = trackSampler.evaluate(time, defaultValue);
          binding.setValue(value, pose);
        };
        return AGTrackEvaluation;
      }();
      function bindTrackAG(animationClip, track, bindContext) {
        var trackBinding = track[trackBindingTag];
        var trackTarget = createRuntimeBindingAG(trackBinding, bindContext);
        if (!trackTarget) {
          warnID(3937, animationClip.name, bindContext.origin.name);
        }
        return trackTarget !== null && trackTarget !== void 0 ? trackTarget : undefined;
      }
      function createRuntimeBindingAG(track, bindContext) {
        var origin = bindContext.origin;
        var path = track.path,
          proxy = track.proxy;
        var nPaths = path.length;
        var iLastPath = nPaths - 1;
        if (nPaths !== 0 && (path.isPropertyAt(iLastPath) || path.isElementAt(iLastPath)) && !proxy) {
          var lastPropertyKey = path.isPropertyAt(iLastPath) ? path.parsePropertyAt(iLastPath) : path.parseElementAt(iLastPath);
          var resultTarget = path[normalizedFollowTag](origin, 0, nPaths - 1);
          if (resultTarget === null) {
            return null;
          }
          if (resultTarget instanceof Node$1 && isTrsPropertyName(lastPropertyKey)) {
            var transformPath = function () {
              var segments = [];
              var node = resultTarget;
              for (; node && node !== origin; node = node.parent) {
                segments.unshift(node.name);
              }
              if (node === origin) {
                return segments.join('/');
              } else {
                return undefined;
              }
            }();
            if (typeof transformPath === 'string') {
              var transformHandle = bindContext.bindTransform(transformPath);
              if (!transformHandle) {
                return undefined;
              }
              return bindPoseTransform(transformHandle, lastPropertyKey);
            }
          }
        }
        {
          var nonTransformBinding = track.createRuntimeBinding(bindContext.origin, undefined, false);
          if (!nonTransformBinding) {
            return null;
          }
          return new NonTransformPoseBinding(nonTransformBinding);
        }
      }
      var AuxiliaryCurveEvaluation = function () {
        function AuxiliaryCurveEvaluation(_binding, _curve) {
          this._binding = _binding;
          this._curve = _curve;
        }
        var _proto9 = AuxiliaryCurveEvaluation.prototype;
        _proto9.evaluate = function evaluate(time, context) {
          var curve = this._curve,
            binding = this._binding;
          var pose = context;
          var value = curve.evaluate(time);
          binding.setValue(value, pose);
        };
        return AuxiliaryCurveEvaluation;
      }();
      function createAnimationAGEvaluation(clip, context) {
        if (clip.isAdditive_experimental) {
          return new AnimationClipAGEvaluationAdditive(clip, context);
        } else {
          return new AnimationClipAGEvaluationRegular(clip, context);
        }
      }
      var AnimationClipAGEvaluationRegular = function () {
        function AnimationClipAGEvaluationRegular(clip, context) {
          this._trackEvaluations = [];
          this._exoticAnimationEvaluation = void 0;
          this._auxiliaryCurveEvaluations = [];
          clip._trySyncLegacyData();
          var trackEvaluations = [];
          var exoticAnimationEvaluation;
          var auxiliaryCurveEvaluations = [];
          var tracks = clip.tracks;
          var exoticAnimation = clip[exoticAnimationTag];
          for (var _iterator = _createForOfIteratorHelperLoose(tracks), _step; !(_step = _iterator()).done;) {
            var track = _step.value;
            if (track instanceof UntypedTrack) {
              continue;
            }
            if (Array.from(track.channels()).every(function (_ref) {
              var curve = _ref.curve;
              return curve.keyFramesCount === 0;
            })) {
              continue;
            }
            var trackRuntimeBinding = bindTrackAG(clip, track, context);
            if (!trackRuntimeBinding) {
              continue;
            }
            var trackSampler = track[createEvalSymbol]();
            var trackEvaluation = new AGTrackEvaluation(trackRuntimeBinding, trackSampler);
            trackEvaluations.push(trackEvaluation);
          }
          if (exoticAnimation) {
            exoticAnimationEvaluation = exoticAnimation.createEvaluatorForAnimationGraph(context);
          }
          var auxiliaryCurveNames = clip.getAuxiliaryCurveNames_experimental();
          var nAuxiliaryCurves = auxiliaryCurveNames.length;
          for (var iAuxiliaryCurve = 0; iAuxiliaryCurve < nAuxiliaryCurves; ++iAuxiliaryCurve) {
            var _curveName = auxiliaryCurveNames[iAuxiliaryCurve];
            var curve = clip.getAuxiliaryCurve_experimental(_curveName);
            var handle = context.bindAuxiliaryCurve(_curveName);
            var _binding2 = new AuxiliaryCurveBinding(handle);
            auxiliaryCurveEvaluations.push(new AuxiliaryCurveEvaluation(_binding2, curve));
          }
          this._trackEvaluations = trackEvaluations;
          this._exoticAnimationEvaluation = exoticAnimationEvaluation;
          this._auxiliaryCurveEvaluations = auxiliaryCurveEvaluations;
        }
        var _proto10 = AnimationClipAGEvaluationRegular.prototype;
        _proto10.destroy = function destroy() {
          var _this$_exoticAnimatio;
          (_this$_exoticAnimatio = this._exoticAnimationEvaluation) === null || _this$_exoticAnimatio === void 0 ? void 0 : _this$_exoticAnimatio.destroy();
          var trackEvaluations = this._trackEvaluations;
          var nTrackEvaluations = trackEvaluations.length;
          for (var iNodeEvaluation = 0; iNodeEvaluation < nTrackEvaluations; ++iNodeEvaluation) {
            trackEvaluations[iNodeEvaluation].destroy();
          }
        };
        _proto10.evaluate = function evaluate(time, context) {
          var trackEvaluations = this._trackEvaluations,
            exoticAnimationEvaluation = this._exoticAnimationEvaluation,
            auxiliaryCurveEvaluations = this._auxiliaryCurveEvaluations;
          var pose = context.pushDefaultedPose();
          var nTrackEvaluations = trackEvaluations.length;
          for (var iNodeEvaluation = 0; iNodeEvaluation < nTrackEvaluations; ++iNodeEvaluation) {
            trackEvaluations[iNodeEvaluation].evaluate(time, pose);
          }
          if (exoticAnimationEvaluation) {
            exoticAnimationEvaluation.evaluate(time, pose);
          }
          var nAuxiliaryCurveEvaluations = auxiliaryCurveEvaluations.length;
          for (var iAuxiliaryCurveEvaluation = 0; iAuxiliaryCurveEvaluation < nAuxiliaryCurveEvaluations; ++iAuxiliaryCurveEvaluation) {
            auxiliaryCurveEvaluations[iAuxiliaryCurveEvaluation].evaluate(time, pose);
          }
          return pose;
        };
        return AnimationClipAGEvaluationRegular;
      }();
      var AnimationClipAGEvaluationAdditive = function () {
        function AnimationClipAGEvaluationAdditive(clip, context) {
          this._clipEval = void 0;
          this._refClipEval = void 0;
          this._clipEval = new AnimationClipAGEvaluationRegular(clip, context);
          var refClip = clip[additiveSettingsTag].refClip;
          if (refClip && refClip !== clip) {
            this._refClipEval = new AnimationClipAGEvaluationRegular(refClip, context);
          }
        }
        var _proto11 = AnimationClipAGEvaluationAdditive.prototype;
        _proto11.destroy = function destroy() {
          var _this$_refClipEval;
          this._clipEval.destroy();
          (_this$_refClipEval = this._refClipEval) === null || _this$_refClipEval === void 0 ? void 0 : _this$_refClipEval.destroy();
        };
        _proto11.evaluate = function evaluate(time, context) {
          var pose = this._clipEval.evaluate(time, context);
          var refPose;
          if (this._refClipEval) {
            var refClipTime = 0.0;
            refPose = this._refClipEval.evaluate(refClipTime, context);
          } else {
            refPose = this._clipEval.evaluate(0.0, context);
          }
          calculateDeltaPose(pose, refPose);
          context.popPose();
          return pose;
        };
        return AnimationClipAGEvaluationAdditive;
      }();

      var _dec$1i, _dec2$19, _class$1g, _class2$1b, _initializer$13;
      var ccclass$d = ccclass$n,
        type$1 = type$7;
      var ClipMotion = (_dec$1i = ccclass$d('cc.animation.ClipMotion'), _dec2$19 = type$1(AnimationClip), _dec$1i(_class$1g = (_class2$1b = function (_Motion) {
        _inheritsLoose(ClipMotion, _Motion);
        function ClipMotion() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Motion.call.apply(_Motion, [this].concat(args)) || this;
          _this.clip = _initializer$13 && _initializer$13();
          return _this;
        }
        var _proto = ClipMotion.prototype;
        _proto[createEval] = function (context, ignoreEmbeddedPlayers) {
          if (!this.clip) {
            return null;
          }
          var clipMotionEval = new ClipMotionEval(context, this.clip, ignoreEmbeddedPlayers);
          return clipMotionEval;
        };
        _proto.clone = function clone() {
          var that = new ClipMotion();
          that.clip = this.clip;
          that[editorExtrasTag] = cloneAnimationGraphEditorExtrasFrom(this);
          return that;
        };
        return ClipMotion;
      }(Motion), (_initializer$13 = applyDecoratedInitializer(_class2$1b.prototype, "clip", [_dec2$19, serializable$j], function () {
        return null;
      })), _class2$1b)) || _class$1g);
      var evaluatePortTag = Symbol('EvaluatePort');
      var ClipMotionEval = function () {
        function ClipMotionEval(context, clip, ignoreEmbeddedPlayers) {
          var _context$clipOverride, _context$clipOverride2;
          this._clipEmbeddedPlayerEval = null;
          this._frameEventEval = null;
          this._wrapInfo = new WrappedInfo();
          this._duration = 0.0;
          this._ignoreEmbeddedPlayers = void 0;
          this._originalClip = clip;
          this._ignoreEmbeddedPlayers = ignoreEmbeddedPlayers;
          var overriding = (_context$clipOverride = (_context$clipOverride2 = context.clipOverrides) === null || _context$clipOverride2 === void 0 ? void 0 : _context$clipOverride2.get(clip)) !== null && _context$clipOverride !== void 0 ? _context$clipOverride : clip;
          this._setClip(overriding, context);
        }
        var _proto2 = ClipMotionEval.prototype;
        _proto2.createPort = function createPort() {
          return new ClipMotionPort(this);
        };
        _proto2.getClipStatuses = function getClipStatuses(baseWeight) {
          var _this2 = this;
          var got = false;
          return {
            next: function next() {
              if (got) {
                return {
                  done: true,
                  value: undefined
                };
              } else {
                got = true;
                return {
                  done: false,
                  value: {
                    __DEBUG_ID__: _this2.__DEBUG__ID__,
                    clip: _this2._clip,
                    weight: baseWeight
                  }
                };
              }
            }
          };
        };
        _proto2[evaluatePortTag] = function (progress, context) {
          var _this$_frameEventEval, _this$_clipEmbeddedPl;
          var duration = this._duration,
            clipDuration = this._clip.duration,
            clipEval = this._clipEval;
          var elapsedTime = duration * progress;
          var wrapMode = this._clip.wrapMode;
          var repeatCount = (wrapMode & WrapModeMask.Loop) === WrapModeMask.Loop ? Infinity : 1;
          var wrapInfo = wrap(elapsedTime, duration, wrapMode, repeatCount, false, this._wrapInfo);
          var clipTime = wrapInfo.ratio * clipDuration;
          var pose = clipEval.evaluate(clipTime, context);
          (_this$_frameEventEval = this._frameEventEval) === null || _this$_frameEventEval === void 0 ? void 0 : _this$_frameEventEval.sample(wrapInfo.ratio, wrapInfo.direction, wrapInfo.iterations);
          (_this$_clipEmbeddedPl = this._clipEmbeddedPlayerEval) === null || _this$_clipEmbeddedPl === void 0 ? void 0 : _this$_clipEmbeddedPl.evaluate(clipTime, Math.trunc(wrapInfo.iterations));
          return pose;
        };
        _proto2.overrideClips = function overrideClips(context) {
          var _context$clipOverride3;
          var originalClip = this._originalClip;
          var overriding = (_context$clipOverride3 = context.clipOverrides) === null || _context$clipOverride3 === void 0 ? void 0 : _context$clipOverride3.get(originalClip);
          if (overriding) {
            this._setClip(overriding, context);
          }
        };
        _proto2.reenter = function reenter() {
          var _this$_frameEventEval2;
          (_this$_frameEventEval2 = this._frameEventEval) === null || _this$_frameEventEval2 === void 0 ? void 0 : _this$_frameEventEval2.reset();
        };
        _proto2._setClip = function _setClip(clip, context) {
          var _this$_clipEval;
          (_this$_clipEval = this._clipEval) === null || _this$_clipEval === void 0 ? void 0 : _this$_clipEval.destroy();
          this._frameEventEval = null;
          if (this._clipEmbeddedPlayerEval) {
            this._clipEmbeddedPlayerEval.destroy();
            this._clipEmbeddedPlayerEval = null;
          }
          this._clip = clip;
          this._duration = clip.speed === 0.0 ? 0.0 : clip.duration / clip.speed;
          this._clipEval = createAnimationAGEvaluation(clip, context);
          this._frameEventEval = clip.createEventEvaluator(context.origin);
          if (!this._ignoreEmbeddedPlayers && clip.containsAnyEmbeddedPlayer()) {
            this._clipEmbeddedPlayerEval = clip.createEmbeddedPlayerEvaluator(context.origin);
          }
        };
        _createClass(ClipMotionEval, [{
          key: "duration",
          get: function get() {
            return this._duration;
          }
        }]);
        return ClipMotionEval;
      }();
      var ClipMotionPort = function () {
        function ClipMotionPort(host) {
          this._eval = void 0;
          this._eval = host;
        }
        var _proto3 = ClipMotionPort.prototype;
        _proto3.evaluate = function evaluate(progress, context) {
          return this._eval[evaluatePortTag](progress, context);
        };
        _proto3.reenter = function reenter() {
          this._eval.reenter();
        };
        return ClipMotionPort;
      }();

      var _dec$1h, _class$1f, _class2$1a, _initializer$12, _dec2$18, _class4$c, _class5$e, _initializer2$T;
      var ccclass$c = ccclass$n,
        serializable$a = serializable$j;
      var AnimationBlendItem = (_dec$1h = ccclass$c(CLASS_NAME_PREFIX_ANIM + "AnimationBlendItem"), _dec$1h(_class$1f = (_class2$1a = function () {
        function AnimationBlendItem() {
          this.motion = _initializer$12 && _initializer$12();
        }
        var _proto = AnimationBlendItem.prototype;
        _proto.clone = function clone() {
          var that = new AnimationBlendItem();
          this._copyTo(that);
          return that;
        };
        _proto._copyTo = function _copyTo(that) {
          var _this$motion$clone, _this$motion;
          that.motion = (_this$motion$clone = (_this$motion = this.motion) === null || _this$motion === void 0 ? void 0 : _this$motion.clone()) !== null && _this$motion$clone !== void 0 ? _this$motion$clone : null;
          return that;
        };
        return AnimationBlendItem;
      }(), (_initializer$12 = applyDecoratedInitializer(_class2$1a.prototype, "motion", [serializable$a], function () {
        return null;
      })), _class2$1a)) || _class$1f);
      var AnimationBlend = (_dec2$18 = ccclass$c(CLASS_NAME_PREFIX_ANIM + "AnimationBlend"), _dec2$18(_class4$c = (_class5$e = function (_Motion) {
        _inheritsLoose(AnimationBlend, _Motion);
        function AnimationBlend() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Motion.call.apply(_Motion, [this].concat(args)) || this;
          _this.name = _initializer2$T && _initializer2$T();
          return _this;
        }
        var _proto2 = AnimationBlend.prototype;
        _proto2.copyTo = function copyTo(that) {
          that.name = this.name;
          that[editorExtrasTag] = cloneAnimationGraphEditorExtrasFrom(this);
        };
        return AnimationBlend;
      }(Motion), (_initializer2$T = applyDecoratedInitializer(_class5$e.prototype, "name", [serializable$a], function () {
        return '';
      })), _class5$e)) || _class4$c);
      var AnimationBlendEval = function () {
        function AnimationBlendEval(context, ignoreEmbeddedPlayers, base, children, inputs) {
          this._childEvaluators = children.map(function (child) {
            var _child$motion$createE, _child$motion;
            return (_child$motion$createE = (_child$motion = child.motion) === null || _child$motion === void 0 ? void 0 : _child$motion[createEval](context, ignoreEmbeddedPlayers)) !== null && _child$motion$createE !== void 0 ? _child$motion$createE : null;
          });
          this._weights = new Array(this._childEvaluators.length).fill(0);
          this._inputs = [].concat(inputs);
        }
        var _proto3 = AnimationBlendEval.prototype;
        _proto3.createPort = function createPort() {
          return new AnimationBlendPort(this, this._childEvaluators.map(function (childEval) {
            var _childEval$createPort;
            return (_childEval$createPort = childEval === null || childEval === void 0 ? void 0 : childEval.createPort()) !== null && _childEval$createPort !== void 0 ? _childEval$createPort : null;
          }));
        };
        _proto3.getChildWeight = function getChildWeight(childIndex) {
          return this._weights[childIndex];
        };
        _proto3.getChildMotionEval = function getChildMotionEval(childIndex) {
          return this._childEvaluators[childIndex];
        };
        _proto3.getClipStatuses = function getClipStatuses(baseWeight) {
          var children = this._childEvaluators,
            weights = this._weights;
          var nChildren = children.length;
          var iChild = 0;
          var currentChildIterator;
          return {
            next: function next() {
              while (true) {
                if (currentChildIterator) {
                  var result = currentChildIterator.next();
                  if (!result.done) {
                    return result;
                  }
                }
                if (iChild >= nChildren) {
                  return {
                    done: true,
                    value: undefined
                  };
                } else {
                  var child = children[iChild];
                  currentChildIterator = child === null || child === void 0 ? void 0 : child.getClipStatuses(baseWeight * weights[iChild]);
                  ++iChild;
                }
              }
            }
          };
        };
        _proto3.__evaluatePort = function __evaluatePort(port, progress, context) {
          var nChild = this._childEvaluators.length;
          var sumWeight = 0.0;
          var finalPose = null;
          for (var iChild = 0; iChild < nChild; ++iChild) {
            var _port$childPorts$iChi;
            var childWeight = this._weights[iChild];
            if (!childWeight) {
              continue;
            }
            var childOutput = (_port$childPorts$iChi = port.childPorts[iChild]) === null || _port$childPorts$iChi === void 0 ? void 0 : _port$childPorts$iChi.evaluate(progress, context);
            if (!childOutput) {
              continue;
            }
            sumWeight += childWeight;
            if (!finalPose) {
              finalPose = childOutput;
            } else {
              if (sumWeight) {
                var t = childWeight / sumWeight;
                blendPoseInto(finalPose, childOutput, t);
              }
              context.popPose();
            }
          }
          if (finalPose) {
            return finalPose;
          }
          return context.pushDefaultedPose();
        };
        _proto3.overrideClips = function overrideClips(context) {
          for (var iChild = 0; iChild < this._childEvaluators.length; ++iChild) {
            var _this$_childEvaluator;
            (_this$_childEvaluator = this._childEvaluators[iChild]) === null || _this$_childEvaluator === void 0 ? void 0 : _this$_childEvaluator.overrideClips(context);
          }
        };
        _proto3.setInput = function setInput(value, index) {
          this._inputs[index] = value;
          this.doEval();
        };
        _proto3.doEval = function doEval() {
          this.eval(this._weights, this._inputs);
        };
        _createClass(AnimationBlendEval, [{
          key: "childCount",
          get: function get() {
            return this._weights.length;
          }
        }, {
          key: "duration",
          get: function get() {
            var uniformDuration = 0.0;
            for (var iChild = 0; iChild < this._childEvaluators.length; ++iChild) {
              var _this$_childEvaluator2, _this$_childEvaluator3;
              uniformDuration += ((_this$_childEvaluator2 = (_this$_childEvaluator3 = this._childEvaluators[iChild]) === null || _this$_childEvaluator3 === void 0 ? void 0 : _this$_childEvaluator3.duration) !== null && _this$_childEvaluator2 !== void 0 ? _this$_childEvaluator2 : 0.0) * this._weights[iChild];
            }
            return uniformDuration;
          }
        }]);
        return AnimationBlendEval;
      }();
      var AnimationBlendPort = function () {
        function AnimationBlendPort(host, childPorts) {
          this.childPorts = [];
          this._host = void 0;
          this._host = host;
          this.childPorts = childPorts;
        }
        var _proto4 = AnimationBlendPort.prototype;
        _proto4.evaluate = function evaluate(progress, context) {
          return this._host.__evaluatePort(this, progress, context);
        };
        _proto4.reenter = function reenter() {
          var childPorts = this.childPorts;
          var nChildPorts = childPorts.length;
          for (var iChild = 0; iChild < nChildPorts; ++iChild) {
            var _childPorts$iChild;
            (_childPorts$iChild = childPorts[iChild]) === null || _childPorts$iChild === void 0 ? void 0 : _childPorts$iChild.reenter();
          }
        };
        return AnimationBlendPort;
      }();

      var _dec$1g, _class$1e, _class2$19, _initializer$11, _initializer2$S, _dec2$17, _class4$b, _class5$d, _initializer3$A, _initializer4$p;
      var ccclass$b = ccclass$n,
        serializable$9 = serializable$j;
      var BindableNumber = (_dec$1g = ccclass$b(CLASS_NAME_PREFIX_ANIM + "BindableNumber"), _dec$1g(_class$1e = (_class2$19 = function () {
        function BindableNumber(value) {
          if (value === void 0) {
            value = 0.0;
          }
          this.variable = _initializer$11 && _initializer$11();
          this.value = _initializer2$S && _initializer2$S();
          this.value = value;
        }
        var _proto = BindableNumber.prototype;
        _proto.clone = function clone() {
          var that = new BindableNumber();
          that.value = this.value;
          that.variable = this.variable;
          return that;
        };
        return BindableNumber;
      }(), (_initializer$11 = applyDecoratedInitializer(_class2$19.prototype, "variable", [serializable$9], function () {
        return '';
      }), _initializer2$S = applyDecoratedInitializer(_class2$19.prototype, "value", [serializable$9], function () {
        return 0.0;
      })), _class2$19)) || _class$1e);
      var BindableBoolean = (_dec2$17 = ccclass$b(CLASS_NAME_PREFIX_ANIM + "BindableBoolean"), _dec2$17(_class4$b = (_class5$d = function () {
        function BindableBoolean(value) {
          if (value === void 0) {
            value = false;
          }
          this.variable = _initializer3$A && _initializer3$A();
          this.value = _initializer4$p && _initializer4$p();
          this.value = value;
        }
        var _proto2 = BindableBoolean.prototype;
        _proto2.clone = function clone() {
          var that = new BindableBoolean();
          that.value = this.value;
          that.variable = this.variable;
          return that;
        };
        return BindableBoolean;
      }(), (_initializer3$A = applyDecoratedInitializer(_class5$d.prototype, "variable", [serializable$9], function () {
        return '';
      }), _initializer4$p = applyDecoratedInitializer(_class5$d.prototype, "value", [serializable$9], function () {
        return false;
      })), _class5$d)) || _class4$b);
      function bindOr(context, bindable, type, callback, thisArg) {
        var variable = bindable.variable,
          value = bindable.value;
        if (!variable) {
          return value;
        }
        var varInstance = context.getVar(variable);
        if (!validateVariableExistence(varInstance, variable)) {
          return value;
        }
        if (varInstance.type !== type) {
          throw new VariableTypeMismatchedError(variable, 'number');
        }
        for (var _len = arguments.length, args = new Array(_len > 5 ? _len - 5 : 0), _key = 5; _key < _len; _key++) {
          args[_key - 5] = arguments[_key];
        }
        var initialValue = varInstance.bind.apply(varInstance, [callback, thisArg].concat(args));
        return initialValue;
      }
      function validateVariableExistence(varInstance, name) {
        if (!varInstance) {
          throw new VariableNotDefinedError(name);
        } else {
          return true;
        }
      }
      function validateVariableType(type, expected, name) {
        if (type !== expected) {
          throw new VariableTypeMismatchedError(name, 'number');
        }
      }
      function validateVariableTypeTriggerLike(type, name) {
        if (type !== VariableType.TRIGGER) {
          throw new VariableTypeMismatchedError(name, 'trigger');
        }
      }

      function blend1D(weights, thresholds, value) {
        weights.fill(0.0);
        if (thresholds.length === 0) ; else if (value <= thresholds[0]) {
          weights[0] = 1;
        } else if (value >= thresholds[thresholds.length - 1]) {
          weights[weights.length - 1] = 1;
        } else {
          var iUpper = 0;
          for (var iThresholds = 1; iThresholds < thresholds.length; ++iThresholds) {
            if (thresholds[iThresholds] > value) {
              iUpper = iThresholds;
              break;
            }
          }
          var lower = thresholds[iUpper - 1];
          var upper = thresholds[iUpper];
          var dVal = upper - lower;
          weights[iUpper - 1] = (upper - value) / dVal;
          weights[iUpper] = (value - lower) / dVal;
        }
      }

      var _dec$1f, _class$1d, _class2$18, _initializer$10, _dec2$16, _class4$a, _class5$c, _initializer2$R, _initializer3$z, _class6$4;
      var ccclass$a = ccclass$n,
        serializable$8 = serializable$j;
      var AnimationBlend1DItem = (_dec$1f = ccclass$a(CLASS_NAME_PREFIX_ANIM + "AnimationBlend1DItem"), _dec$1f(_class$1d = (_class2$18 = function (_AnimationBlendItem) {
        _inheritsLoose(AnimationBlend1DItem, _AnimationBlendItem);
        function AnimationBlend1DItem() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _AnimationBlendItem.call.apply(_AnimationBlendItem, [this].concat(args)) || this;
          _this.threshold = _initializer$10 && _initializer$10();
          return _this;
        }
        var _proto = AnimationBlend1DItem.prototype;
        _proto.clone = function clone() {
          var that = new AnimationBlend1DItem();
          this._copyTo(that);
          return that;
        };
        _proto._copyTo = function _copyTo(that) {
          _AnimationBlendItem.prototype._copyTo.call(this, that);
          that.threshold = this.threshold;
          return that;
        };
        return AnimationBlend1DItem;
      }(AnimationBlendItem), (_initializer$10 = applyDecoratedInitializer(_class2$18.prototype, "threshold", [serializable$8], function () {
        return 0.0;
      })), _class2$18)) || _class$1d);
      var AnimationBlend1D = (_dec2$16 = ccclass$a('cc.animation.AnimationBlend1D'), _dec2$16(_class4$a = (_class5$c = (_class6$4 = function (_AnimationBlend) {
        _inheritsLoose(AnimationBlend1D, _AnimationBlend);
        function AnimationBlend1D() {
          var _this2;
          for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
            args[_key2] = arguments[_key2];
          }
          _this2 = _AnimationBlend.call.apply(_AnimationBlend, [this].concat(args)) || this;
          _this2._items = _initializer2$R && _initializer2$R();
          _this2.param = _initializer3$z && _initializer3$z();
          return _this2;
        }
        var _proto2 = AnimationBlend1D.prototype;
        _proto2.clone = function clone() {
          var that = new AnimationBlend1D();
          this.copyTo(that);
          that._items = this._items.map(function (item) {
            return item.clone();
          });
          that.param = this.param.clone();
          return that;
        };
        _proto2[createEval] = function (context, ignoreEmbeddedPlayers) {
          var evaluation = new AnimationBlend1DEval(context, ignoreEmbeddedPlayers, this, this._items, this._items.map(function (_ref) {
            var threshold = _ref.threshold;
            return threshold;
          }), 0.0);
          var initialValue = bindOr(context, this.param, VariableType.FLOAT, evaluation.setInput, evaluation, 0);
          evaluation.setInput(initialValue, 0);
          return evaluation;
        };
        _createClass(AnimationBlend1D, [{
          key: "items",
          get: function get() {
            return this._items;
          },
          set: function set(value) {
            this._items = Array.from(value).sort(function (_ref2, _ref3) {
              var lhs = _ref2.threshold;
              var rhs = _ref3.threshold;
              return lhs - rhs;
            });
          }
        }]);
        return AnimationBlend1D;
      }(AnimationBlend), _class6$4.Item = AnimationBlend1DItem, _class6$4), (_initializer2$R = applyDecoratedInitializer(_class5$c.prototype, "_items", [serializable$8], function () {
        return [];
      }), _initializer3$z = applyDecoratedInitializer(_class5$c.prototype, "param", [serializable$8], function () {
        return new BindableNumber();
      })), _class5$c)) || _class4$a);
      var AnimationBlend1DEval = function (_AnimationBlendEval) {
        _inheritsLoose(AnimationBlend1DEval, _AnimationBlendEval);
        function AnimationBlend1DEval(context, ignoreEmbeddedPlayers, base, items, thresholds, input) {
          var _this3;
          _this3 = _AnimationBlendEval.call(this, context, ignoreEmbeddedPlayers, base, items, [input]) || this;
          _this3._thresholds = thresholds;
          _this3.doEval();
          return _this3;
        }
        var _proto3 = AnimationBlend1DEval.prototype;
        _proto3.eval = function _eval(weights, _ref4) {
          var value = _ref4[0];
          blend1D(weights, this._thresholds, value);
        };
        return AnimationBlend1DEval;
      }(AnimationBlendEval);

      var blendSimpleDirectional = function () {
        var CACHE_NORMALIZED_SAMPLE = new Vec2();
        var CACHE_BARYCENTRIC_SOLUTIONS = {
          wA: 0,
          wB: 0
        };
        return function blendSimpleDirectional(weights, samples, input) {
          assertIsTrue(weights.length === samples.length);
          if (samples.length === 0) {
            return;
          }
          if (samples.length === 1) {
            weights[0] = 1.0;
            return;
          }
          if (Vec2.strictEquals(input, Vec2.ZERO)) {
            var _iCenter = samples.findIndex(function (sample) {
              return Vec2.strictEquals(sample, Vec2.ZERO);
            });
            if (_iCenter >= 0) {
              weights[_iCenter] = 1.0;
            } else {
              weights.fill(1.0 / samples.length);
            }
            return;
          }
          var iSectorStart = -1;
          var iSectorEnd = -1;
          var iCenter = -1;
          var lhsCosAngle = Number.NEGATIVE_INFINITY;
          var rhsCosAngle = Number.NEGATIVE_INFINITY;
          var inputX = input.x,
            inputY = input.y;
          for (var iSample = 0; iSample < samples.length; ++iSample) {
            var sample = samples[iSample];
            if (Vec2.equals(sample, Vec2.ZERO)) {
              iCenter = iSample;
              continue;
            }
            var sampleNormalized = Vec2.normalize(CACHE_NORMALIZED_SAMPLE, sample);
            var cosAngle = Vec2.dot(sampleNormalized, input);
            var sign = sampleNormalized.x * inputY - sampleNormalized.y * inputX;
            if (sign > 0) {
              if (cosAngle >= rhsCosAngle) {
                rhsCosAngle = cosAngle;
                iSectorStart = iSample;
              }
            } else if (cosAngle >= lhsCosAngle) {
              lhsCosAngle = cosAngle;
              iSectorEnd = iSample;
            }
          }
          var centerWeight = 0.0;
          if (iSectorStart < 0 || iSectorEnd < 0) {
            centerWeight = 1.0;
          } else {
            var _solveBarycentric = solveBarycentric(samples[iSectorStart], samples[iSectorEnd], input, CACHE_BARYCENTRIC_SOLUTIONS),
              wA = _solveBarycentric.wA,
              wB = _solveBarycentric.wB;
            var w1 = 0.0;
            var w2 = 0.0;
            var sum = wA + wB;
            if (sum > 1) {
              w1 = wA / sum;
              w2 = wB / sum;
            } else if (sum < 0) {
              w1 = 0.0;
              w2 = 0.0;
              centerWeight = 1.0;
            } else {
              w1 = wA;
              w2 = wB;
              centerWeight = 1.0 - sum;
            }
            weights[iSectorStart] = w1;
            weights[iSectorEnd] = w2;
          }
          if (centerWeight > 0.0) {
            if (iCenter >= 0) {
              weights[iCenter] = centerWeight;
            } else {
              var average = centerWeight / weights.length;
              for (var i = 0; i < weights.length; ++i) {
                weights[i] += average;
              }
            }
          }
        };
      }();
      function sampleFreeformCartesian(weights, thresholds, value) {
        sampleFreeform(weights, thresholds, value, getGradientBandCartesianCoords);
      }
      function sampleFreeform(weights, samples, value, getGradientBandCoords) {
        weights.fill(0.0);
        var pIpInput = new Vec2(0, 0);
        var pIJ = new Vec2(0, 0);
        var sumInfluence = 0.0;
        var nSamples = samples.length;
        for (var iSample = 0; iSample < nSamples; ++iSample) {
          var influence = Number.MAX_VALUE;
          var outsideHull = false;
          for (var jSample = 0; jSample < nSamples; ++jSample) {
            if (iSample === jSample) {
              continue;
            }
            getGradientBandCoords(samples[iSample], samples[jSample], value, pIpInput, pIJ);
            var t = 1 - Vec2.dot(pIpInput, pIJ) / Vec2.lengthSqr(pIJ);
            if (t < 0) {
              outsideHull = true;
              break;
            }
            influence = Math.min(influence, t);
          }
          if (!outsideHull) {
            weights[iSample] = influence;
            sumInfluence += influence;
          }
        }
        if (sumInfluence > 0) {
          weights.forEach(function (influence, index) {
            return weights[index] = influence / sumInfluence;
          });
        }
      }
      function solveBarycentric(a, b, p, resolutions) {
        var det = Vec2.cross(a, b);
        if (!det) {
          resolutions.wA = 0.0;
          resolutions.wB = 0.0;
        } else {
          resolutions.wA = Vec2.cross(p, b) / det;
          resolutions.wB = Vec2.cross(p, a) / -det;
        }
        return resolutions;
      }
      var getGradientBandCartesianCoords = function getGradientBandCartesianCoords(pI, pJ, input, pIpInput, pIpJ) {
        Vec2.subtract(pIpInput, input, pI);
        Vec2.subtract(pIpJ, pJ, pI);
      };
      var PRECOMPUTED_VIJ_DATA_STRIDE = 3;
      var PolarSpaceGradientBandInterpolator2D = function () {
        function PolarSpaceGradientBandInterpolator2D(examples) {
          var angleMultiplier = PolarSpaceGradientBandInterpolator2D._ANGLE_MULTIPLIER;
          var nExamples = examples.length;
          var exampleMagnitudes = this._exampleMagnitudes = new Array(nExamples).fill(0.0);
          var exampleDirections = this._exampleDirections = examples.map(function (example, iExample) {
            var direction = Vec2.copy(new Vec2(), example);
            var magnitude = Vec2.len(direction);
            exampleMagnitudes[iExample] = magnitude;
            if (!approx(magnitude, 0.0, 1e-5)) {
              Vec2.multiplyScalar(direction, direction, 1.0 / magnitude);
            }
            return direction;
          });
          var precomputedVIJs = this._precomputedVIJs = new Float32Array(PRECOMPUTED_VIJ_DATA_STRIDE * nExamples * nExamples);
          for (var iExample = 0; iExample < nExamples; ++iExample) {
            var magnitudeI = exampleMagnitudes[iExample];
            var directionI = exampleDirections[iExample];
            for (var jExample = 0; jExample < nExamples; ++jExample) {
              if (iExample === jExample) {
                continue;
              }
              var magnitudeJ = exampleMagnitudes[jExample];
              var directionJ = exampleDirections[jExample];
              var averagedMagnitude = (magnitudeI + magnitudeJ) / 2;
              var pOutput = PRECOMPUTED_VIJ_DATA_STRIDE * (nExamples * iExample + jExample);
              precomputedVIJs[pOutput + 0] = (magnitudeJ - magnitudeI) / averagedMagnitude;
              precomputedVIJs[pOutput + 1] = signedAngle(directionI, directionJ) * angleMultiplier;
              precomputedVIJs[pOutput + 2] = averagedMagnitude;
            }
          }
          this._cacheVIXAngles = new Float32Array(nExamples);
        }
        var _proto = PolarSpaceGradientBandInterpolator2D.prototype;
        _proto.interpolate = function interpolate(weights, input) {
          var exampleDirections = this._exampleDirections,
            exampleMagnitudes = this._exampleMagnitudes,
            precomputedVIJs = this._precomputedVIJs,
            cacheVIXAngles = this._cacheVIXAngles;
          var cacheInputDirection = PolarSpaceGradientBandInterpolator2D._CACHE_INPUT_DIRECTION,
            cacheVIJ = PolarSpaceGradientBandInterpolator2D._CACHE_VIJ,
            cacheVIX = PolarSpaceGradientBandInterpolator2D._CACHE_VIX,
            angleMultiplier = PolarSpaceGradientBandInterpolator2D._ANGLE_MULTIPLIER;
          var nExamples = exampleDirections.length;
          assertIsTrue(weights.length === nExamples);
          if (nExamples === 0) {
            return;
          } else if (nExamples === 1) {
            weights[0] = 1.0;
            return;
          }
          var vX = input;
          var magnitudeX = Vec2.len(vX);
          var vIXAngles = cacheVIXAngles;
          if (Vec2.equals(vX, Vec2.ZERO)) {
            for (var iExample = 0; iExample < nExamples; ++iExample) {
              vIXAngles[iExample] = 0.0;
            }
          } else {
            var directionX = Vec2.multiplyScalar(cacheInputDirection, vX, 1.0 / magnitudeX);
            for (var _iExample = 0; _iExample < nExamples; ++_iExample) {
              var directionI = exampleDirections[_iExample];
              if (Vec2.equals(directionI, Vec2.ZERO)) {
                vIXAngles[_iExample] = 0.0;
              } else {
                vIXAngles[_iExample] = signedAngle(directionI, directionX) * angleMultiplier;
              }
            }
          }
          var totalWeight = 0.0;
          for (var _iExample2 = 0; _iExample2 < nExamples; ++_iExample2) {
            var magnitudeI = exampleMagnitudes[_iExample2];
            var _directionI = exampleDirections[_iExample2];
            var minInfluence = Number.POSITIVE_INFINITY;
            for (var jExample = 0; jExample < nExamples; ++jExample) {
              if (_iExample2 === jExample) {
                continue;
              }
              var directionJ = exampleDirections[jExample];
              var precomputedDataIndex = PRECOMPUTED_VIJ_DATA_STRIDE * (nExamples * _iExample2 + jExample);
              var vIJMag = precomputedVIJs[precomputedDataIndex + 0],
                vIJAnglePrecomputed = precomputedVIJs[precomputedDataIndex + 1],
                averagedMagnitude = precomputedVIJs[precomputedDataIndex + 2];
              var vIJAngle = vIJAnglePrecomputed;
              var vIXAngle = vIXAngles[_iExample2];
              if (Vec2.equals(_directionI, Vec2.ZERO)) {
                vIJAngle = vIXAngles[jExample];
              } else if (Vec2.equals(directionJ, Vec2.ZERO)) {
                vIJAngle = vIXAngles[_iExample2];
              } else if (Vec2.equals(vX, Vec2.ZERO)) {
                vIXAngle = vIJAngle;
              }
              var vIJ = Vec2.set(cacheVIJ, vIJMag, vIJAngle);
              var vIX = Vec2.set(cacheVIX, (magnitudeX - magnitudeI) / averagedMagnitude, vIXAngle);
              var influence = 1.0 - Vec2.dot(vIX, vIJ) / Vec2.lengthSqr(vIJ);
              if (influence <= 0) {
                minInfluence = 0.0;
                break;
              }
              minInfluence = Math.min(minInfluence, influence);
            }
            weights[_iExample2] = minInfluence;
            totalWeight += minInfluence;
          }
          if (totalWeight > 0) {
            for (var _iExample3 = 0; _iExample3 < nExamples; ++_iExample3) {
              weights[_iExample3] /= totalWeight;
            }
          } else {
            var averaged = 1.0 / nExamples;
            for (var _iExample4 = 0; _iExample4 < nExamples; ++_iExample4) {
              weights[_iExample4] = averaged;
            }
          }
        };
        return PolarSpaceGradientBandInterpolator2D;
      }();
      PolarSpaceGradientBandInterpolator2D._CACHE_INPUT_DIRECTION = new Vec2();
      PolarSpaceGradientBandInterpolator2D._CACHE_VIJ = new Vec2();
      PolarSpaceGradientBandInterpolator2D._CACHE_VIX = new Vec2();
      PolarSpaceGradientBandInterpolator2D._ANGLE_MULTIPLIER = 1.0;
      function signedAngle(v1, v2) {
        var angle = Vec2.angle(v1, v2);
        var determinate = v1.x * v2.y - v1.y * v2.x;
        return determinate < 0 ? -angle : angle;
      }

      var _dec$1e, _class$1c, _class2$17, _initializer$$, _dec2$15, _class4$9, _class5$b, _initializer2$Q, _initializer3$y, _initializer4$o, _initializer5$h, _class6$3;
      var ccclass$9 = ccclass$n,
        serializable$7 = serializable$j;
      var Algorithm;
      (function (Algorithm) {
        Algorithm[Algorithm["SIMPLE_DIRECTIONAL"] = 0] = "SIMPLE_DIRECTIONAL";
        Algorithm[Algorithm["FREEFORM_CARTESIAN"] = 1] = "FREEFORM_CARTESIAN";
        Algorithm[Algorithm["FREEFORM_DIRECTIONAL"] = 2] = "FREEFORM_DIRECTIONAL";
      })(Algorithm || (Algorithm = {}));
      ccenum(Algorithm);
      var AnimationBlend2DItem = (_dec$1e = ccclass$9(CLASS_NAME_PREFIX_ANIM + "AnimationBlend2DItem"), _dec$1e(_class$1c = (_class2$17 = function (_AnimationBlendItem) {
        _inheritsLoose(AnimationBlend2DItem, _AnimationBlendItem);
        function AnimationBlend2DItem() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _AnimationBlendItem.call.apply(_AnimationBlendItem, [this].concat(args)) || this;
          _this.threshold = _initializer$$ && _initializer$$();
          return _this;
        }
        var _proto = AnimationBlend2DItem.prototype;
        _proto.clone = function clone() {
          var that = new AnimationBlend2DItem();
          this._copyTo(that);
          return that;
        };
        _proto._copyTo = function _copyTo(that) {
          _AnimationBlendItem.prototype._copyTo.call(this, that);
          Vec2.copy(that.threshold, this.threshold);
          return that;
        };
        return AnimationBlend2DItem;
      }(AnimationBlendItem), (_initializer$$ = applyDecoratedInitializer(_class2$17.prototype, "threshold", [serializable$7], function () {
        return new Vec2();
      })), _class2$17)) || _class$1c);
      var AnimationBlend2D = (_dec2$15 = ccclass$9('cc.animation.AnimationBlend2D'), _dec2$15(_class4$9 = (_class5$b = (_class6$3 = function (_AnimationBlend) {
        _inheritsLoose(AnimationBlend2D, _AnimationBlend);
        function AnimationBlend2D() {
          var _this2;
          for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
            args[_key2] = arguments[_key2];
          }
          _this2 = _AnimationBlend.call.apply(_AnimationBlend, [this].concat(args)) || this;
          _this2._items = _initializer2$Q && _initializer2$Q();
          _this2.paramX = _initializer3$y && _initializer3$y();
          _this2.paramY = _initializer4$o && _initializer4$o();
          _this2._algorithm = _initializer5$h && _initializer5$h();
          _this2._polarSpaceGBI = undefined;
          return _this2;
        }
        var _proto2 = AnimationBlend2D.prototype;
        _proto2.__callOnAfterDeserializeRecursive = function __callOnAfterDeserializeRecursive() {
          this._tryReconstructPolarSpaceInterpolator();
        };
        _proto2.clone = function clone() {
          var that = new AnimationBlend2D();
          this.copyTo(that);
          that._items = this._items.map(function (item) {
            var _item$clone;
            return (_item$clone = item === null || item === void 0 ? void 0 : item.clone()) !== null && _item$clone !== void 0 ? _item$clone : null;
          });
          that.paramX = this.paramX.clone();
          that.paramY = this.paramY.clone();
          that.algorithm = this._algorithm;
          return that;
        };
        _proto2[createEval] = function (context, ignoreEmbeddedPlayers) {
          var algorithm = this.algorithm;
          var evaluation;
          switch (algorithm) {
            case Algorithm.FREEFORM_DIRECTIONAL:
              assertIsTrue(this._polarSpaceGBI, "The polar space interpolator is not setup correctly!");
              evaluation = new PolarSpaceGradientBandBlend2DEval(context, ignoreEmbeddedPlayers, this, this._items, this._polarSpaceGBI, [0.0, 0.0]);
              break;
            default:
              assertIsTrue(false);
            case Algorithm.SIMPLE_DIRECTIONAL:
            case Algorithm.FREEFORM_CARTESIAN:
              evaluation = new AnimationBlend2DEval(context, ignoreEmbeddedPlayers, this, this._items, this._items.map(function (_ref) {
                var threshold = _ref.threshold;
                return threshold;
              }), algorithm, [0.0, 0.0]);
              break;
          }
          var initialValueX = bindOr(context, this.paramX, VariableType.FLOAT, evaluation.setInput, evaluation, 0);
          var initialValueY = bindOr(context, this.paramY, VariableType.FLOAT, evaluation.setInput, evaluation, 1);
          evaluation.setInput(initialValueX, 0);
          evaluation.setInput(initialValueY, 1);
          return evaluation;
        };
        _proto2._tryReconstructPolarSpaceInterpolator = function _tryReconstructPolarSpaceInterpolator() {
          if (this._algorithm === Algorithm.FREEFORM_DIRECTIONAL) {
            this._polarSpaceGBI = new PolarSpaceGradientBandInterpolator2D(this._items.map(function (item) {
              return item.threshold;
            }));
          } else {
            this._polarSpaceGBI = undefined;
          }
        };
        _createClass(AnimationBlend2D, [{
          key: "algorithm",
          get: function get() {
            return this._algorithm;
          },
          set: function set(value) {
            if (value === this._algorithm) {
              return;
            }
            this._algorithm = value;
            this._tryReconstructPolarSpaceInterpolator();
          }
        }, {
          key: "items",
          get: function get() {
            return this._items;
          },
          set: function set(items) {
            this._items = Array.from(items);
            this._tryReconstructPolarSpaceInterpolator();
          }
        }]);
        return AnimationBlend2D;
      }(AnimationBlend), _class6$3.Algorithm = Algorithm, _class6$3.Item = AnimationBlend2DItem, _class6$3), (_initializer2$Q = applyDecoratedInitializer(_class5$b.prototype, "_items", [serializable$7], function () {
        return [];
      }), _initializer3$y = applyDecoratedInitializer(_class5$b.prototype, "paramX", [serializable$7], function () {
        return new BindableNumber();
      }), _initializer4$o = applyDecoratedInitializer(_class5$b.prototype, "paramY", [serializable$7], function () {
        return new BindableNumber();
      }), _initializer5$h = applyDecoratedInitializer(_class5$b.prototype, "_algorithm", [serializable$7], function () {
        return Algorithm.SIMPLE_DIRECTIONAL;
      })), _class5$b)) || _class4$9);
      var AnimationBlend2DEval = function (_AnimationBlendEval) {
        _inheritsLoose(AnimationBlend2DEval, _AnimationBlendEval);
        function AnimationBlend2DEval(context, ignoreEmbeddedPlayers, base, items, thresholds, algorithm, inputs) {
          var _this3;
          _this3 = _AnimationBlendEval.call(this, context, ignoreEmbeddedPlayers, base, items, inputs) || this;
          _this3._thresholds = void 0;
          _this3._algorithm = void 0;
          _this3._value = new Vec2();
          _this3._thresholds = thresholds;
          _this3._algorithm = algorithm;
          _this3.doEval();
          return _this3;
        }
        var _proto3 = AnimationBlend2DEval.prototype;
        _proto3.eval = function _eval(weights, _ref2) {
          var x = _ref2[0],
            y = _ref2[1];
          Vec2.set(this._value, x, y);
          weights.fill(0);
          switch (this._algorithm) {
            case Algorithm.SIMPLE_DIRECTIONAL:
              blendSimpleDirectional(weights, this._thresholds, this._value);
              break;
            case Algorithm.FREEFORM_CARTESIAN:
              sampleFreeformCartesian(weights, this._thresholds, this._value);
              break;
          }
        };
        return AnimationBlend2DEval;
      }(AnimationBlendEval);
      var PolarSpaceGradientBandBlend2DEval = function (_AnimationBlendEval2) {
        _inheritsLoose(PolarSpaceGradientBandBlend2DEval, _AnimationBlendEval2);
        function PolarSpaceGradientBandBlend2DEval(context, ignoreEmbeddedPlayers, base, items, interpolator, inputs) {
          var _this4;
          _this4 = _AnimationBlendEval2.call(this, context, ignoreEmbeddedPlayers, base, items, inputs) || this;
          _this4._interpolator = void 0;
          _this4._value = new Vec2();
          _this4._interpolator = interpolator;
          _this4.doEval();
          return _this4;
        }
        var _proto4 = PolarSpaceGradientBandBlend2DEval.prototype;
        _proto4.eval = function _eval(weights, _ref3) {
          var x = _ref3[0],
            y = _ref3[1];
          Vec2.set(this._value, x, y);
          weights.fill(0);
          this._interpolator.interpolate(weights, this._value);
        };
        return PolarSpaceGradientBandBlend2DEval;
      }(AnimationBlendEval);

      var _dec$1d, _class$1b, _class2$16, _initializer$_, _dec2$14, _class4$8, _class5$a, _initializer2$P, _class6$2;
      var ccclass$8 = ccclass$n,
        serializable$6 = serializable$j;
      var AnimationBlendDirectItem = (_dec$1d = ccclass$8(CLASS_NAME_PREFIX_ANIM + "AnimationBlendDirectItem"), _dec$1d(_class$1b = (_class2$16 = function (_AnimationBlendItem) {
        _inheritsLoose(AnimationBlendDirectItem, _AnimationBlendItem);
        function AnimationBlendDirectItem() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _AnimationBlendItem.call.apply(_AnimationBlendItem, [this].concat(args)) || this;
          _this.weight = _initializer$_ && _initializer$_();
          return _this;
        }
        var _proto = AnimationBlendDirectItem.prototype;
        _proto.clone = function clone() {
          var that = new AnimationBlendDirectItem();
          this._copyTo(that);
          return that;
        };
        _proto._copyTo = function _copyTo(that) {
          _AnimationBlendItem.prototype._copyTo.call(this, that);
          that.weight = this.weight;
          return that;
        };
        return AnimationBlendDirectItem;
      }(AnimationBlendItem), (_initializer$_ = applyDecoratedInitializer(_class2$16.prototype, "weight", [serializable$6], function () {
        return new BindableNumber(0.0);
      })), _class2$16)) || _class$1b);
      (_dec2$14 = ccclass$8('cc.animation.AnimationBlendDirect'), _dec2$14(_class4$8 = (_class5$a = (_class6$2 = function (_AnimationBlend) {
        _inheritsLoose(AnimationBlendDirect, _AnimationBlend);
        function AnimationBlendDirect() {
          var _this2;
          for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
            args[_key2] = arguments[_key2];
          }
          _this2 = _AnimationBlend.call.apply(_AnimationBlend, [this].concat(args)) || this;
          _this2._items = _initializer2$P && _initializer2$P();
          return _this2;
        }
        var _proto2 = AnimationBlendDirect.prototype;
        _proto2.clone = function clone() {
          var that = new AnimationBlendDirect();
          this.copyTo(that);
          that._items = this._items.map(function (item) {
            var _item$clone;
            return (_item$clone = item === null || item === void 0 ? void 0 : item.clone()) !== null && _item$clone !== void 0 ? _item$clone : null;
          });
          return that;
        };
        _proto2[createEval] = function (context, ignoreEmbeddedPlayers) {
          var myEval = new AnimationBlendDirectEval(context, ignoreEmbeddedPlayers, this, this._items, new Array(this._items.length).fill(0.0));
          for (var iItem = 0; iItem < this._items.length; ++iItem) {
            var item = this._items[iItem];
            var initialValue = bindOr(context, item.weight, VariableType.FLOAT, myEval.setInput, myEval, iItem);
            myEval.setInput(initialValue, iItem);
          }
          return myEval;
        };
        _createClass(AnimationBlendDirect, [{
          key: "items",
          get: function get() {
            return this._items;
          },
          set: function set(value) {
            this._items = Array.from(value);
          }
        }]);
        return AnimationBlendDirect;
      }(AnimationBlend), _class6$2.Item = AnimationBlendDirectItem, _class6$2), (_initializer2$P = applyDecoratedInitializer(_class5$a.prototype, "_items", [serializable$6], function () {
        return [];
      })), _class5$a)) || _class4$8);
      var AnimationBlendDirectEval = function (_AnimationBlendEval) {
        _inheritsLoose(AnimationBlendDirectEval, _AnimationBlendEval);
        function AnimationBlendDirectEval() {
          var _this3;
          for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
            args[_key3] = arguments[_key3];
          }
          _this3 = _AnimationBlendEval.call.apply(_AnimationBlendEval, [this].concat(args)) || this;
          _this3.doEval();
          return _this3;
        }
        var _proto3 = AnimationBlendDirectEval.prototype;
        _proto3.eval = function _eval(weights, inputs) {
          var nChildren = weights.length;
          for (var iChild = 0; iChild < nChildren; ++iChild) {
            weights[iChild] = inputs[iChild];
          }
        };
        return AnimationBlendDirectEval;
      }(AnimationBlendEval);

      var _dec$1c, _class$1a, _class2$15, _initializer$Z, _initializer2$O, _dec2$13, _dec3$Q, _class4$7, _class5$9, _initializer3$x;
      var JointMask = (_dec$1c = ccclass$n('cc.JointMask'), _dec$1c(_class$1a = (_class2$15 = function JointMask() {
        this.path = _initializer$Z && _initializer$Z();
        this.enabled = _initializer2$O && _initializer2$O();
      }, (_initializer$Z = applyDecoratedInitializer(_class2$15.prototype, "path", [serializable$j], function () {
        return '';
      }), _initializer2$O = applyDecoratedInitializer(_class2$15.prototype, "enabled", [serializable$j], function () {
        return true;
      })), _class2$15)) || _class$1a);
      var AnimationMask = (_dec2$13 = ccclass$n(CLASS_NAME_PREFIX_ANIM + "AnimationMask"), _dec3$Q = type$7(JointMask), _dec2$13(_class4$7 = (_class5$9 = function (_Asset) {
        _inheritsLoose(AnimationMask, _Asset);
        function AnimationMask() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Asset.call.apply(_Asset, [this].concat(args)) || this;
          _this._jointMasks = _initializer3$x && _initializer3$x();
          return _this;
        }
        var _proto = AnimationMask.prototype;
        _proto.addJoint = function addJoint(path, enabled) {
          this.removeJoint(path);
          var info = new JointMask();
          info.path = path;
          info.enabled = enabled;
          this._jointMasks.push(info);
        };
        _proto.removeJoint = function removeJoint(removal) {
          removeIf(this._jointMasks, function (_ref) {
            var path = _ref.path;
            return path === removal;
          });
        };
        _proto.clear = function clear() {
          this._jointMasks.length = 0;
        };
        _proto.filterDisabledNodes = function filterDisabledNodes(root) {
          var jointMasks = this._jointMasks;
          var nJointMasks = jointMasks.length;
          var disabledNodes = new Set();
          for (var iJointMask = 0; iJointMask < nJointMasks; ++iJointMask) {
            var _jointMasks$iJointMas = jointMasks[iJointMask],
              path = _jointMasks$iJointMas.path,
              enabled = _jointMasks$iJointMas.enabled;
            if (enabled) {
              continue;
            }
            var node = root.getChildByPath(path);
            if (node) {
              disabledNodes.add(node);
            }
          }
          return disabledNodes;
        };
        _proto.isExcluded = function isExcluded(path) {
          var _this$_jointMasks$fin, _this$_jointMasks$fin2;
          return !((_this$_jointMasks$fin = (_this$_jointMasks$fin2 = this._jointMasks.find(function (_ref2) {
            var p = _ref2.path;
            return p === path;
          })) === null || _this$_jointMasks$fin2 === void 0 ? void 0 : _this$_jointMasks$fin2.enabled) !== null && _this$_jointMasks$fin !== void 0 ? _this$_jointMasks$fin : true);
        };
        _createClass(AnimationMask, [{
          key: "joints",
          get: function get() {
            return this._jointMasks;
          },
          set: function set(value) {
            this.clear();
            for (var _iterator = _createForOfIteratorHelperLoose(value), _step; !(_step = _iterator()).done;) {
              var joint = _step.value;
              this.addJoint(joint.path, joint.enabled);
            }
          }
        }]);
        return AnimationMask;
      }(Asset), (_initializer3$x = applyDecoratedInitializer(_class5$9.prototype, "_jointMasks", [serializable$j], function () {
        return [];
      }), _applyDecoratedDescriptor(_class5$9.prototype, "joints", [_dec3$Q], Object.getOwnPropertyDescriptor(_class5$9.prototype, "joints"), _class5$9.prototype)), _class5$9)) || _class4$7);

      var _Symbol$iterator;
      var _dec$1b, _class$19, _class2$14, _initializer$Y, _initializer2$N, _dec2$12, _dec3$P, _class4$6, _class5$8, _initializer3$w, _initializer4$n, _dec4$D, _class7$4, _class8$4, _initializer5$g;
      var ClipOverrideEntry = (_dec$1b = ccclass$n(CLASS_NAME_PREFIX_ANIM + "ClipOverrideEntry"), _dec$1b(_class$19 = (_class2$14 = function ClipOverrideEntry() {
        this.original = _initializer$Y && _initializer$Y();
        this.substitution = _initializer2$N && _initializer2$N();
      }, (_initializer$Y = applyDecoratedInitializer(_class2$14.prototype, "original", [serializable$j], function () {
        return null;
      }), _initializer2$N = applyDecoratedInitializer(_class2$14.prototype, "substitution", [serializable$j], function () {
        return null;
      })), _class2$14)) || _class$19);
      var AnimationGraphVariant = (_dec2$12 = ccclass$n(CLASS_NAME_PREFIX_ANIM + "AnimationGraphVariant"), _dec3$P = type$7(AnimationGraph), _dec2$12(_class4$6 = (_class5$8 = function (_AnimationGraphLike) {
        _inheritsLoose(AnimationGraphVariant, _AnimationGraphLike);
        function AnimationGraphVariant() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _AnimationGraphLike.call.apply(_AnimationGraphLike, [this].concat(args)) || this;
          _this._graph = _initializer3$w && _initializer3$w();
          _this._clipOverrides = _initializer4$n && _initializer4$n();
          return _this;
        }
        _createClass(AnimationGraphVariant, [{
          key: "original",
          get: function get() {
            return this._graph;
          },
          set: function set(value) {
            this._graph = value;
          }
        }, {
          key: "clipOverrides",
          get: function get() {
            return this._clipOverrides;
          }
        }]);
        return AnimationGraphVariant;
      }(AnimationGraphLike), (_applyDecoratedDescriptor(_class5$8.prototype, "original", [_dec3$P], Object.getOwnPropertyDescriptor(_class5$8.prototype, "original"), _class5$8.prototype), _initializer3$w = applyDecoratedInitializer(_class5$8.prototype, "_graph", [serializable$j], function () {
        return null;
      }), _initializer4$n = applyDecoratedInitializer(_class5$8.prototype, "_clipOverrides", [serializable$j], function () {
        return new ClipOverrideMap();
      })), _class5$8)) || _class4$6);
      var ClipOverrideMap = (_dec4$D = ccclass$n(CLASS_NAME_PREFIX_ANIM + "ClipOverrideMap"), _dec4$D(_class7$4 = (_class8$4 = (_Symbol$iterator = Symbol.iterator, function () {
        function ClipOverrideMap() {
          this._entries = _initializer5$g && _initializer5$g();
        }
        var _proto = ClipOverrideMap.prototype;
        _proto[_Symbol$iterator] = function () {
          return this._entries[Symbol.iterator]();
        };
        _proto.has = function has(original) {
          return !!this._entries.find(function (_ref) {
            var o = _ref.original;
            return o === original;
          });
        };
        _proto.get = function get(original) {
          var entry = this._entries.find(function (_ref2) {
            var o = _ref2.original;
            return o === original;
          });
          return entry === null || entry === void 0 ? void 0 : entry.substitution;
        };
        _proto.set = function set(original, substitution) {
          var entry = this._entries.find(function (_ref3) {
            var o = _ref3.original;
            return o === original;
          });
          if (entry) {
            entry.substitution = substitution;
          } else {
            var newEntry = new ClipOverrideEntry();
            newEntry.original = original;
            newEntry.substitution = substitution;
            this._entries.push(newEntry);
          }
        };
        _proto["delete"] = function _delete(original) {
          removeIf(this._entries, function (_ref4) {
            var o = _ref4.original;
            return o === original;
          });
        };
        _proto.clear = function clear() {
          this._entries.length = 0;
        };
        _createClass(ClipOverrideMap, [{
          key: "size",
          get: function get() {
            return this._entries.length;
          }
        }]);
        return ClipOverrideMap;
      }()), (_initializer5$g = applyDecoratedInitializer(_class8$4.prototype, "_entries", [serializable$j], function () {
        return [];
      })), _class8$4)) || _class7$4);

      var POSE_GRAPH_NODE_MENU_PREFIX_POSE = "i18n:ENGINE.animation_graph.pose_graph_node_sub_categories.pose_nodes/";
      var POSE_GRAPH_NODE_MENU_PREFIX_POSE_BLEND = POSE_GRAPH_NODE_MENU_PREFIX_POSE + "/" + "i18n:ENGINE.animation_graph.pose_graph_node_sub_categories.pose_nodes_blend/";

      var _dec$1a, _dec2$11, _dec3$O, _dec4$C, _class$18, _class2$13, _initializer$X;
      var createNodeFactory$1 = {
        listEntries: function listEntries(context) {
          return [].concat(context.animationGraph.layers[context.layerIndex].stashes()).map(function (_ref) {
            var stashId = _ref[0];
            return {
              arg: stashId,
              menu: stashId
            };
          });
        },
        create: function create(arg) {
          var node = new PoseNodeUseStashedPose();
          node.stashName = arg;
          return node;
        }
      };
      var PoseNodeUseStashedPose = (_dec$1a = ccclass$n(CLASS_NAME_PREFIX_ANIM + "PoseNodeUseStashedPose"), _dec2$11 = poseGraphNodeCategory(POSE_GRAPH_NODE_MENU_PREFIX_POSE), _dec3$O = poseGraphCreateNodeFactory(createNodeFactory$1), _dec4$C = poseGraphNodeAppearance({
        inline: true
      }), _dec$1a(_class$18 = _dec2$11(_class$18 = _dec3$O(_class$18 = _dec4$C(_class$18 = (_class2$13 = function (_PoseNode) {
        _inheritsLoose(PoseNodeUseStashedPose, _PoseNode);
        function PoseNodeUseStashedPose() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _PoseNode.call.apply(_PoseNode, [this].concat(args)) || this;
          _this.stashName = _initializer$X && _initializer$X();
          _this._runtimeStash = undefined;
          return _this;
        }
        var _proto = PoseNodeUseStashedPose.prototype;
        _proto.bind = function bind(context) {
          var stashName = this.stashName;
          if (!stashName) {
            return;
          }
          var runtimeStash = context.stashView.bindStash(stashName);
          this._runtimeStash = runtimeStash;
        };
        _proto.settle = function settle(context) {};
        _proto.reenter = function reenter() {
          var _this$_runtimeStash;
          (_this$_runtimeStash = this._runtimeStash) === null || _this$_runtimeStash === void 0 ? void 0 : _this$_runtimeStash.reenter();
        };
        _proto.doUpdate = function doUpdate(context) {
          var _this$_runtimeStash2;
          (_this$_runtimeStash2 = this._runtimeStash) === null || _this$_runtimeStash2 === void 0 ? void 0 : _this$_runtimeStash2.requestUpdate(context);
        };
        _proto.doEvaluate = function doEvaluate(context) {
          var _this$_runtimeStash$e, _this$_runtimeStash3;
          return (_this$_runtimeStash$e = (_this$_runtimeStash3 = this._runtimeStash) === null || _this$_runtimeStash3 === void 0 ? void 0 : _this$_runtimeStash3.evaluate(context)) !== null && _this$_runtimeStash$e !== void 0 ? _this$_runtimeStash$e : context.pushDefaultedPose();
        };
        return PoseNodeUseStashedPose;
      }(PoseNode), (_initializer$X = applyDecoratedInitializer(_class2$13.prototype, "stashName", [serializable$j], function () {
        return '';
      })), _class2$13)) || _class$18) || _class$18) || _class$18) || _class$18);

      var _dec$19, _class$17, _class2$12, _initializer$W, _initializer2$M, _class3$o;
      var ccclass$7 = ccclass$n,
        serializable$5 = serializable$j;
      var UnaryOperator;
      (function (UnaryOperator) {
        UnaryOperator[UnaryOperator["TRUTHY"] = 0] = "TRUTHY";
        UnaryOperator[UnaryOperator["FALSY"] = 1] = "FALSY";
      })(UnaryOperator || (UnaryOperator = {}));
      (_dec$19 = ccclass$7(CLASS_NAME_PREFIX_ANIM + "UnaryCondition"), _dec$19(_class$17 = (_class2$12 = (_class3$o = function () {
        function UnaryCondition() {
          this.operator = _initializer$W && _initializer$W();
          this.operand = _initializer2$M && _initializer2$M();
        }
        var _proto = UnaryCondition.prototype;
        _proto.clone = function clone() {
          var that = new UnaryCondition();
          that.operator = this.operator;
          that.operand = this.operand.clone();
          return that;
        };
        _proto[createEval] = function (context) {
          var operator = this.operator,
            operand = this.operand;
          var evaluation = new UnaryConditionEval(operator, false);
          var value = bindOr(context, operand, VariableType.BOOLEAN, evaluation.setOperand, evaluation);
          evaluation.reset(value);
          return evaluation;
        };
        return UnaryCondition;
      }(), _class3$o.Operator = UnaryOperator, _class3$o), (_initializer$W = applyDecoratedInitializer(_class2$12.prototype, "operator", [serializable$5], function () {
        return UnaryOperator.TRUTHY;
      }), _initializer2$M = applyDecoratedInitializer(_class2$12.prototype, "operand", [serializable$5], function () {
        return new BindableBoolean();
      })), _class2$12)) || _class$17);
      var UnaryConditionEval = function () {
        function UnaryConditionEval(operator, operand) {
          this._operator = operator;
          this._operand = operand;
          this._eval();
        }
        var _proto2 = UnaryConditionEval.prototype;
        _proto2.reset = function reset(value) {
          this.setOperand(value);
        };
        _proto2.setOperand = function setOperand(value) {
          this._operand = value;
          this._eval();
        };
        _proto2.eval = function _eval() {
          return this._result;
        };
        _proto2._eval = function _eval() {
          var operand = this._operand;
          switch (this._operator) {
            default:
            case UnaryOperator.TRUTHY:
              this._result = !!operand;
              break;
            case UnaryOperator.FALSY:
              this._result = !operand;
              break;
          }
        };
        return UnaryConditionEval;
      }();

      var TCBindingValueType;
      (function (TCBindingValueType) {
        TCBindingValueType[TCBindingValueType["FLOAT"] = 0] = "FLOAT";
        TCBindingValueType[TCBindingValueType["INTEGER"] = 3] = "INTEGER";
      })(TCBindingValueType || (TCBindingValueType = {}));
      var TCBinding = function TCBinding() {};

      var provide = function provide() {
        for (var _len = arguments.length, valueTypes = new Array(_len), _key = 0; _key < _len; _key++) {
          valueTypes[_key] = arguments[_key];
        }
        return function () {} ;
      };
      var TCBindingTransitionSourceFilter;
      (function (TCBindingTransitionSourceFilter) {
        TCBindingTransitionSourceFilter[TCBindingTransitionSourceFilter["MOTION"] = 1] = "MOTION";
        TCBindingTransitionSourceFilter[TCBindingTransitionSourceFilter["POSE"] = 2] = "POSE";
        TCBindingTransitionSourceFilter[TCBindingTransitionSourceFilter["EMPTY"] = 4] = "EMPTY";
        TCBindingTransitionSourceFilter[TCBindingTransitionSourceFilter["WEIGHTED"] = 7] = "WEIGHTED";
      })(TCBindingTransitionSourceFilter || (TCBindingTransitionSourceFilter = {}));
      var support = function support(transitionSourceFilter) {
        return function () {} ;
      };

      var _dec$18, _dec2$10, _class$16, _class2$11, _initializer$V, _initializer2$L;
      var ccclass$6 = ccclass$n,
        serializable$4 = serializable$j;
      var TCVariableBinding = (_dec$18 = ccclass$6(CLASS_NAME_PREFIX_ANIM + "TCVariableBinding"), _dec2$10 = provide(TCBindingValueType.FLOAT, TCBindingValueType.INTEGER), _dec$18(_class$16 = _dec2$10(_class$16 = (_class2$11 = function (_TCBinding) {
        _inheritsLoose(TCVariableBinding, _TCBinding);
        function TCVariableBinding() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _TCBinding.call.apply(_TCBinding, [this].concat(args)) || this;
          _this.type = _initializer$V && _initializer$V();
          _this.variableName = _initializer2$L && _initializer2$L();
          return _this;
        }
        var _proto = TCVariableBinding.prototype;
        _proto.getValueType = function getValueType() {
          return this.type;
        };
        _proto.bind = function bind(context) {
          var varInstance = context.getVar(this.variableName);
          if (!varInstance) {
            return undefined;
          }
          return new TCVariableBindingEvaluation(varInstance);
        };
        return TCVariableBinding;
      }(TCBinding), (_initializer$V = applyDecoratedInitializer(_class2$11.prototype, "type", [serializable$4, editorOnly], function () {
        return TCBindingValueType.FLOAT;
      }), _initializer2$L = applyDecoratedInitializer(_class2$11.prototype, "variableName", [serializable$4], function () {
        return '';
      })), _class2$11)) || _class$16) || _class$16);
      var TCVariableBindingEvaluation = function () {
        function TCVariableBindingEvaluation(_varInstance) {
          this._varInstance = _varInstance;
        }
        var _proto2 = TCVariableBindingEvaluation.prototype;
        _proto2.evaluate = function evaluate() {
          return this._varInstance.value;
        };
        return TCVariableBindingEvaluation;
      }();

      var _dec$17, _dec2$$, _class$15, _class2$10, _initializer$U;
      var ccclass$5 = ccclass$n,
        serializable$3 = serializable$j;
      (_dec$17 = ccclass$5(CLASS_NAME_PREFIX_ANIM + "TCAuxiliaryCurveBinding"), _dec2$$ = provide(TCBindingValueType.FLOAT), _dec$17(_class$15 = _dec2$$(_class$15 = (_class2$10 = function (_TCBinding) {
        _inheritsLoose(TCAuxiliaryCurveBinding, _TCBinding);
        function TCAuxiliaryCurveBinding() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _TCBinding.call.apply(_TCBinding, [this].concat(args)) || this;
          _this.curveName = _initializer$U && _initializer$U();
          return _this;
        }
        var _proto = TCAuxiliaryCurveBinding.prototype;
        _proto.getValueType = function getValueType() {
          return TCBindingValueType.FLOAT;
        };
        _proto.bind = function bind(context) {
          var view = context.getEvaluationTimeAuxiliaryCurveView();
          return new TCAuxiliaryCurveBindingEvaluation(view, this.curveName);
        };
        return TCAuxiliaryCurveBinding;
      }(TCBinding), (_initializer$U = applyDecoratedInitializer(_class2$10.prototype, "curveName", [serializable$3], function () {
        return '';
      })), _class2$10)) || _class$15) || _class$15);
      var TCAuxiliaryCurveBindingEvaluation = function () {
        function TCAuxiliaryCurveBindingEvaluation(_view, _curveName) {
          this._view = _view;
          this._curveName = _curveName;
        }
        var _proto2 = TCAuxiliaryCurveBindingEvaluation.prototype;
        _proto2.evaluate = function evaluate() {
          return this._view.get(this._curveName);
        };
        return TCAuxiliaryCurveBindingEvaluation;
      }();

      var _dec$16, _dec2$_, _dec3$N, _class$14;
      var ccclass$4 = ccclass$n;
      (_dec$16 = ccclass$4(CLASS_NAME_PREFIX_ANIM + "TCStateWeightBinding"), _dec2$_ = provide(TCBindingValueType.FLOAT), _dec3$N = support(TCBindingTransitionSourceFilter.WEIGHTED), _dec$16(_class$14 = _dec2$_(_class$14 = _dec3$N(_class$14 = function (_TCBinding) {
        _inheritsLoose(TCStateWeightBinding, _TCBinding);
        function TCStateWeightBinding() {
          return _TCBinding.apply(this, arguments) || this;
        }
        var _proto = TCStateWeightBinding.prototype;
        _proto.getValueType = function getValueType() {
          return TCBindingValueType.FLOAT;
        };
        _proto.bind = function bind(_context) {
          return new TCStateWeightBindingEvaluation();
        };
        return TCStateWeightBinding;
      }(TCBinding)) || _class$14) || _class$14) || _class$14);
      var TCStateWeightBindingEvaluation = function () {
        function TCStateWeightBindingEvaluation() {}
        var _proto2 = TCStateWeightBindingEvaluation.prototype;
        _proto2.evaluate = function evaluate(context) {
          return context.sourceStateWeight;
        };
        return TCStateWeightBindingEvaluation;
      }();

      var _dec$15, _dec2$Z, _dec3$M, _class$13;
      var ccclass$3 = ccclass$n;
      (_dec$15 = ccclass$3(CLASS_NAME_PREFIX_ANIM + "TCStateMotionTimeBinding"), _dec2$Z = provide(TCBindingValueType.FLOAT), _dec3$M = support(TCBindingTransitionSourceFilter.POSE), _dec$15(_class$13 = _dec2$Z(_class$13 = _dec3$M(_class$13 = function (_TCBinding) {
        _inheritsLoose(TCStateMotionTimeBinding, _TCBinding);
        function TCStateMotionTimeBinding() {
          return _TCBinding.apply(this, arguments) || this;
        }
        var _proto = TCStateMotionTimeBinding.prototype;
        _proto.getValueType = function getValueType() {
          return TCBindingValueType.FLOAT;
        };
        _proto.bind = function bind(_context) {
          return new TCStateMotionTimeBindingEvaluation();
        };
        return TCStateMotionTimeBinding;
      }(TCBinding)) || _class$13) || _class$13) || _class$13);
      var TCStateMotionTimeBindingEvaluation = function () {
        function TCStateMotionTimeBindingEvaluation() {}
        var _proto2 = TCStateMotionTimeBindingEvaluation.prototype;
        _proto2.evaluate = function evaluate(context) {
          return context.sourceStateMotionTimeNormalized;
        };
        return TCStateMotionTimeBindingEvaluation;
      }();

      var _dec$14, _class$12, _class2$$, _initializer$T, _initializer2$K, _initializer3$v, _initializer4$m, _class3$n;
      var ccclass$2 = ccclass$n,
        serializable$2 = serializable$j;
      var BinaryOperator;
      (function (BinaryOperator) {
        BinaryOperator[BinaryOperator["EQUAL_TO"] = 0] = "EQUAL_TO";
        BinaryOperator[BinaryOperator["NOT_EQUAL_TO"] = 1] = "NOT_EQUAL_TO";
        BinaryOperator[BinaryOperator["LESS_THAN"] = 2] = "LESS_THAN";
        BinaryOperator[BinaryOperator["LESS_THAN_OR_EQUAL_TO"] = 3] = "LESS_THAN_OR_EQUAL_TO";
        BinaryOperator[BinaryOperator["GREATER_THAN"] = 4] = "GREATER_THAN";
        BinaryOperator[BinaryOperator["GREATER_THAN_OR_EQUAL_TO"] = 5] = "GREATER_THAN_OR_EQUAL_TO";
      })(BinaryOperator || (BinaryOperator = {}));
      (_dec$14 = ccclass$2(CLASS_NAME_PREFIX_ANIM + "BinaryCondition"), _dec$14(_class$12 = (_class2$$ = (_class3$n = function () {
        function BinaryCondition() {
          this.operator = _initializer$T && _initializer$T();
          this.lhs = _initializer2$K && _initializer2$K();
          this.lhsBinding = _initializer3$v && _initializer3$v();
          this.rhs = _initializer4$m && _initializer4$m();
        }
        var _proto = BinaryCondition.prototype;
        _proto.clone = function clone() {
          var that = new BinaryCondition();
          that.operator = this.operator;
          that.lhs = this.lhs;
          that.lhsBinding = instantiate(this.lhsBinding);
          that.rhs = this.rhs;
          return that;
        };
        _proto[createEval] = function (context) {
          var _this$lhsBinding;
          var lhsBindingEvaluation = (_this$lhsBinding = this.lhsBinding) === null || _this$lhsBinding === void 0 ? void 0 : _this$lhsBinding.bind(context);
          var binaryConditionEval = new BinaryConditionEval(this.operator, this.lhs, this.rhs, lhsBindingEvaluation);
          return binaryConditionEval;
        };
        return BinaryCondition;
      }(), _class3$n.Operator = BinaryOperator, _class3$n), (_initializer$T = applyDecoratedInitializer(_class2$$.prototype, "operator", [serializable$2], function () {
        return BinaryOperator.EQUAL_TO;
      }), _initializer2$K = applyDecoratedInitializer(_class2$$.prototype, "lhs", [serializable$2], function () {
        return 0.0;
      }), _initializer3$v = applyDecoratedInitializer(_class2$$.prototype, "lhsBinding", [serializable$2], function () {
        return new TCVariableBinding();
      }), _initializer4$m = applyDecoratedInitializer(_class2$$.prototype, "rhs", [serializable$2], function () {
        return 0.0;
      })), _class2$$)) || _class$12);
      var BinaryConditionEval = function () {
        function BinaryConditionEval(_operator, lhsValue, rhsValue, _lhsBindingEvaluation) {
          this._operator = _operator;
          this._lhsBindingEvaluation = _lhsBindingEvaluation;
          this._lhsValue = lhsValue;
          this._rhsValue = rhsValue;
        }
        var _proto2 = BinaryConditionEval.prototype;
        _proto2.eval = function _eval(context) {
          var _this$_lhsBindingEval, _this$_lhsBindingEval2;
          var lhsValue = (_this$_lhsBindingEval = (_this$_lhsBindingEval2 = this._lhsBindingEvaluation) === null || _this$_lhsBindingEval2 === void 0 ? void 0 : _this$_lhsBindingEval2.evaluate(context)) !== null && _this$_lhsBindingEval !== void 0 ? _this$_lhsBindingEval : this._lhsValue;
          var rhsValue = this._rhsValue;
          switch (this._operator) {
            default:
            case BinaryOperator.EQUAL_TO:
              return lhsValue === rhsValue;
            case BinaryOperator.NOT_EQUAL_TO:
              return lhsValue !== rhsValue;
            case BinaryOperator.LESS_THAN:
              return lhsValue < rhsValue;
            case BinaryOperator.LESS_THAN_OR_EQUAL_TO:
              return lhsValue <= rhsValue;
            case BinaryOperator.GREATER_THAN:
              return lhsValue > rhsValue;
            case BinaryOperator.GREATER_THAN_OR_EQUAL_TO:
              return lhsValue >= rhsValue;
          }
        };
        return BinaryConditionEval;
      }();

      var _dec$13, _class$11, _class2$_, _initializer$S;
      var ccclass$1 = ccclass$n,
        serializable$1 = serializable$j;
      var TriggerCondition = (_dec$13 = ccclass$1(CLASS_NAME_PREFIX_ANIM + "TriggerCondition"), _dec$13(_class$11 = (_class2$_ = function () {
        function TriggerCondition() {
          this.trigger = _initializer$S && _initializer$S();
        }
        var _proto = TriggerCondition.prototype;
        _proto.clone = function clone() {
          var that = new TriggerCondition();
          that.trigger = this.trigger;
          return that;
        };
        _proto[createEval] = function (context) {
          var evaluation = new TriggerConditionEval(false);
          var triggerInstance = context.getVar(this.trigger);
          if (validateVariableExistence(triggerInstance, this.trigger)) {
            validateVariableTypeTriggerLike(triggerInstance.type, this.trigger);
            evaluation.setTrigger(triggerInstance.bind(evaluation.setTrigger, evaluation));
          }
          return evaluation;
        };
        return TriggerCondition;
      }(), (_initializer$S = applyDecoratedInitializer(_class2$_.prototype, "trigger", [serializable$1], function () {
        return '';
      })), _class2$_)) || _class$11);
      var TriggerConditionEval = function () {
        function TriggerConditionEval(triggered) {
          this._triggered = false;
          this._triggered = triggered;
        }
        var _proto2 = TriggerConditionEval.prototype;
        _proto2.setTrigger = function setTrigger(trigger) {
          this._triggered = trigger;
        };
        _proto2.eval = function _eval() {
          return this._triggered;
        };
        return TriggerConditionEval;
      }();

      var _dec$12, _class$10;
      var StateMachineComponent = (_dec$12 = ccclass$n(CLASS_NAME_PREFIX_ANIM + "StateMachineComponent"), _dec$12(_class$10 = function () {
        function StateMachineComponent() {}
        var _proto = StateMachineComponent.prototype;
        _proto.onMotionStateEnter = function onMotionStateEnter(controller, motionStateStatus) {};
        _proto.onMotionStateExit = function onMotionStateExit(controller, motionStateStatus) {};
        _proto.onMotionStateUpdate = function onMotionStateUpdate(controller, motionStateStatus) {};
        _proto.onStateMachineEnter = function onStateMachineEnter(controller) {};
        _proto.onStateMachineExit = function onStateMachineExit(controller) {};
        return StateMachineComponent;
      }()) || _class$10);

      var TRANSFORM_STRIDE_IN_FLOATS = 10;
      var TRANSFORM_STRIDE_IN_BYTES = Float64Array.BYTES_PER_ELEMENT * TRANSFORM_STRIDE_IN_FLOATS;
      var ROTATION_OFFSET = 3;
      var SCALE_OFFSET = ROTATION_OFFSET + 4;
      var TransformArray = function () {
        function TransformArray(bufferOrLength, byteOffset, length_) {
          this._data = void 0;
          if (typeof bufferOrLength === 'undefined') {
            this._data = new Float64Array();
          } else if (typeof bufferOrLength === 'number') {
            this._data = new Float64Array(TRANSFORM_STRIDE_IN_FLOATS * bufferOrLength);
          } else {
            this._data = new Float64Array(bufferOrLength, byteOffset, typeof length_ === 'number' ? TRANSFORM_STRIDE_IN_FLOATS * length_ : undefined);
          }
        }
        var _proto = TransformArray.prototype;
        _proto.getTransform = function getTransform(index, out) {
          var data = this._data;
          var position = out.position,
            rotation = out.rotation,
            scale = out.scale;
          var baseOffset = TRANSFORM_STRIDE_IN_FLOATS * index;
          Vec3.fromArray(position, data, baseOffset);
          Quat.fromArray(rotation, data, baseOffset + ROTATION_OFFSET);
          Vec3.fromArray(scale, data, baseOffset + SCALE_OFFSET);
          return out;
        };
        _proto.getPosition = function getPosition(index, out) {
          var data = this._data;
          var baseOffset = TRANSFORM_STRIDE_IN_FLOATS * index;
          Vec3.fromArray(out, data, baseOffset);
          return out;
        };
        _proto.getRotation = function getRotation(index, out) {
          var data = this._data;
          var baseOffset = TRANSFORM_STRIDE_IN_FLOATS * index;
          Quat.fromArray(out, data, baseOffset + ROTATION_OFFSET);
          return out;
        };
        _proto.getScale = function getScale(index, out) {
          var data = this._data;
          var baseOffset = TRANSFORM_STRIDE_IN_FLOATS * index;
          Vec3.fromArray(out, data, baseOffset + SCALE_OFFSET);
          return out;
        };
        _proto.setTransform = function setTransform(index, value) {
          var data = this._data;
          var position = value.position,
            rotation = value.rotation,
            scale = value.scale;
          var baseOffset = TRANSFORM_STRIDE_IN_FLOATS * index;
          Vec3.toArray(data, position, baseOffset);
          Quat.toArray(data, rotation, baseOffset + ROTATION_OFFSET);
          Vec3.toArray(data, scale, baseOffset + SCALE_OFFSET);
        };
        _proto.setPosition = function setPosition(index, value) {
          var data = this._data;
          var baseOffset = TRANSFORM_STRIDE_IN_FLOATS * index;
          Vec3.toArray(data, value, baseOffset);
        };
        _proto.setRotation = function setRotation(index, value) {
          var data = this._data;
          var baseOffset = TRANSFORM_STRIDE_IN_FLOATS * index;
          Quat.toArray(data, value, baseOffset + ROTATION_OFFSET);
        };
        _proto.setScale = function setScale(index, value) {
          var data = this._data;
          var baseOffset = TRANSFORM_STRIDE_IN_FLOATS * index;
          Vec3.toArray(data, value, baseOffset + SCALE_OFFSET);
        };
        _proto.copyWithin = function copyWithin(target, start, end) {
          this._data.copyWithin(target * TRANSFORM_STRIDE_IN_FLOATS, start * TRANSFORM_STRIDE_IN_FLOATS, typeof end === 'number' ? end * TRANSFORM_STRIDE_IN_FLOATS : undefined);
        };
        _proto.fill = function fill(value, start, end) {
          var _start, _end;
          var length = this.length;
          (_start = start) !== null && _start !== void 0 ? _start : start = 0;
          (_end = end) !== null && _end !== void 0 ? _end : end = length;
          if (start >= length) {
            return;
          }
          this.setTransform(start, value);
          for (var i = start + 1; i < end; ++i) {
            this.copyWithin(i, start, start + 1);
          }
        };
        _proto.fillZero = function fillZero(start, end) {
          this._data.fill(0.0, typeof start === 'number' ? start * TRANSFORM_STRIDE_IN_FLOATS : undefined, typeof end === 'number' ? end * TRANSFORM_STRIDE_IN_FLOATS : undefined);
        };
        _proto.set = function set(transformArray, targetOffset) {
          this._data.set(transformArray._data, typeof targetOffset === 'number' ? targetOffset * TRANSFORM_STRIDE_IN_FLOATS : undefined);
        };
        _proto.slice = function slice(start, end) {
          var dataSliced = this._data.slice(typeof start === 'number' ? start * TRANSFORM_STRIDE_IN_FLOATS : undefined, typeof end === 'number' ? end * TRANSFORM_STRIDE_IN_FLOATS : undefined);
          return new TransformArray(dataSliced.buffer, dataSliced.byteOffset, dataSliced.length / TRANSFORM_STRIDE_IN_FLOATS);
        };
        _proto.copyRange = function copyRange(targetOffset, source, sourceOffset, size) {
          var sizeInFloats = TRANSFORM_STRIDE_IN_FLOATS * size;
          var targetFloats = this._data;
          var targetStartInFloats = TRANSFORM_STRIDE_IN_FLOATS * targetOffset;
          var sourceFloats = source._data;
          var sourceStartInFloats = TRANSFORM_STRIDE_IN_FLOATS * sourceOffset;
          for (var i = 0; i < sizeInFloats; ++i) {
            targetFloats[targetStartInFloats + i] = sourceFloats[sourceStartInFloats + i];
          }
        };
        _createClass(TransformArray, [{
          key: "buffer",
          get: function get() {
            return this._data.buffer;
          }
        }, {
          key: "byteLength",
          get: function get() {
            return this._data.byteLength;
          }
        }, {
          key: "byteOffset",
          get: function get() {
            return this._data.byteOffset;
          }
        }, {
          key: "length",
          get: function get() {
            return this._data.length / TRANSFORM_STRIDE_IN_FLOATS;
          }
        }], [{
          key: "BYTES_PER_ELEMENT",
          get: function get() {
            return TRANSFORM_STRIDE_IN_BYTES;
          }
        }]);
        return TransformArray;
      }();

      var allocatorPageCountTag = Symbol('[[The count of pages used by this allocator.]]' );
      var onStackPurgedTag = Symbol("[[Notify that theres is no allocator on the stack anymore.]]" );
      var SharedMemoryPage = function SharedMemoryPage(byteLength) {
        this.buffer = void 0;
        this.useCount = 0;
        this.buffer = new ArrayBuffer(byteLength);
      };
      var PagedStack = function () {
        function PagedStack(_manager, _pageSize) {
          this._locking = false;
          this._pages = [];
          this._allocatorCount = 0;
          this._manager = _manager;
          this._pageSize = _pageSize;
        }
        var _proto = PagedStack.prototype;
        _proto.debugLock = function debugLock() {
          assertIsTrue(!this._locking, "The memory is locking.");
          this._locking = true;
        };
        _proto.debugUnlock = function debugUnlock() {
          assertIsTrue(this._locking, "Wrong execution logic: the memory is not locking.");
          this._locking = false;
        };
        _proto.getPageMemory = function getPageMemory(index) {
          assertIsTrue(index >= 0 && index < this._pages.length, "Page index out of range");
          return this._pages[index].buffer;
        };
        _proto.pushPage = function pushPage(allocator) {
          var oldAllocatorPageCount = allocator[allocatorPageCountTag];
          assertIsTrue(oldAllocatorPageCount <= this._pages.length);
          if (oldAllocatorPageCount === this._pages.length) {
            this._pushNewPage();
          }
          assertIsTrue(oldAllocatorPageCount < this._pages.length);
          var page = this._pages[oldAllocatorPageCount];
          ++page.useCount;
          ++allocator[allocatorPageCountTag];
          return page;
        };
        _proto.popPage = function popPage(allocator) {
          var allocatorPageCount = allocator[allocatorPageCountTag];
          assertIsTrue(allocatorPageCount > 0);
          var allocatorLastPageIndex = allocatorPageCount - 1;
          var lastPage = this._pages[allocatorLastPageIndex];
          assertIsTrue(lastPage.useCount > 0);
          --lastPage.useCount;
          --allocator[allocatorPageCountTag];
          if (lastPage.useCount === 0) {
            assertIsTrue(allocatorLastPageIndex === this._pages.length - 1);
            this._pages.pop();
          }
        };
        _proto.createAllocator = function createAllocator(sliceSize) {
          var allocator = new SharedStackBasedAllocator(this, sliceSize);
          ++this._allocatorCount;
          return allocator;
        };
        _proto.destroyAllocator = function destroyAllocator(allocator) {
          var allocatorPageCount = allocator[allocatorPageCountTag];
          for (var iPage = 0; iPage < allocatorPageCount; ++iPage) {
            var page = this._pages[iPage];
            assertIsTrue(page.useCount > 0);
            --page.useCount;
          }
          assertIsTrue(this._allocatorCount > 0);
          --this._allocatorCount;
          if (this._allocatorCount === 0) {
            this._manager[onStackPurgedTag](this);
          }
        };
        _proto._pushNewPage = function _pushNewPage() {
          var newPage = new SharedMemoryPage(this._pageSize);
          this._pages.push(newPage);
        };
        _createClass(PagedStack, [{
          key: "pageSize",
          get: function get() {
            return this._pageSize;
          }
        }, {
          key: "debugLocking",
          get: function get() {
            return this._locking;
          }
        }, {
          key: "allocatorCount",
          get: function get() {
            return this._allocatorCount;
          }
        }]);
        return PagedStack;
      }();
      var SharedMemorySlice = function SharedMemorySlice(buffer, byteOffset) {
        this.buffer = buffer;
        this.byteOffset = byteOffset;
      };
      var SharedStackBasedAllocator = function () {
        function SharedStackBasedAllocator(_resource, _sliceSize) {
          this[allocatorPageCountTag] = 0;
          this._slicesPerPage = 0;
          this._slices = [];
          this._resource = _resource;
          this._sliceSize = _sliceSize;
          var slicesPerPage = Math.floor(this._resource.pageSize / _sliceSize);
          assertIsTrue(slicesPerPage > 0);
          this._slicesPerPage = slicesPerPage;
        }
        var _proto2 = SharedStackBasedAllocator.prototype;
        _proto2.destroy = function destroy() {
          assertIsTrue(this._slices.length === 0, "Can not destroy the allocator since it's not empty.");
          assertIsTrue(!this._resource.debugLocking, "Can not destroy the allocator since it's locking.");
          this._resource.destroyAllocator(this);
        };
        _proto2.debugLock = function debugLock() {
          this._resource.debugLock();
        };
        _proto2.debugUnlock = function debugUnlock() {
          this._resource.debugUnlock();
        };
        _proto2.push = function push() {
          var sliceLength = this._sliceSize,
            slices = this._slices,
            slicesPerPage = this._slicesPerPage;
          var desiredSliceIndex = slices.length;
          var newSliceIndexInPage = 0;
          var newSlicePageIndex = 0;
          if (sliceLength === 0) {
            if (this[allocatorPageCountTag] === 0) {
              this._resource.pushPage(this);
            }
            assertIsTrue(this[allocatorPageCountTag] === 1);
          } else {
            var capacity = slicesPerPage * this[allocatorPageCountTag];
            assertIsTrue(desiredSliceIndex <= capacity);
            if (desiredSliceIndex === capacity) {
              this._resource.pushPage(this);
              assertIsTrue(desiredSliceIndex < slicesPerPage * this[allocatorPageCountTag]);
            }
            newSliceIndexInPage = desiredSliceIndex % slicesPerPage;
            newSlicePageIndex = (desiredSliceIndex - newSliceIndexInPage) / slicesPerPage;
            assertIsTrue(this[allocatorPageCountTag] * slicesPerPage >= desiredSliceIndex);
          }
          var pageMemory = this._resource.getPageMemory(newSlicePageIndex);
          var newSlice = new SharedMemorySlice(pageMemory, sliceLength * newSliceIndexInPage);
          this._slices.push(newSlice);
          return newSlice;
        };
        _proto2.pop = function pop() {
          var slices = this._slices,
            slicesPerPage = this._slicesPerPage;
          var allocatedCount = slices.length;
          assertIsTrue(allocatedCount > 0);
          var removingSliceIndex = allocatedCount - 1;
          if (this._sliceSize === 0) {
            assertIsTrue(this[allocatorPageCountTag] === 1);
            if (removingSliceIndex === 0) {
              this._resource.popPage(this);
            }
          } else {
            var removingSliceIndexInPage = removingSliceIndex % slicesPerPage;
            if (removingSliceIndexInPage === 0) {
              this._resource.popPage(this);
            }
          }
          this._slices.pop();
        };
        _createClass(SharedStackBasedAllocator, [{
          key: "isEmpty",
          get: function get() {
            return this._slices.length === 0;
          }
        }]);
        return SharedStackBasedAllocator;
      }();
      var SharedStackBasedAllocatorManager = function () {
        function SharedStackBasedAllocatorManager(_thresholds) {
          this._stacks = new Map();
          this._thresholds = _thresholds;
          assertIsTrue(_thresholds.every(function (v, i, arr) {
            return i === 0 || v > arr[i - 1];
          }));
        }
        var _proto3 = SharedStackBasedAllocatorManager.prototype;
        _proto3.createAllocator = function createAllocator(pageSize) {
          var allocationPageSize = pageSize;
          var stackPageSize = this._selectStackPageSize(allocationPageSize);
          var stack = this._stacks.get(stackPageSize);
          if (!stack) {
            stack = new PagedStack(this, stackPageSize);
            this._stacks.set(stackPageSize, stack);
          }
          return stack.createAllocator(allocationPageSize);
        };
        _proto3[onStackPurgedTag] = function (stack) {
          var stackFound = false;
          for (var _iterator = _createForOfIteratorHelperLoose(this._stacks), _step; !(_step = _iterator()).done;) {
            var _step$value = _step.value,
              k = _step$value[0],
              v = _step$value[1];
            if (v === stack) {
              this._stacks["delete"](k);
              stackFound = true;
              break;
            }
          }
          if (!stackFound) {
            assertIsTrue(false, "Given allocator is not of mime.");
          }
        };
        _proto3._selectStackPageSize = function _selectStackPageSize(allocationPageSize) {
          var thresholdIndex = binarySearchEpsilon(this._thresholds, allocationPageSize);
          var stackPageSize = allocationPageSize;
          if (thresholdIndex >= 0) {
            stackPageSize = this._thresholds[thresholdIndex];
          } else {
            thresholdIndex = ~thresholdIndex;
            if (thresholdIndex === this._thresholds.length) ; else {
              assertIsTrue(thresholdIndex >= 0 && thresholdIndex < this._thresholds.length);
              stackPageSize = this._thresholds[thresholdIndex];
            }
          }
          return stackPageSize;
        };
        _createClass(SharedStackBasedAllocatorManager, [{
          key: "isEmpty",
          get: function get() {
            return this._stacks.size === 0;
          }
        }]);
        return SharedStackBasedAllocatorManager;
      }();

      var PoseStackAllocator = function () {
        function PoseStackAllocator(transformCount, auxiliaryCurveCount) {
          this._poses = [];
          this._allocatedCount = 0;
          this._memoryAllocator = void 0;
          this._transformCount = transformCount;
          this._auxiliaryCurveCount = auxiliaryCurveCount;
          var poseBytes = calculateRequiredBytes(transformCount, auxiliaryCurveCount, 1);
          this._memoryAllocator = globalPosePageMemoryAllocatorManager.createAllocator(poseBytes);
        }
        var _proto = PoseStackAllocator.prototype;
        _proto.destroy = function destroy() {
          assertIsTrue(this._allocatedCount === 0, "Can not destroy the allocator since it's not empty.");
          for (var iPose = 0; iPose < this._poses.length; ++iPose) {
            this._memoryAllocator.pop();
          }
          this._poses.length = 0;
          return this._memoryAllocator.destroy();
        };
        _proto.push = function push() {
          if (this._allocatedCount === 0) {
            this._memoryAllocator.debugLock();
          }
          if (this._allocatedCount === this._poses.length) {
            this._allocateNewPose();
            assertIsTrue(this._allocatedCount < this._poses.length);
          }
          var pose = this._poses[this._allocatedCount];
          ++this._allocatedCount;
          return pose;
        };
        _proto.pop = function pop() {
          assertIsTrue(this._allocatedCount > 0, "PoseStackAllocator: push/pop does not match.");
          --this._allocatedCount;
          if (this._allocatedCount === 0) {
            this._memoryAllocator.debugUnlock();
          }
        };
        _proto._allocateNewPose = function _allocateNewPose() {
          var slice = this._memoryAllocator.push();
          var transformsByteLength = TransformArray.BYTES_PER_ELEMENT * this._transformCount;
          var baseOffset = slice.byteOffset;
          var transforms = new TransformArray(slice.buffer, baseOffset, this._transformCount);
          var auxiliaryCurves = new Float64Array(slice.buffer, baseOffset + transformsByteLength, this._auxiliaryCurveCount);
          var pose = Pose._create(transforms, auxiliaryCurves);
          this._poses.push(pose);
        };
        _createClass(PoseStackAllocator, [{
          key: "allocatedCount",
          get: function get() {
            return this._allocatedCount;
          }
        }, {
          key: "top",
          get: function get() {
            assertIsTrue(this._allocatedCount > 0);
            return this._poses[this._allocatedCount - 1];
          }
        }]);
        return PoseStackAllocator;
      }();
      function calculateRequiredBytes(transformCount, auxiliaryCurveCount, capacity) {
        return (TransformArray.BYTES_PER_ELEMENT * transformCount + Float64Array.BYTES_PER_ELEMENT * auxiliaryCurveCount) * capacity;
      }
      var PAGE_SIZE = calculateRequiredBytes(128, 10, 4);
      var globalPosePageMemoryAllocatorManager = new SharedStackBasedAllocatorManager([PAGE_SIZE]);

      function partition(array, predicate) {
        var nElements = array.length;
        var iFirstGroup2Element = 0;
        for (; iFirstGroup2Element < nElements; ++iFirstGroup2Element) {
          var _element = array[iFirstGroup2Element];
          if (!predicate(_element, iFirstGroup2Element, array)) {
            break;
          }
        }
        if (iFirstGroup2Element === nElements) {
          return nElements;
        }
        var nGroup1 = iFirstGroup2Element;
        for (var iElement = iFirstGroup2Element + 1; iElement < nElements; ++iElement) {
          var _element2 = array[iElement];
          var isFirstGroupElement = predicate(_element2, iElement, array);
          if (isFirstGroupElement) {
            var t = _element2;
            array[iElement] = array[nGroup1];
            array[nGroup1] = t;
            ++nGroup1;
          }
        }
        return nGroup1;
      }

      var TransformSpace;
      (function (TransformSpace) {
        TransformSpace[TransformSpace["WORLD"] = 0] = "WORLD";
        TransformSpace[TransformSpace["COMPONENT"] = 1] = "COMPONENT";
        TransformSpace[TransformSpace["PARENT"] = 2] = "PARENT";
        TransformSpace[TransformSpace["LOCAL"] = 3] = "LOCAL";
      })(TransformSpace || (TransformSpace = {}));
      ccenum(TransformSpace);

      var MAX_POSE_PER_PAGE = 8;
      var allocationInfoTag = Symbol('PoseHeapAllocator');
      function isPagedPose(pose) {
        return allocationInfoTag in pose;
      }
      var PoseHeapAllocator = function () {
        function PoseHeapAllocator(transformCount, metaValueCount) {
          this._transformCount = 0;
          this._metaValueCount = 0;
          this._pages = [];
          this._allocatedCount = 0;
          this._foremostPossibleFreePage = 0;
          this._transformCount = transformCount;
          this._metaValueCount = metaValueCount;
        }
        var _proto = PoseHeapAllocator.prototype;
        _proto.allocatePose = function allocatePose() {
          ++this._allocatedCount;
          var pages = this._pages;
          var nPages = pages.length;
          for (var _iPage = this._foremostPossibleFreePage; _iPage < nPages; ++_iPage) {
            var _page = pages[_iPage];
            var _pose = _page.tryAllocate();
            if (_pose) {
              _pose[allocationInfoTag].pageIndex = _iPage;
              if (_page.freeCount === 0) {
                ++this._foremostPossibleFreePage;
              }
              return _pose;
            }
          }
          var pose = this._allocatePoseInNewPage();
          this._foremostPossibleFreePage = pose[allocationInfoTag].pageIndex;
          return pose;
        };
        _proto.destroyPose = function destroyPose(pose) {
          assertIsTrue(isPagedPose(pose));
          var pages = this._pages;
          var nPages = pages.length;
          var pageIndex = pose[allocationInfoTag].pageIndex;
          assertIsTrue(pageIndex >= 0 && pageIndex < nPages);
          var page = pages[pageIndex];
          page.deallocate(pose);
          --this._allocatedCount;
          if (pageIndex < this._foremostPossibleFreePage) {
            assertIsTrue(page.freeCount > 0);
            this._foremostPossibleFreePage = pageIndex;
          }
        };
        _proto._allocatePoseInNewPage = function _allocatePoseInNewPage() {
          var page = new PosePage(this._transformCount, this._metaValueCount, 4);
          var pageIndex = this._pages.length;
          this._pages.push(page);
          var pose = page.tryAllocate();
          assertIsTrue(pose);
          pose[allocationInfoTag].pageIndex = pageIndex;
          return pose;
        };
        _createClass(PoseHeapAllocator, [{
          key: "allocatedCount",
          get: function get() {
            return this._allocatedCount;
          }
        }]);
        return PoseHeapAllocator;
      }();
      var AllocationInfo = function () {
        function AllocationInfo() {
          this._id = -1;
        }
        _createClass(AllocationInfo, [{
          key: "pageIndex",
          get: function get() {
            return this._id >> POSE_INDEX_BITS;
          },
          set: function set(value) {
            this._id &= POSE_INDEX_MASK;
            this._id |= value << POSE_INDEX_BITS;
          }
        }, {
          key: "poseIndex",
          get: function get() {
            return this._id & POSE_INDEX_MASK;
          },
          set: function set(value) {
            this._id &= ~POSE_INDEX_MASK;
            this._id |= value;
          }
        }]);
        return AllocationInfo;
      }();
      var POSE_INDEX_MASK = 7;
      var POSE_INDEX_BITS = 3;
      assertIsTrue(POSE_INDEX_MASK + 1 >= MAX_POSE_PER_PAGE);
      var PosePage = function () {
        function PosePage(_transformCount, _metaValueCount, _capacity) {
          this._buffer = void 0;
          this._idleFlags = 0xF;
          this._poses = void 0;
          this._freeCount = 0;
          this._transformCount = _transformCount;
          this._metaValueCount = _metaValueCount;
          this._capacity = _capacity;
          var byteLength = (TransformArray.BYTES_PER_ELEMENT * _transformCount + Float64Array.BYTES_PER_ELEMENT * _metaValueCount) * _capacity;
          this._buffer = new ArrayBuffer(byteLength);
          this._poses = new Array(_capacity).fill(null);
          this._freeCount = _capacity;
        }
        var _proto2 = PosePage.prototype;
        _proto2.tryAllocate = function tryAllocate() {
          var _poses$idlePoseIndex;
          var poses = this._poses,
            idleFlags = this._idleFlags,
            capacity = this._capacity;
          var idlePoseIndex = findRightmostSetBit(idleFlags);
          if (idlePoseIndex >= capacity) {
            return null;
          }
          assertIsTrue(idlePoseIndex >= 0 && idlePoseIndex < poses.length);
          var pose = (_poses$idlePoseIndex = poses[idlePoseIndex]) !== null && _poses$idlePoseIndex !== void 0 ? _poses$idlePoseIndex : poses[idlePoseIndex] = this._createPose(idlePoseIndex);
          pose[allocationInfoTag].poseIndex = idlePoseIndex;
          this._idleFlags &= ~(1 << idlePoseIndex);
          assertIsTrue(this._freeCount > 0);
          --this._freeCount;
          return pose;
        };
        _proto2.deallocate = function deallocate(pose) {
          var poses = this._poses;
          var poseIndex = pose[allocationInfoTag].poseIndex;
          assertIsTrue(poseIndex >= 0 && poseIndex < poses.length);
          assertIsTrue(poses[poseIndex] === pose);
          this._idleFlags |= 1 << poseIndex;
          assertIsTrue(this._freeCount < this._capacity);
          ++this._freeCount;
        };
        _proto2._createPose = function _createPose(index) {
          var transformsByteLength = TransformArray.BYTES_PER_ELEMENT * this._transformCount;
          var baseOffset = (transformsByteLength + Float64Array.BYTES_PER_ELEMENT * this._metaValueCount) * index;
          var transforms = new TransformArray(this._buffer, baseOffset, this._transformCount);
          var metaValues = new Float64Array(this._buffer, baseOffset + transformsByteLength, this._metaValueCount);
          var pose = Pose._create(transforms, metaValues);
          pose[allocationInfoTag] = new AllocationInfo();
          return pose;
        };
        _createClass(PosePage, [{
          key: "capacity",
          get: function get() {
            return this._capacity;
          }
        }, {
          key: "freeCount",
          get: function get() {
            return this._freeCount;
          }
        }]);
        return PosePage;
      }();
      function findRightmostSetBit(bits) {
        return bits === 0 ? Infinity : Math.log2(bits & -bits);
      }

      var _dec$11, _dec2$Y, _dec3$L, _dec4$B, _dec5$w, _dec6$h, _dec7$c, _class3$m;
      function findBoneByNameRecursively(from, name) {
        if (from.name === name) {
          return from;
        }
        var nChildren = from.children.length;
        for (var iChild = 0; iChild < nChildren; ++iChild) {
          var found = findBoneByNameRecursively(from.children[iChild], name);
          if (found) {
            return found;
          }
        }
        return null;
      }
      var AnimationGraphBindingContext = function () {
        function AnimationGraphBindingContext(origin, poseLayoutMaintainer, varRegistry, _controller) {
          var _this = this;
          this._origin = void 0;
          this._layoutMaintainer = void 0;
          this._varRegistry = void 0;
          this._additiveFlagStack = [];
          this._triggerResetter = function (name) {
            return _this._resetTrigger(name);
          };
          this._isLayerWideContextPropertiesSet = false;
          this._stashView = void 0;
          this._motionSyncManager = void 0;
          this._clipOverrides = undefined;
          this._controller = _controller;
          this._origin = origin;
          this._layoutMaintainer = poseLayoutMaintainer;
          this._varRegistry = varRegistry;
          this._additiveFlagStack = [false];
        }
        var _proto = AnimationGraphBindingContext.prototype;
        _proto.bindTransform = function bindTransform(bone) {
          var boneNode = this._origin.getChildByPath(bone);
          if (!boneNode) {
            return null;
          }
          return this._layoutMaintainer.getOrCreateTransformBinding(boneNode);
        };
        _proto.bindTransformByName = function bindTransformByName(bone) {
          var boneNode = findBoneByNameRecursively(this._origin, bone);
          if (!boneNode) {
            return null;
          }
          return this._layoutMaintainer.getOrCreateTransformBinding(boneNode);
        };
        _proto.getBoneChildren = function getBoneChildren(bone) {
          var boneNode = findBoneByNameRecursively(this._origin, bone);
          if (!boneNode) {
            return [];
          }
          return boneNode.children.map(function (childNode) {
            return childNode.name;
          });
        };
        _proto.getParentBoneNameByName = function getParentBoneNameByName(bone) {
          var _boneNode$parent;
          var boneNode = findBoneByNameRecursively(this._origin, bone);
          if (!boneNode) {
            return null;
          }
          return boneNode === this._origin ? '' : (_boneNode$parent = boneNode.parent) === null || _boneNode$parent === void 0 ? void 0 : _boneNode$parent.name;
        };
        _proto.bindAuxiliaryCurve = function bindAuxiliaryCurve(name) {
          return this._layoutMaintainer.getOrCreateAuxiliaryCurveBinding(name);
        };
        _proto.getEvaluationTimeAuxiliaryCurveView = function getEvaluationTimeAuxiliaryCurveView() {
          return this._layoutMaintainer.auxiliaryCurveRegistry;
        };
        _proto.getVar = function getVar(id) {
          return this._varRegistry[id];
        };
        _proto._pushAdditiveFlag = function _pushAdditiveFlag(additive) {
          this._additiveFlagStack.push(additive);
        };
        _proto._popAdditiveFlag = function _popAdditiveFlag() {
          assertIsTrue(this._additiveFlagStack.length > 1);
          this._additiveFlagStack.pop();
        };
        _proto._integrityCheck = function _integrityCheck() {
          return this._additiveFlagStack.length === 1;
        };
        _proto._setLayerWideContextProperties = function _setLayerWideContextProperties(stashView, motionSyncManager) {
          assertIsTrue(!this._isLayerWideContextPropertiesSet);
          this._isLayerWideContextPropertiesSet = true;
          this._stashView = stashView;
          this._motionSyncManager = motionSyncManager;
        };
        _proto._unsetLayerWideContextProperties = function _unsetLayerWideContextProperties() {
          assertIsTrue(this._isLayerWideContextPropertiesSet);
          this._isLayerWideContextPropertiesSet = false;
          this._stashView = undefined;
          this._motionSyncManager = undefined;
        };
        _proto._setClipOverrides = function _setClipOverrides(clipOverrides) {
          this._clipOverrides = clipOverrides;
        };
        _proto._resetTrigger = function _resetTrigger(triggerName) {
          var varInstance = this._varRegistry[triggerName];
          if (!varInstance) {
            return;
          }
          varInstance.value = false;
        };
        _createClass(AnimationGraphBindingContext, [{
          key: "origin",
          get: function get() {
            return this._origin;
          }
        }, {
          key: "controller",
          get: function get() {
            return this._controller;
          }
        }, {
          key: "triggerResetter",
          get: function get() {
            return this._triggerResetter;
          }
        }, {
          key: "clipOverrides",
          get: function get() {
            return this._clipOverrides;
          }
        }, {
          key: "additive",
          get: function get() {
            var additiveFlagStack = this._additiveFlagStack;
            return additiveFlagStack[additiveFlagStack.length - 1];
          }
        }, {
          key: "stashView",
          get: function get() {
            assertIsTrue(this._stashView);
            return this._stashView;
          }
        }, {
          key: "motionSyncManager",
          get: function get() {
            assertIsTrue(this._motionSyncManager);
            return this._motionSyncManager;
          }
        }]);
        return AnimationGraphBindingContext;
      }();
      var cacheTransform$2 = new Transform();
      var AuxiliaryCurveRegistry = function () {
        function AuxiliaryCurveRegistry() {
          this._namedCurves = new Map();
        }
        var _proto2 = AuxiliaryCurveRegistry.prototype;
        _proto2.names = function names() {
          return this._namedCurves.keys();
        };
        _proto2.has = function has(name) {
          return this._namedCurves.has(name);
        };
        _proto2.get = function get(name) {
          var _this$_namedCurves$ge;
          return (_this$_namedCurves$ge = this._namedCurves.get(name)) !== null && _this$_namedCurves$ge !== void 0 ? _this$_namedCurves$ge : 0.0;
        };
        _proto2.set = function set(name, value) {
          this._namedCurves.set(name, value);
        };
        return AuxiliaryCurveRegistry;
      }();
      var LayoutChangeFlag;
      (function (LayoutChangeFlag) {
        LayoutChangeFlag[LayoutChangeFlag["TRANSFORM_COUNT"] = 1] = "TRANSFORM_COUNT";
        LayoutChangeFlag[LayoutChangeFlag["TRANSFORM_ORDER"] = 2] = "TRANSFORM_ORDER";
        LayoutChangeFlag[LayoutChangeFlag["AUXILIARY_CURVE_COUNT"] = 4] = "AUXILIARY_CURVE_COUNT";
      })(LayoutChangeFlag || (LayoutChangeFlag = {}));
      var checkBindStatus = function checkBindStatus(bindStarted) {
        if (bindStarted === void 0) {
          bindStarted = false;
        }
        return function (_, _propertyKey, descriptor) {
          var vendor = descriptor.value;
          if (vendor) {
            descriptor.value = function () {
              assertIsTrue(this._bindStarted === bindStarted, bindStarted ? "The operation is invalid since bind has not been started." : "The operation is invalid since bind has already been started.");
              for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
                args[_key] = arguments[_key];
              }
              return vendor.call.apply(vendor, [this].concat(args));
            };
          }
        };
      };
      var AnimationGraphPoseLayoutMaintainer = (_dec$11 = checkBindStatus(true), _dec2$Y = checkBindStatus(true), _dec3$L = checkBindStatus(true), _dec4$B = checkBindStatus(true), _dec5$w = checkBindStatus(true), _dec6$h = checkBindStatus(false), _dec7$c = checkBindStatus(true), (_class3$m = function () {
        function AnimationGraphPoseLayoutMaintainer(origin, auxiliaryCurveRegistry) {
          this._origin = void 0;
          this._auxiliaryCurveRegistry = void 0;
          this._auxiliaryCurveRecords = [];
          this._transformRecords = [];
          this._parentTable = [];
          this._bindStarted = false;
          this._transformCountBeforeBind = -1;
          this._auxiliaryCurveCountBeforeBind = -1;
          this._origin = origin;
          this._auxiliaryCurveRegistry = auxiliaryCurveRegistry;
        }
        var _proto3 = AnimationGraphPoseLayoutMaintainer.prototype;
        _proto3.getOrCreateTransformBinding = function getOrCreateTransformBinding(node) {
          var origin = this._origin;
          var debugIntegrityCheckLengthOfPathToOrigin = 0;
          var isValidNode = false;
          for (var current = node; current; current = current.parent) {
            if (current === origin) {
              isValidNode = true;
              break;
            }
            {
              ++debugIntegrityCheckLengthOfPathToOrigin;
            }
          }
          if (!isValidNode) {
            return null;
          }
          var handle = this._getOrCreateTransformBinding(node);
          if (node !== origin) {
            {
              --debugIntegrityCheckLengthOfPathToOrigin;
              assertIsTrue(debugIntegrityCheckLengthOfPathToOrigin >= 0);
            }
            for (var parent = node.parent; parent !== origin; parent = parent.parent) {
              assertIsTrue(parent);
              void this._getOrCreateTransformBinding(parent);
              {
                --debugIntegrityCheckLengthOfPathToOrigin;
                assertIsTrue(debugIntegrityCheckLengthOfPathToOrigin >= 0);
              }
            }
          }
          {
            assertIsTrue(debugIntegrityCheckLengthOfPathToOrigin === 0);
          }
          return handle;
        };
        _proto3._getOrCreateTransformBinding = function _getOrCreateTransformBinding(node) {
          var transformRecords = this._transformRecords;
          var transformIndex = transformRecords.findIndex(function (transformRecord) {
            return transformRecord.node === node;
          });
          if (transformIndex >= 0) {
            var _transformRecord = transformRecords[transformIndex];
            ++_transformRecord.refCount;
            return _transformRecord.handle;
          }
          var newNodeIndex = 0;
          var _loop = function _loop(parent) {
            var parentIndex = transformRecords.findIndex(function (transformRecord) {
              return transformRecord.node === parent;
            });
            if (parentIndex >= 0) {
              newNodeIndex = parentIndex + 1;
              return 1;
            }
          };
          for (var parent = node.parent; parent; parent = parent.parent) {
            if (_loop(parent)) break;
          }
          for (var _transformIndex = newNodeIndex; _transformIndex < transformRecords.length; ++_transformIndex) {
            ++transformRecords[_transformIndex].handle.index;
          }
          var transformRecord = new TransformRecord(new TransformHandleInternal(this, newNodeIndex), node);
          transformRecords.splice(newNodeIndex, 0, transformRecord);
          return transformRecord.handle;
        };
        _proto3.getOrCreateAuxiliaryCurveBinding = function getOrCreateAuxiliaryCurveBinding(name) {
          var auxiliaryCurveRecords = this._auxiliaryCurveRecords;
          var auxiliaryCurveIndex = auxiliaryCurveRecords.findIndex(function (record) {
            return record.name === name;
          });
          if (auxiliaryCurveIndex >= 0) {
            var auxiliaryCurveRecord = auxiliaryCurveRecords[auxiliaryCurveIndex];
            ++auxiliaryCurveRecord.refCount;
            return auxiliaryCurveRecord.handle;
          } else {
            var newAuxiliaryCurveIndex = auxiliaryCurveRecords.length;
            var _auxiliaryCurveRecord = new AuxiliaryCurveRecord(new AuxiliaryCurveHandleInternal(this, newAuxiliaryCurveIndex), name);
            auxiliaryCurveRecords.push(_auxiliaryCurveRecord);
            return _auxiliaryCurveRecord.handle;
          }
        };
        _proto3.createEvaluationContext = function createEvaluationContext() {
          assertIsTrue(!this._bindStarted);
          return new AnimationGraphEvaluationContext(this.transformCount, this.auxiliaryCurveCount, this._parentTable.slice(), this._origin);
        };
        _proto3.resetPoseStashAllocator = function resetPoseStashAllocator(allocator) {
          assertIsTrue(!this._bindStarted);
          allocator._reset(this.transformCount, this.auxiliaryCurveCount);
        };
        _proto3.createTransformFilter = function createTransformFilter(mask) {
          var origin = this._origin;
          var involvedTransformIndices = [];
          for (var _iterator = _createForOfIteratorHelperLoose(this._transformRecords), _step; !(_step = _iterator()).done;) {
            var _step$value = _step.value,
              node = _step$value.node,
              handle = _step$value.handle;
            var path = countPath(origin, node);
            if (typeof path === 'undefined') {
              error(node.getPathInHierarchy() + " is not a child of " + origin.getPathInHierarchy());
            } else if (mask.isExcluded(path)) {
              continue;
            }
            involvedTransformIndices.push(handle.index);
          }
          involvedTransformIndices.sort();
          var poseFilter = new TransformFilter(involvedTransformIndices);
          return poseFilter;
          function countPath(from, to) {
            var path = [];
            for (var node = to; node; node = node.parent) {
              if (node === from) {
                return path.join('/');
              } else {
                path.unshift(node.name);
              }
            }
            return undefined;
          }
        };
        _proto3.fetchDefaultTransforms = function fetchDefaultTransforms(transforms) {
          var nTransforms = this._transformRecords.length;
          assertIsTrue(transforms.length === nTransforms);
          for (var iTransform = 0; iTransform < nTransforms; ++iTransform) {
            var defaultTransform = this._transformRecords[iTransform].defaultTransform;
            transforms.setTransform(iTransform, defaultTransform);
          }
        };
        _proto3.apply = function apply(pose) {
          var transforms = pose.transforms,
            auxiliaryCurves = pose.auxiliaryCurves;
          var nTransforms = this._transformRecords.length;
          assertIsTrue(transforms.length === nTransforms);
          for (var iTransform = 0; iTransform < nTransforms; ++iTransform) {
            var transform = transforms.getTransform(iTransform, cacheTransform$2);
            var node = this._transformRecords[iTransform].node;
            node.setRTS(transform.rotation, transform.position, transform.scale);
          }
          var nAuxiliaryCurves = this._auxiliaryCurveRecords.length;
          for (var iAuxiliaryCurve = 0; iAuxiliaryCurve < nAuxiliaryCurves; ++iAuxiliaryCurve) {
            var _curveName = this._auxiliaryCurveRecords[iAuxiliaryCurve].name;
            var curveValue = auxiliaryCurves[iAuxiliaryCurve];
            this._auxiliaryCurveRegistry.set(_curveName, curveValue);
          }
        };
        _proto3._destroyTransformHandle = function _destroyTransformHandle(index) {
          assertIsTrue(index >= 0 && index < this._transformRecords.length, "Invalid transform handle.");
          var record = this._transformRecords[index];
          assertIsTrue(record.refCount > 0, "Something work wrong: refCount mismatch.");
          --record.refCount;
        };
        _proto3._destroyAuxiliaryCurveHandle = function _destroyAuxiliaryCurveHandle(index) {
          assertIsTrue(index >= 0 && index < this._auxiliaryCurveRecords.length, "Invalid auxiliary value handle.");
          var record = this._auxiliaryCurveRecords[index];
          assertIsTrue(record.refCount > 0, "Something work wrong: refCount mismatch.");
          --record.refCount;
        };
        _proto3.startBind = function startBind() {
          this._bindStarted = true;
          this._transformCountBeforeBind = this._transformRecords.length;
          this._auxiliaryCurveCountBeforeBind = this._auxiliaryCurveRecords.length;
        };
        _proto3.endBind = function endBind() {
          var transformRecords = this._transformRecords,
            auxiliaryCurveRecords = this._auxiliaryCurveRecords;
          var changeFlags = 0;
          trimRecords(transformRecords);
          if (transformRecords.length !== this._transformCountBeforeBind) {
            changeFlags |= LayoutChangeFlag.TRANSFORM_COUNT;
            var nRecords = transformRecords.length;
            for (var iRecord = 0; iRecord < nRecords; ++iRecord) {
              var record = transformRecords[iRecord];
              record.order = iRecord;
            }
          } else {
            var _nRecords = transformRecords.length;
            var orderChanged = false;
            for (var _iRecord = 0; _iRecord < _nRecords; ++_iRecord) {
              var _record = transformRecords[_iRecord];
              if (_record.order !== _iRecord) {
                orderChanged = true;
                _record.order = _iRecord;
              }
            }
            if (orderChanged) {
              changeFlags |= LayoutChangeFlag.TRANSFORM_ORDER;
            }
          }
          trimRecords(auxiliaryCurveRecords);
          if (auxiliaryCurveRecords.length !== this._auxiliaryCurveCountBeforeBind) {
            changeFlags |= LayoutChangeFlag.AUXILIARY_CURVE_COUNT;
          }
          var parentTable = this._parentTable,
            origin = this._origin;
          parentTable.length = transformRecords.length;
          var _loop2 = function _loop2() {
            var node = transformRecords[iTransform].node;
            if (node === origin) {
              parentTable[iTransform] = -1;
              return 1;
            }
            var parent = node.parent;
            if (parent === origin) {
              var parentIndex = transformRecords.findIndex(function (record) {
                return record.node === parent;
              });
              parentTable[iTransform] = parentIndex >= 0 ? parentIndex : -1;
            } else {
              var _parentIndex = transformRecords.findIndex(function (record) {
                return record.node === parent;
              });
              assertIsTrue(_parentIndex >= 0, "Parent node is not bound!");
              assertIsTrue(_parentIndex < iTransform);
              parentTable[iTransform] = _parentIndex;
            }
          };
          for (var iTransform = 0; iTransform < transformRecords.length; ++iTransform) {
            if (_loop2()) continue;
          }
          this._bindStarted = false;
          {
            transformRecords.forEach(function (transformRecord, index, transformRecords) {
              assertIsTrue(transformRecord.handle.index === index, "Bad transform handle.");
              assertIsTrue(transformRecord.order === index, "Bad transform order field.");
              var _loop3 = function _loop3(parent) {
                var parentIndex = transformRecords.findIndex(function (r) {
                  return r.node === parent;
                });
                if (parentIndex >= 0) {
                  assertIsTrue(parentIndex < index, "Bad transform order.");
                }
              };
              for (var parent = transformRecord.node.parent; parent; parent = parent.parent) {
                _loop3(parent);
              }
            });
            this._transformCountBeforeBind = -1;
            this._auxiliaryCurveCountBeforeBind = -1;
          }
          return changeFlags;
        };
        _createClass(AnimationGraphPoseLayoutMaintainer, [{
          key: "transformCount",
          get: function get() {
            return this._transformRecords.length;
          }
        }, {
          key: "auxiliaryCurveCount",
          get: function get() {
            return this._auxiliaryCurveRecords.length;
          }
        }, {
          key: "auxiliaryCurveRegistry",
          get: function (_get) {
            function get() {
              return _get.apply(this, arguments);
            }
            get.toString = function () {
              return _get.toString();
            };
            return get;
          }(function () {
            return this._auxiliaryCurveRegistry;
          })
        }]);
        return AnimationGraphPoseLayoutMaintainer;
      }(), (_applyDecoratedDescriptor(_class3$m.prototype, "getOrCreateTransformBinding", [_dec$11], Object.getOwnPropertyDescriptor(_class3$m.prototype, "getOrCreateTransformBinding"), _class3$m.prototype), _applyDecoratedDescriptor(_class3$m.prototype, "_getOrCreateTransformBinding", [_dec2$Y], Object.getOwnPropertyDescriptor(_class3$m.prototype, "_getOrCreateTransformBinding"), _class3$m.prototype), _applyDecoratedDescriptor(_class3$m.prototype, "getOrCreateAuxiliaryCurveBinding", [_dec3$L], Object.getOwnPropertyDescriptor(_class3$m.prototype, "getOrCreateAuxiliaryCurveBinding"), _class3$m.prototype), _applyDecoratedDescriptor(_class3$m.prototype, "_destroyTransformHandle", [_dec4$B], Object.getOwnPropertyDescriptor(_class3$m.prototype, "_destroyTransformHandle"), _class3$m.prototype), _applyDecoratedDescriptor(_class3$m.prototype, "_destroyAuxiliaryCurveHandle", [_dec5$w], Object.getOwnPropertyDescriptor(_class3$m.prototype, "_destroyAuxiliaryCurveHandle"), _class3$m.prototype), _applyDecoratedDescriptor(_class3$m.prototype, "startBind", [_dec6$h], Object.getOwnPropertyDescriptor(_class3$m.prototype, "startBind"), _class3$m.prototype), _applyDecoratedDescriptor(_class3$m.prototype, "endBind", [_dec7$c], Object.getOwnPropertyDescriptor(_class3$m.prototype, "endBind"), _class3$m.prototype)), _class3$m));
      var TransformRecord = function TransformRecord(handle, node) {
        this.order = -1;
        this.refCount = 1;
        this.handle = void 0;
        this.node = void 0;
        this.defaultTransform = void 0;
        this.handle = handle;
        this.node = node;
        var defaultTransform = new Transform();
        defaultTransform.position = node.position;
        defaultTransform.rotation = node.rotation;
        defaultTransform.scale = node.scale;
        this.defaultTransform = defaultTransform;
      };
      var AuxiliaryCurveRecord = function AuxiliaryCurveRecord(handle, name) {
        this.refCount = 1;
        this.handle = void 0;
        this.name = void 0;
        this.handle = handle;
        this.name = name;
      };
      function trimRecords(records) {
        var nUsedRecords = partition(records, function (record) {
          assertIsTrue(record.refCount >= 0);
          return record.refCount > 0;
        });
        assertIsTrue(nUsedRecords <= records.length);
        if (nUsedRecords === records.length) {
          return;
        }
        for (var iRecord = 0; iRecord < nUsedRecords; ++iRecord) {
          records[iRecord].handle.index = iRecord;
        }
        {
          records.slice(nUsedRecords).forEach(function (record) {
            return record.refCount = -1;
          });
        }
        records.splice(nUsedRecords, records.length - nUsedRecords);
      }
      var defaultTransformsTag = Symbol('[[DefaultTransforms]]');
      var AnimationGraphSettleContext = function () {
        function AnimationGraphSettleContext(_layoutMaintainer) {
          this._layoutMaintainer = _layoutMaintainer;
        }
        var _proto4 = AnimationGraphSettleContext.prototype;
        _proto4.createTransformFilter = function createTransformFilter(mask) {
          return this._layoutMaintainer.createTransformFilter(mask);
        };
        _createClass(AnimationGraphSettleContext, [{
          key: "transformCount",
          get: function get() {
            return this._layoutMaintainer.transformCount;
          }
        }]);
        return AnimationGraphSettleContext;
      }();
      var cacheTransform_spaceConversion$1 = new Transform();
      var cacheParentTransform_spaceConversion$1 = new Transform();
      var AnimationGraphEvaluationContext = function () {
        function AnimationGraphEvaluationContext(transformCount, metaValueCount, parentTable, componentNode) {
          this[defaultTransformsTag] = void 0;
          this._poseAllocator = void 0;
          this._parentTable = void 0;
          this._componentNode = void 0;
          this._cacheComponentToWorldTransform = new Transform();
          {
            assertIsTrue(transformCount === parentTable.length);
            assertIsTrue(parentTable.every(function (parentIndex, currentIndex) {
              if (parentIndex < 0) {
                return true;
              }
              return parentIndex < currentIndex;
            }));
          }
          this._poseAllocator = new PoseStackAllocator(transformCount, metaValueCount);
          this._parentTable = parentTable;
          this._componentNode = componentNode;
          this[defaultTransformsTag] = new TransformArray(transformCount);
        }
        var _proto5 = AnimationGraphEvaluationContext.prototype;
        _proto5.destroy = function destroy() {
          this._poseAllocator.destroy();
        };
        _proto5.pushDefaultedPose = function pushDefaultedPose() {
          var pose = this._poseAllocator.push();
          pose.transforms.set(this[defaultTransformsTag]);
          pose._poseTransformSpace = PoseTransformSpace.LOCAL;
          pose.auxiliaryCurves.fill(0.0);
          return pose;
        };
        _proto5.pushDefaultedPoseInComponentSpace = function pushDefaultedPoseInComponentSpace() {
          var pose = this.pushDefaultedPose();
          this._poseTransformsSpaceLocalToComponent(pose);
          return pose;
        };
        _proto5.pushZeroDeltaPose = function pushZeroDeltaPose() {
          var pose = this._poseAllocator.push();
          pose.transforms.fill(ZERO_DELTA_TRANSFORM);
          pose._poseTransformSpace = PoseTransformSpace.LOCAL;
          pose.auxiliaryCurves.fill(0.0);
          return pose;
        };
        _proto5.pushDuplicatedPose = function pushDuplicatedPose(src) {
          var pose = this._poseAllocator.push();
          pose.transforms.set(src.transforms);
          pose._poseTransformSpace = src._poseTransformSpace;
          pose.auxiliaryCurves.set(src.auxiliaryCurves);
          return pose;
        };
        _proto5.popPose = function popPose() {
          this._poseAllocator.pop();
        };
        _proto5._isStackTopPose_debugging = function _isStackTopPose_debugging(pose) {
          return pose === this._poseAllocator.top;
        };
        _proto5._poseTransformsSpaceLocalToComponent = function _poseTransformsSpaceLocalToComponent(pose) {
          var transforms = pose.transforms;
          var nTransforms = transforms.length;
          for (var iTransform = 0; iTransform < nTransforms; ++iTransform) {
            var parentTransformIndex = this._parentTable[iTransform];
            if (parentTransformIndex < 0) {
              continue;
            }
            var transform = transforms.getTransform(iTransform, cacheTransform_spaceConversion$1);
            var parentTransform = transforms.getTransform(parentTransformIndex, cacheParentTransform_spaceConversion$1);
            Transform.multiply(transform, parentTransform, transform);
            transforms.setTransform(iTransform, transform);
          }
          pose._poseTransformSpace = PoseTransformSpace.COMPONENT;
        };
        _proto5._poseTransformsSpaceComponentToLocal = function _poseTransformsSpaceComponentToLocal(pose) {
          var transforms = pose.transforms;
          var nTransforms = transforms.length;
          for (var iTransform = nTransforms - 1; iTransform >= 0; --iTransform) {
            var parentTransformIndex = this._parentTable[iTransform];
            if (parentTransformIndex < 0) {
              continue;
            }
            var transform = transforms.getTransform(iTransform, cacheTransform_spaceConversion$1);
            var parentTransform = transforms.getTransform(parentTransformIndex, cacheParentTransform_spaceConversion$1);
            Transform.calculateRelative(transform, transform, parentTransform);
            transforms.setTransform(iTransform, transform);
          }
          pose._poseTransformSpace = PoseTransformSpace.LOCAL;
        };
        _proto5._convertPoseSpaceTransformToTargetSpace = function _convertPoseSpaceTransformToTargetSpace(transform, outTransformSpace, pose, poseTransformIndex) {
          var poseSpace = pose._poseTransformSpace;
          switch (outTransformSpace) {
            default:
              {
                assertIsTrue(false);
              }
              break;
            case TransformSpace.WORLD:
              if (poseSpace === PoseTransformSpace.COMPONENT) {
                Transform.multiply(transform, this._getComponentToWorldTransform(), transform);
              } else {
                assertIsTrue(poseSpace === PoseTransformSpace.LOCAL);
                Transform.multiply(transform, this._getLocalToWorldTransform(cacheParentTransform_spaceConversion$1, pose, poseTransformIndex), transform);
              }
              break;
            case TransformSpace.COMPONENT:
              if (poseSpace === PoseTransformSpace.COMPONENT) ; else {
                assertIsTrue(poseSpace === PoseTransformSpace.LOCAL);
                Transform.multiply(transform, this._getLocalToComponentTransform(cacheParentTransform_spaceConversion$1, pose, poseTransformIndex), transform);
              }
              break;
            case TransformSpace.PARENT:
              {
                if (poseSpace === PoseTransformSpace.COMPONENT) {
                  var parentTransformIndex = this._parentTable[poseTransformIndex];
                  if (parentTransformIndex >= 0) {
                    var parentComponentTransform = pose.transforms.getTransform(parentTransformIndex, cacheParentTransform_spaceConversion$1);
                    var invParentComponentTransform = Transform.invert(parentComponentTransform, parentComponentTransform);
                    Transform.multiply(transform, invParentComponentTransform, transform);
                  }
                } else {
                  assertIsTrue(poseSpace === PoseTransformSpace.LOCAL);
                }
                break;
              }
            case TransformSpace.LOCAL:
              {
                assertIsTrue(poseSpace === PoseTransformSpace.COMPONENT || poseSpace === PoseTransformSpace.LOCAL);
                var boneTransform = pose.transforms.getTransform(poseTransformIndex, cacheParentTransform_spaceConversion$1);
                var invBoneTransform = Transform.invert(boneTransform, boneTransform);
                Transform.multiply(transform, invBoneTransform, transform);
                break;
              }
          }
          return transform;
        };
        _proto5._convertTransformToPoseTransformSpace = function _convertTransformToPoseTransformSpace(transform, transformSpace, pose, poseTransformIndex) {
          var poseSpace = pose._poseTransformSpace;
          switch (transformSpace) {
            default:
              {
                assertIsTrue(false);
              }
              break;
            case TransformSpace.WORLD:
              if (poseSpace === PoseTransformSpace.COMPONENT) {
                var worldToComponent = Transform.invert(cacheParentTransform_spaceConversion$1, this._getComponentToWorldTransform());
                Transform.multiply(transform, worldToComponent, transform);
              } else {
                assertIsTrue(poseSpace === PoseTransformSpace.LOCAL);
                var localToWorld = this._getLocalToWorldTransform(cacheParentTransform_spaceConversion$1, pose, poseTransformIndex);
                var worldToLocal = Transform.invert(localToWorld, localToWorld);
                Transform.multiply(transform, worldToLocal, transform);
              }
              break;
            case TransformSpace.COMPONENT:
              if (poseSpace === PoseTransformSpace.COMPONENT) ; else {
                assertIsTrue(poseSpace === PoseTransformSpace.LOCAL);
                var localToComponent = this._getLocalToComponentTransform(cacheParentTransform_spaceConversion$1, pose, poseTransformIndex);
                var componentToLocal = Transform.invert(localToComponent, localToComponent);
                Transform.multiply(transform, componentToLocal, transform);
              }
              break;
            case TransformSpace.PARENT:
              {
                if (poseSpace === PoseTransformSpace.COMPONENT) {
                  var parentTransformIndex = this._parentTable[poseTransformIndex];
                  if (parentTransformIndex >= 0) {
                    var parentTransform = pose.transforms.getTransform(parentTransformIndex, cacheParentTransform_spaceConversion$1);
                    Transform.multiply(transform, parentTransform, transform);
                  }
                }
                break;
              }
            case TransformSpace.LOCAL:
              {
                assertIsTrue(poseSpace === PoseTransformSpace.COMPONENT || poseSpace === PoseTransformSpace.LOCAL);
                var currentTransform = pose.transforms.getTransform(poseTransformIndex, cacheParentTransform_spaceConversion$1);
                Transform.multiply(transform, currentTransform, transform);
                break;
              }
          }
          return transform;
        };
        _proto5._getComponentToWorldTransform = function _getComponentToWorldTransform() {
          var result = this._cacheComponentToWorldTransform;
          var componentNode = this._componentNode;
          result.position = componentNode.worldPosition;
          result.rotation = componentNode.worldRotation;
          result.scale = componentNode.worldScale;
          return result;
        };
        _proto5._getLocalToComponentTransform = function _getLocalToComponentTransform(out, pose, transformIndex) {
          var parentTable = this._parentTable;
          Transform.setIdentity(out);
          for (var iTransform = parentTable[transformIndex]; iTransform >= 0; iTransform = parentTable[iTransform]) {
            var localTransform = pose.transforms.getTransform(iTransform, cacheTransform_spaceConversion$1);
            Transform.multiply(out, localTransform, out);
          }
          return out;
        };
        _proto5._getLocalToWorldTransform = function _getLocalToWorldTransform(out, pose, transformIndex) {
          this._getLocalToComponentTransform(out, pose, transformIndex);
          Transform.multiply(out, this._getComponentToWorldTransform(), out);
          return out;
        };
        _createClass(AnimationGraphEvaluationContext, [{
          key: "allocatedPoseCount",
          get: function get() {
            return this._poseAllocator.allocatedCount;
          }
        }, {
          key: "parentTable",
          get: function get() {
            return this._parentTable;
          }
        }, {
          key: "_stackSize_debugging",
          get: function get() {
            return this._poseAllocator.allocatedCount;
          }
        }]);
        return AnimationGraphEvaluationContext;
      }();
      var TransformHandleInternal = function () {
        function TransformHandleInternal(host, index) {
          this.index = -1;
          this._host = void 0;
          this._host = host;
          this.index = index;
        }
        var _proto6 = TransformHandleInternal.prototype;
        _proto6.destroy = function destroy() {
          this._host._destroyTransformHandle(this.index);
        };
        return TransformHandleInternal;
      }();
      var AuxiliaryCurveHandleInternal = function () {
        function AuxiliaryCurveHandleInternal(host, index) {
          this.index = -1;
          this._host = void 0;
          this._host = host;
          this.index = index;
        }
        var _proto7 = AuxiliaryCurveHandleInternal.prototype;
        _proto7.destroy = function destroy() {
          this._host._destroyAuxiliaryCurveHandle(this.index);
        };
        return AuxiliaryCurveHandleInternal;
      }();
      var AnimationGraphUpdateContextGenerator = function () {
        function AnimationGraphUpdateContextGenerator() {
          this._context = {
            deltaTime: 0.0,
            indicativeWeight: 0.0
          };
        }
        var _proto8 = AnimationGraphUpdateContextGenerator.prototype;
        _proto8.generate = function generate(deltaTime, indicativeWeight) {
          this._context.deltaTime = deltaTime;
          this._context.indicativeWeight = indicativeWeight;
          return this._context;
        };
        _proto8.forkSubWeight = function forkSubWeight(base, subWeight) {
          this._context.deltaTime = base.deltaTime;
          this._context.indicativeWeight = base.indicativeWeight * subWeight;
        };
        return AnimationGraphUpdateContextGenerator;
      }();
      var DeferredPoseStashAllocator = function () {
        function DeferredPoseStashAllocator() {
          this._allocator = null;
        }
        var _proto9 = DeferredPoseStashAllocator.prototype;
        _proto9._reset = function _reset(transformCount, auxiliaryCurveCount) {
          this._allocator = new PoseHeapAllocator(transformCount, auxiliaryCurveCount);
        };
        _proto9.allocatePose = function allocatePose() {
          assertIsTrue(this._allocator);
          var pose = this._allocator.allocatePose();
          return pose;
        };
        _proto9.destroyPose = function destroyPose(pose) {
          assertIsTrue(this._allocator);
          return this._allocator.destroyPose(pose);
        };
        _createClass(DeferredPoseStashAllocator, [{
          key: "allocatedPoseCount",
          get: function get() {
            assertIsTrue(this._allocator);
            return this._allocator.allocatedCount;
          }
        }]);
        return DeferredPoseStashAllocator;
      }();

      var _dec$10, _class$$, _class2$Z, _initializer$R;
      var MotionSyncInfo = (_dec$10 = ccclass$n(CLASS_NAME_PREFIX_ANIM + "MotionSyncInfo"), _dec$10(_class$$ = (_class2$Z = function MotionSyncInfo() {
        this.group = _initializer$R && _initializer$R();
      }, (_initializer$R = applyDecoratedInitializer(_class2$Z.prototype, "group", [serializable$j], function () {
        return '';
      })), _class2$Z)) || _class$$);

      function makeCreateNodeFactory(create_) {
        return {
          listEntries: function listEntries(context) {
            return [{
              arg: {
                type: 'clip-motion'
              },
              menu: 'i18n:ENGINE.animation_graph.pose_graph_node_sub_menus.play_or_sample_clip_motion'
            }, {
              arg: {
                type: 'animation-blend-1d'
              },
              menu: 'i18n:ENGINE.animation_graph.pose_graph_node_sub_menus.play_or_sample_animation_blend_1d'
            }, {
              arg: {
                type: 'animation-blend-2d'
              },
              menu: 'i18n:ENGINE.animation_graph.pose_graph_node_sub_menus.play_or_sample_animation_blend_2d'
            }];
          },
          create: function create(arg) {
            var motion = null;
            switch (arg.type) {
              case 'clip-motion':
                motion = new ClipMotion();
                break;
              case 'animation-blend-1d':
                motion = new AnimationBlend1D();
                break;
              case 'animation-blend-2d':
                motion = new AnimationBlend2D();
                break;
            }
            return create_(motion);
          }
        };
      }

      var _dec$$, _dec2$X, _dec3$K, _dec4$A, _dec5$v, _dec6$g, _class$_, _class2$Y, _initializer$Q, _initializer2$J, _descriptor$9, _descriptor2$4;
      var ZERO_DURATION_THRESHOLD = 1e-5;
      var PoseNodePlayMotion = (_dec$$ = ccclass$n(CLASS_NAME_PREFIX_ANIM + "PoseNodePlayMotion"), _dec2$X = poseGraphNodeCategory(POSE_GRAPH_NODE_MENU_PREFIX_POSE), _dec3$K = poseGraphCreateNodeFactory(makeCreateNodeFactory(function (motion) {
        var node = new PoseNodePlayMotion();
        node.motion = motion;
        return node;
      })), _dec4$A = poseGraphNodeAppearance({
        themeColor: '#227F9B'
      }), _dec5$v = input({
        type: PoseGraphType.FLOAT
      }), _dec6$g = input({
        type: PoseGraphType.FLOAT
      }), _dec$$(_class$_ = _dec2$X(_class$_ = _dec3$K(_class$_ = _dec4$A(_class$_ = (_class2$Y = function (_PoseNode) {
        _inheritsLoose(PoseNodePlayMotion, _PoseNode);
        function PoseNodePlayMotion() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _PoseNode.call.apply(_PoseNode, [this].concat(args)) || this;
          _this.motion = _initializer$Q && _initializer$Q();
          _this.syncInfo = _initializer2$J && _initializer2$J();
          _initializerDefineProperty(_this, "startTime", _descriptor$9, _assertThisInitialized(_this));
          _initializerDefineProperty(_this, "speedMultiplier", _descriptor2$4, _assertThisInitialized(_this));
          _this._workspace = null;
          _this._runtimeSyncRecord = undefined;
          return _this;
        }
        var _proto = PoseNodePlayMotion.prototype;
        _proto.bind = function bind(context) {
          var motion = this.motion;
          if (!motion) {
            return;
          }
          var motionEval = motion[createEval](context, false);
          if (!motionEval) {
            return;
          }
          this._workspace = new Workspace$2(motionEval, motionEval.createPort());
          if (this.syncInfo.group) {
            this._runtimeSyncRecord = context.motionSyncManager.register(this.syncInfo);
          }
        };
        _proto.settle = function settle(context) {};
        _proto.reenter = function reenter() {
          if (this._workspace) {
            var runtimeSyncRecord = this._runtimeSyncRecord,
              duration = this._workspace.motionEval.duration;
            this._forceEvaluateEvaluation();
            var startTimeNormalized = duration < ZERO_DURATION_THRESHOLD ? 0.0 : clamp01(this.startTime / duration);
            if (runtimeSyncRecord) {
              runtimeSyncRecord.notifyRenter(startTimeNormalized);
            } else {
              this._workspace.normalizedTime = startTimeNormalized;
            }
            this._workspace.lastIndicativeWeight = 0.0;
          }
        };
        _proto.doUpdate = function doUpdate(context) {
          if (this._workspace) {
            var deltaTime = context.deltaTime;
            var runtimeSyncRecord = this._runtimeSyncRecord;
            var duration = this._workspace.motionEval.duration;
            var normalizedDeltaTime = 0.0;
            if (duration > ZERO_DURATION_THRESHOLD) {
              normalizedDeltaTime = deltaTime * this.speedMultiplier / duration;
            }
            if (runtimeSyncRecord) {
              runtimeSyncRecord.notifyUpdate(normalizedDeltaTime, context.indicativeWeight);
            } else {
              this._workspace.normalizedTime += normalizedDeltaTime;
            }
            this._workspace.lastIndicativeWeight = context.indicativeWeight;
          }
        };
        _proto.doEvaluate = function doEvaluate(context) {
          if (!this._workspace) {
            return context.pushDefaultedPose();
          } else {
            var normalizedTime = this._runtimeSyncRecord ? this._runtimeSyncRecord.getSyncedEnterTime() : this._workspace.normalizedTime;
            return this._workspace.motionEvalPort.evaluate(normalizedTime, context);
          }
        };
        _createClass(PoseNodePlayMotion, [{
          key: "lastIndicativeWeight",
          get: function get() {
            var _this$_workspace$last, _this$_workspace;
            return (_this$_workspace$last = (_this$_workspace = this._workspace) === null || _this$_workspace === void 0 ? void 0 : _this$_workspace.lastIndicativeWeight) !== null && _this$_workspace$last !== void 0 ? _this$_workspace$last : 0.0;
          }
        }, {
          key: "elapsedMotionTime",
          get: function get() {
            var _this$_workspace$norm, _this$_workspace2;
            return (_this$_workspace$norm = (_this$_workspace2 = this._workspace) === null || _this$_workspace2 === void 0 ? void 0 : _this$_workspace2.normalizedTime) !== null && _this$_workspace$norm !== void 0 ? _this$_workspace$norm : 0.0;
          }
        }]);
        return PoseNodePlayMotion;
      }(PoseNode), (_initializer$Q = applyDecoratedInitializer(_class2$Y.prototype, "motion", [serializable$j], function () {
        return new ClipMotion();
      }), _initializer2$J = applyDecoratedInitializer(_class2$Y.prototype, "syncInfo", [serializable$j], function () {
        return new MotionSyncInfo();
      }), _descriptor$9 = _applyDecoratedDescriptor(_class2$Y.prototype, "startTime", [serializable$j, _dec5$v], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return 0.0;
        }
      }), _descriptor2$4 = _applyDecoratedDescriptor(_class2$Y.prototype, "speedMultiplier", [serializable$j, _dec6$g], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return 1.0;
        }
      })), _class2$Y)) || _class$_) || _class$_) || _class$_) || _class$_);
      var Workspace$2 = function Workspace(motionEval, motionEvalPort) {
        this.normalizedTime = 0.0;
        this.lastIndicativeWeight = 0.0;
        this.motionEval = motionEval;
        this.motionEvalPort = motionEvalPort;
      };

      function isEvaluatableNode(node) {
        return node instanceof PoseNode || node instanceof PureValueNode;
      }
      var InstantiatedPoseGraph = function () {
        function InstantiatedPoseGraph(_rootPoseNode, _countingPlayMotionNodes) {
          this._rootPoseNode = _rootPoseNode;
          this._countingPlayMotionNodes = _countingPlayMotionNodes;
        }
        var _proto = InstantiatedPoseGraph.prototype;
        _proto.bind = function bind(context) {
          var _this$_rootPoseNode;
          (_this$_rootPoseNode = this._rootPoseNode) === null || _this$_rootPoseNode === void 0 ? void 0 : _this$_rootPoseNode.bind(context);
        };
        _proto.settle = function settle(context) {
          var _this$_rootPoseNode2;
          (_this$_rootPoseNode2 = this._rootPoseNode) === null || _this$_rootPoseNode2 === void 0 ? void 0 : _this$_rootPoseNode2.settle(context);
        };
        _proto.reenter = function reenter() {
          var _this$_rootPoseNode3;
          (_this$_rootPoseNode3 = this._rootPoseNode) === null || _this$_rootPoseNode3 === void 0 ? void 0 : _this$_rootPoseNode3.reenter();
        };
        _proto.update = function update(context) {
          var _this$_rootPoseNode4;
          (_this$_rootPoseNode4 = this._rootPoseNode) === null || _this$_rootPoseNode4 === void 0 ? void 0 : _this$_rootPoseNode4.update(context);
        };
        _proto.evaluate = function evaluate(context) {
          var _this$_rootPoseNode$e, _this$_rootPoseNode5;
          return (_this$_rootPoseNode$e = (_this$_rootPoseNode5 = this._rootPoseNode) === null || _this$_rootPoseNode5 === void 0 ? void 0 : _this$_rootPoseNode5.evaluate(context, PoseTransformSpaceRequirement.LOCAL)) !== null && _this$_rootPoseNode$e !== void 0 ? _this$_rootPoseNode$e : null;
        };
        _proto.countMotionTime = function countMotionTime() {
          var playMotionNodes = this._countingPlayMotionNodes;
          if (!playMotionNodes) {
            {
              assertIsTrue(false, "Should not call countMotionTime() on this pose graph " + "since \"mayCountMotionTime\" was not passed to instantiatePoseGraph()");
            }
            return 0.0;
          }
          var maxWeightedTime = 0.0;
          var maxWeight = Number.NEGATIVE_INFINITY;
          for (var iPlayMotionNode = 0; iPlayMotionNode < playMotionNodes.length; ++iPlayMotionNode) {
            var _playMotionNodes$iPla = playMotionNodes[iPlayMotionNode],
              elapsedMotionTime = _playMotionNodes$iPla.elapsedMotionTime,
              lastIndicativeWeight = _playMotionNodes$iPla.lastIndicativeWeight;
            if (lastIndicativeWeight > maxWeight) {
              maxWeight = lastIndicativeWeight;
              maxWeightedTime = elapsedMotionTime;
            }
          }
          return maxWeightedTime;
        };
        return InstantiatedPoseGraph;
      }();
      function instantiatePoseGraph(graph, linkContext, mayCountMotionTime) {
        if (mayCountMotionTime === void 0) {
          mayCountMotionTime = false;
        }
        var outputNode = graph.outputNode;
        var outputNodeShell = graph.getShell(outputNode);
        assertIsTrue(outputNodeShell);
        var bindings = outputNodeShell.getBindings();
        assertIsTrue(bindings.length < 2);
        if (bindings.length === 0) {
          return new InstantiatedPoseGraph(undefined, mayCountMotionTime ? [] : undefined);
        }
        var binding = bindings[0];
        assertIsTrue(binding.outputIndex === 0);
        assertIsTrue(binding.producer instanceof PoseNode);
        var instantiationMap = new Map();
        var mainRecord = instantiateNode(graph, binding.producer, instantiationMap, linkContext);
        assertIsTrue(mainRecord instanceof PoseNode);
        return new InstantiatedPoseGraph(mainRecord, mayCountMotionTime ? Array.from(instantiationMap.values()).filter(function (node) {
          return node instanceof PoseNodePlayMotion;
        }) : undefined);
      }
      function instantiateNode(graph, node, instantiationMap, linkContext) {
        var shell = graph.getShell(node);
        assertIsTrue(shell, "Want to instantiate an unbound graph?");
        var existing = instantiationMap.get(node);
        if (existing) {
          return existing;
        }
        var instantiated = instantiate(node);
        if ('__callOnAfterDeserializeRecursive' in instantiated) {
          instantiated.__callOnAfterDeserializeRecursive();
        }
        if (instantiated instanceof PureValueNode) {
          instantiated.link(linkContext);
        }
        var consumerNode = instantiated;
        var runtimePVNodePropertyBindings = [];
        for (var _iterator = _createForOfIteratorHelperLoose(shell.getBindings()), _step; !(_step = _iterator()).done;) {
          var _step$value = _step.value,
            producerNode = _step$value.producer,
            producerOutputIndex = _step$value.outputIndex,
            consumerInputPath = _step$value.inputPath;
          if (!isEvaluatableNode(producerNode)) {
            warn("There's a input bound to a node with unrecognized type.");
            continue;
          }
          var producer = instantiateNode(graph, producerNode, instantiationMap, linkContext);
          if (producer instanceof PoseNode) {
            assertIsTrue(consumerNode instanceof PoseNode);
            linkPoseNode(consumerNode, consumerInputPath, producer, producerOutputIndex);
          } else {
            var runtimePVNodePropertyBinding = linkPVNode(consumerNode, consumerInputPath, producer, producerOutputIndex);
            if (runtimePVNodePropertyBinding) {
              runtimePVNodePropertyBindings.push(runtimePVNodePropertyBinding);
            }
          }
        }
        var dependencyEvaluation = new DependencyEvaluation(runtimePVNodePropertyBindings);
        var evaluation;
        if (consumerNode instanceof PoseNode) {
          consumerNode._setDependencyEvaluation(dependencyEvaluation);
          evaluation = consumerNode;
        } else {
          var pureValueNodeEvaluation = new RuntimePVNodeEvaluation(consumerNode, dependencyEvaluation);
          evaluation = pureValueNodeEvaluation;
        }
        instantiationMap.set(node, evaluation);
        return evaluation;
      }
      var DependencyEvaluation = function () {
        function DependencyEvaluation(bindingEvaluations) {
          this._bindingEvaluations = void 0;
          this._bindingEvaluations = bindingEvaluations;
        }
        var _proto2 = DependencyEvaluation.prototype;
        _proto2.evaluate = function evaluate() {
          var bindingEvaluations = this._bindingEvaluations;
          for (var _iterator2 = _createForOfIteratorHelperLoose(bindingEvaluations), _step2; !(_step2 = _iterator2()).done;) {
            var binding = _step2.value;
            binding.evaluate();
          }
        };
        return DependencyEvaluation;
      }();
      var RuntimePVNodeEvaluation = function () {
        function RuntimePVNodeEvaluation(_node, _dependency) {
          this._outputs = void 0;
          this._node = _node;
          this._dependency = _dependency;
          this._outputs = new Array(_node.outputCount);
        }
        var _proto3 = RuntimePVNodeEvaluation.prototype;
        _proto3.getDefaultOutput = function getDefaultOutput() {
          return this.getOutput(0);
        };
        _proto3.getOutput = function getOutput(outputIndex) {
          return this._outputs[outputIndex];
        };
        _proto3.evaluate = function evaluate() {
          var node = this._node,
            dependency = this._dependency;
          dependency.evaluate();
          node.selfEvaluate(this._outputs);
        };
        _createClass(RuntimePVNodeEvaluation, [{
          key: "node",
          get: function get() {
            return this._node;
          }
        }, {
          key: "outputCount",
          get: function get() {
            return this._outputs.length;
          }
        }]);
        return RuntimePVNodeEvaluation;
      }();
      function linkPoseNode(consumerNode, consumerInputPath, producerNode, producerOutputIndex) {
        var consumerPropertyKey = consumerInputPath[0],
          _consumerInputPath$ = consumerInputPath[1],
          consumerElementIndex = _consumerInputPath$ === void 0 ? -1 : _consumerInputPath$;
        if (!(consumerPropertyKey in consumerNode)) {
          warn("Invalid binding: consumer node has no property " + consumerPropertyKey);
          return;
        }
        if (producerOutputIndex !== 0) {
          warn("Node " + producerNode.toString() + " does not have specified output " + producerOutputIndex + ".");
          return;
        }
        var consumerProperty = consumerNode[consumerPropertyKey];
        if (consumerElementIndex < 0) {
          if (consumerProperty !== null) {
            warn("Invalid binding: consumer node's input " + consumerPropertyKey + " should be leaved as evaluation before evaluation.");
            return;
          }
          consumerNode[consumerPropertyKey] = producerNode;
          return;
        }
        if (!Array.isArray(consumerProperty)) {
          warn("Invalid binding: consumer node's input " + consumerPropertyKey + " should be an array.");
          return;
        }
        if (consumerElementIndex >= consumerProperty.length) {
          warn("Invalid binding: consumer node's input " + consumerPropertyKey + " " + ("have length " + consumerProperty.length + " but the binding specified " + consumerElementIndex));
          return;
        }
        if (consumerProperty[consumerElementIndex] !== null) {
          warn("Invalid binding: consumer node's input " + consumerPropertyKey + "[" + consumerElementIndex + "] should be leaved as null before evaluation");
          return;
        }
        consumerProperty[consumerElementIndex] = producerNode;
      }
      var RuntimePVNodePlainPropertyBinding = function () {
        function RuntimePVNodePlainPropertyBinding(_consumerNode, _consumerPropertyKey, _producerRecord, _producerOutputIndex) {
          this._consumerNode = _consumerNode;
          this._consumerPropertyKey = _consumerPropertyKey;
          this._producerRecord = _producerRecord;
          this._producerOutputIndex = _producerOutputIndex;
        }
        var _proto4 = RuntimePVNodePlainPropertyBinding.prototype;
        _proto4.evaluate = function evaluate() {
          this._producerRecord.evaluate();
          this._consumerNode[this._consumerPropertyKey] = this._producerRecord.getOutput(this._producerOutputIndex);
        };
        return RuntimePVNodePlainPropertyBinding;
      }();
      var RuntimePVNodeArrayElementPropertyBinding = function () {
        function RuntimePVNodeArrayElementPropertyBinding(_consumerNode, _consumerPropertyKey, _consumerElementIndex, _producerRecord, _producerOutputIndex) {
          this._consumerNode = _consumerNode;
          this._consumerPropertyKey = _consumerPropertyKey;
          this._consumerElementIndex = _consumerElementIndex;
          this._producerRecord = _producerRecord;
          this._producerOutputIndex = _producerOutputIndex;
        }
        var _proto5 = RuntimePVNodeArrayElementPropertyBinding.prototype;
        _proto5.evaluate = function evaluate() {
          this._producerRecord.evaluate();
          this._consumerNode[this._consumerPropertyKey][this._consumerElementIndex] = this._producerRecord.getOutput(this._producerOutputIndex);
        };
        return RuntimePVNodeArrayElementPropertyBinding;
      }();
      function linkPVNode(consumerNode, consumerInputPath, producerRecord, producerOutputIndex) {
        var consumerPropertyKey = consumerInputPath[0],
          _consumerInputPath$2 = consumerInputPath[1],
          consumerElementIndex = _consumerInputPath$2 === void 0 ? -1 : _consumerInputPath$2;
        if (!(consumerPropertyKey in consumerNode)) {
          warn("Invalid binding: consumer node has no property " + consumerPropertyKey);
          return undefined;
        }
        var consumerProperty = consumerNode[consumerPropertyKey];
        if (consumerElementIndex < 0) {
          return new RuntimePVNodePlainPropertyBinding(consumerNode, consumerPropertyKey, producerRecord, producerOutputIndex);
        }
        if (!Array.isArray(consumerProperty)) {
          warn("Invalid binding: consumer node's input " + consumerPropertyKey + " should be an array.");
          return undefined;
        }
        if (consumerElementIndex >= consumerProperty.length) {
          warn("Invalid binding: consumer node's input " + consumerPropertyKey + " " + ("have length " + consumerProperty.length + " but the binding specified " + consumerElementIndex));
          return undefined;
        }
        return new RuntimePVNodeArrayElementPropertyBinding(consumerNode, consumerPropertyKey, consumerElementIndex, producerRecord, producerOutputIndex);
      }

      var _emptyClipStatusesIte;
      var MAX_TRANSITIONS_PER_FRAME = 16;
      var TopLevelStateMachineEvaluation = function () {
        function TopLevelStateMachineEvaluation(stateMachine, name, context) {
          this.passthroughWeight = 1.0;
          this._motionStates = [];
          this._proceduralPoseStates = [];
          this._topLevelEntry = void 0;
          this._topLevelExit = void 0;
          this._currentNode = void 0;
          this._pendingTransitionPath = [];
          this._activatedTransitions = [];
          this._activatedTransitionPool = ActivatedTransition.createPool(4);
          this._updateContextGenerator = new AnimationGraphUpdateContextGenerator();
          this._conditionEvaluationContext = new ConditionEvaluationContextImpl();
          this._additive = false;
          this._additive = context.additive;
          this.name = name;
          this._controller = context.controller;
          var _this$_addStateMachin = this._addStateMachine(stateMachine, null, context, name),
            entry = _this$_addStateMachin.entry,
            exit = _this$_addStateMachin.exit;
          this._topLevelEntry = entry;
          this._topLevelExit = exit;
          this._currentNode = entry;
          entry.increaseActiveReference();
          this._resetTrigger = context.triggerResetter;
        }
        var _proto = TopLevelStateMachineEvaluation.prototype;
        _proto.settle = function settle(context) {
          var proceduralPoseStates = this._proceduralPoseStates;
          var nProceduralPoseStates = proceduralPoseStates.length;
          for (var iState = 0; iState < nProceduralPoseStates; ++iState) {
            var state = proceduralPoseStates[iState];
            state.settle(context);
          }
        };
        _proto.reenter = function reenter() {
          for (var _iterator = _createForOfIteratorHelperLoose(this._activatedTransitions), _step; !(_step = _iterator()).done;) {
            var transition = _step.value;
            transition.destination.decreaseActiveReference();
            this._activatedTransitionPool.free(transition);
          }
          this._activatedTransitions.length = 0;
          this._topLevelEntry.increaseActiveReference();
          this._currentNode.decreaseActiveReference();
          this._currentNode = this._topLevelEntry;
        };
        _proto.update = function update(context) {
          assertIsTrue(!this.exited);
          this._loopMatchTransitions();
          this._resetStateTickFlagsAndWeights();
          this._updateActivatedTransitions(context.deltaTime);
          this._commitStateUpdates(context);
        };
        _proto.evaluate = function evaluate(context) {
          var sampled = this._sample(context);
          if (sampled) {
            return sampled;
          }
          return this._pushNullishPose(context);
        };
        _proto.getCurrentStateStatus = function getCurrentStateStatus() {
          var currentNode = this._currentNode;
          if (currentNode.kind === NodeKind.animation) {
            return currentNode.getStatus();
          } else if (currentNode.kind === NodeKind.procedural) {
            return currentNode.getStatus();
          } else {
            return null;
          }
        };
        _proto.getCurrentClipStatuses = function getCurrentClipStatuses() {
          var currentNode = this._currentNode;
          if (currentNode.kind === NodeKind.animation) {
            return currentNode.getClipStatuses(currentNode.absoluteWeight);
          } else {
            return emptyClipStatusesIterable;
          }
        };
        _proto.getCurrentTransition = function getCurrentTransition(transitionStatus) {
          var activatedTransitions = this._activatedTransitions;
          if (activatedTransitions.length === 0) {
            return false;
          }
          var lastActivatedTransition = activatedTransitions[activatedTransitions.length - 1];
          var baseDurationState = activatedTransitions.length === 1 ? this._currentNode : activatedTransitions[activatedTransitions.length - 2].destination;
          var absoluteDuration = lastActivatedTransition.getAbsoluteDuration(baseDurationState);
          transitionStatus.duration = absoluteDuration;
          transitionStatus.time = lastActivatedTransition.normalizedElapsedTime * absoluteDuration;
          return true;
        };
        _proto.getNextStateStatus = function getNextStateStatus() {
          var activatedTransitions = this._activatedTransitions;
          if (activatedTransitions.length === 0) {
            return null;
          }
          var lastState = activatedTransitions[activatedTransitions.length - 1].destination;
          switch (lastState.kind) {
            default:
              break;
            case NodeKind.procedural:
              return lastState.getStatus();
            case NodeKind.animation:
              return lastState.getStatus();
          }
          return null;
        };
        _proto.getNextClipStatuses = function getNextClipStatuses() {
          var _lastState$getClipSta;
          var activatedTransitions = this._activatedTransitions;
          if (activatedTransitions.length === 0) {
            return emptyClipStatusesIterable;
          }
          var lastActivatedTransition = activatedTransitions[activatedTransitions.length - 1];
          var lastState = lastActivatedTransition.destination;
          switch (lastState.kind) {
            default:
              return emptyClipStatusesIterable;
            case NodeKind.animation:
              return (_lastState$getClipSta = lastState.getClipStatuses(lastActivatedTransition.destination.absoluteWeight)) !== null && _lastState$getClipSta !== void 0 ? _lastState$getClipSta : emptyClipStatusesIterable;
          }
        };
        _proto.overrideClips = function overrideClips(context) {
          var motionStates = this._motionStates;
          var nMotionStates = motionStates.length;
          for (var iMotionState = 0; iMotionState < nMotionStates; ++iMotionState) {
            var node = motionStates[iMotionState];
            node.overrideClips(context);
          }
        };
        _proto._addStateMachine = function _addStateMachine(graph, parentStateMachineInfo, context, __DEBUG_ID__) {
          var _this = this;
          var nodes = Array.from(graph.states());
          var entryEval;
          var anyNode;
          var exitEval;
          var nodeEvaluations = nodes.map(function (node) {
            if (node instanceof MotionState) {
              var motionStateEval = new VMSMEval(node, context);
              _this._motionStates.push(motionStateEval);
              return motionStateEval;
            } else if (node === graph.entryState) {
              return entryEval = new SpecialStateEval(node, NodeKind.entry, node.name);
            } else if (node === graph.exitState) {
              return exitEval = new SpecialStateEval(node, NodeKind.exit, node.name);
            } else if (node === graph.anyState) {
              return anyNode = new SpecialStateEval(node, NodeKind.any, node.name);
            } else if (node instanceof EmptyState) {
              return new EmptyStateEval(node);
            } else if (node instanceof ProceduralPoseState_) {
              var stateEval = new ProceduralPoseStateEval(node, context);
              _this._proceduralPoseStates.push(stateEval);
              return stateEval;
            } else {
              assertIsTrue(node instanceof SubStateMachine);
              return null;
            }
          });
          assertIsNonNullable(entryEval, 'Entry node is missing');
          assertIsNonNullable(exitEval, 'Exit node is missing');
          assertIsNonNullable(anyNode, 'Any node is missing');
          var stateMachineInfo = {
            components: null,
            parent: parentStateMachineInfo,
            entry: entryEval,
            exit: exitEval,
            any: anyNode
          };
          for (var iNode = 0; iNode < nodes.length; ++iNode) {
            var nodeEval = nodeEvaluations[iNode];
            if (nodeEval) {
              nodeEval.stateMachine = stateMachineInfo;
            }
          }
          var subStateMachineInfos = nodes.map(function (node) {
            if (node instanceof SubStateMachine) {
              var subStateMachineInfo = _this._addStateMachine(node.stateMachine, stateMachineInfo, context, __DEBUG_ID__ + "/" + node.name);
              subStateMachineInfo.components = new InstantiatedComponents(node);
              return subStateMachineInfo;
            } else {
              return null;
            }
          });
          {
            for (var _iterator2 = _createForOfIteratorHelperLoose(nodeEvaluations), _step2; !(_step2 = _iterator2()).done;) {
              var _nodeEval = _step2.value;
              if (_nodeEval) {
                _nodeEval.setPrefix_debug(__DEBUG_ID__ + "/");
              }
            }
          }
          for (var _iNode = 0; _iNode < nodes.length; ++_iNode) {
            var node = nodes[_iNode];
            var outgoingTemplates = graph.getOutgoings(node);
            var fromNode = void 0;
            if (node instanceof SubStateMachine) {
              var subStateMachineInfo = subStateMachineInfos[_iNode];
              assertIsNonNullable(subStateMachineInfo);
              fromNode = subStateMachineInfo.exit;
            } else {
              var _nodeEval2 = nodeEvaluations[_iNode];
              assertIsNonNullable(_nodeEval2);
              fromNode = _nodeEval2;
            }
            var _loop = function _loop() {
              var outgoing = _step3.value;
              var outgoingNode = outgoing.to;
              var iOutgoingNode = nodes.findIndex(function (nodeTemplate) {
                return nodeTemplate === outgoing.to;
              });
              if (iOutgoingNode < 0) {
                assertIsTrue(false, 'Bad animation data');
              }
              var toNode;
              if (outgoingNode instanceof SubStateMachine) {
                var _subStateMachineInfo = subStateMachineInfos[iOutgoingNode];
                assertIsNonNullable(_subStateMachineInfo);
                toNode = _subStateMachineInfo.entry;
              } else {
                var _nodeEval3 = nodeEvaluations[iOutgoingNode];
                assertIsNonNullable(_nodeEval3);
                if (_nodeEval3 instanceof VMSMEval) {
                  toNode = _nodeEval3.entry;
                } else {
                  toNode = _nodeEval3;
                }
              }
              var conditions = outgoing.conditions.map(function (condition) {
                return condition[createEval](context);
              });
              var transitionEval = {
                conditions: conditions,
                to: toNode,
                triggers: undefined,
                duration: 0.0,
                normalizedDuration: false,
                destinationStart: 0.0,
                relativeDestinationStart: false,
                exitCondition: 0.0,
                exitConditionEnabled: false,
                activated: false,
                startEventBinding: undefined,
                endEventBinding: undefined
              };
              if (isAnimationTransition(outgoing) || outgoing instanceof EmptyStateTransition || outgoing instanceof ProceduralPoseTransition_) {
                transitionEval.duration = outgoing.duration;
                transitionEval.destinationStart = outgoing.destinationStart;
                transitionEval.relativeDestinationStart = outgoing.relativeDestinationStart;
                if (outgoing.startEventBinding.isBound) {
                  transitionEval.startEventBinding = outgoing.startEventBinding;
                }
                if (outgoing.endEventBinding.isBound) {
                  transitionEval.endEventBinding = outgoing.endEventBinding;
                }
                if (isAnimationTransition(outgoing)) {
                  transitionEval.normalizedDuration = outgoing.relativeDuration;
                  transitionEval.exitConditionEnabled = outgoing.exitConditionEnabled;
                  transitionEval.exitCondition = outgoing.exitCondition;
                }
              }
              transitionEval.conditions.forEach(function (conditionEval, iCondition) {
                var condition = outgoing.conditions[iCondition];
                if (condition instanceof TriggerCondition && condition.trigger) {
                  var _transitionEval$trigg;
                  ((_transitionEval$trigg = transitionEval.triggers) !== null && _transitionEval$trigg !== void 0 ? _transitionEval$trigg : transitionEval.triggers = []).push(condition.trigger);
                }
              });
              fromNode.addTransition(transitionEval);
            };
            for (var _iterator3 = _createForOfIteratorHelperLoose(outgoingTemplates), _step3; !(_step3 = _iterator3()).done;) {
              _loop();
            }
          }
          return stateMachineInfo;
        };
        _proto._loopMatchTransitions = function _loopMatchTransitions() {
          var pendingTransitionPath = this._pendingTransitionPath,
            activatedTransitions = this._activatedTransitions;
          assertIsTrue(pendingTransitionPath.length === 0);
          var matchingSource = activatedTransitions.length === 0 ? this._currentNode : activatedTransitions[activatedTransitions.length - 1].destination;
          for (var iterations = 0;; ++iterations) {
            if (iterations >= MAX_TRANSITIONS_PER_FRAME) {
              var prettyPath = '';
              {
                var lastDestination = activatedTransitions[activatedTransitions.length - 1].destination;
                var loopFormPosition = -1;
                for (var i = activatedTransitions.length - 2; i >= 0; --i) {
                  if (activatedTransitions[i].destination === lastDestination) {
                    loopFormPosition = i;
                    break;
                  }
                }
                prettyPath = this._currentNode.name + " --> ... --> ";
                var pathToPrint = loopFormPosition < 0 ? activatedTransitions.slice(-MAX_TRANSITIONS_PER_FRAME) : activatedTransitions.slice(loopFormPosition);
                prettyPath += "" + pathToPrint.map(function (t) {
                  return t.destination.name;
                }).join(' --> ');
              }
              warnID(14000, MAX_TRANSITIONS_PER_FRAME, prettyPath);
              break;
            }
            var transition = this._matchNextTransition(matchingSource);
            if (!transition) {
              break;
            }
            var destinationState = transition.to;
            var currentMatchingSource = matchingSource;
            matchingSource = destinationState;
            if (!isRealState(destinationState)) {
              pendingTransitionPath.push(transition);
              continue;
            }
            if (destinationState === currentMatchingSource) {
              break;
            }
            this._activateTransition(pendingTransitionPath, transition);
            pendingTransitionPath.length = 0;
          }
          pendingTransitionPath.length = 0;
        };
        _proto._resetStateTickFlagsAndWeights = function _resetStateTickFlagsAndWeights() {
          var currentNode = this._currentNode,
            activatedTransitions = this._activatedTransitions;
          currentNode.resetTickFlagsAndWeight();
          for (var iTransition = 0; iTransition < activatedTransitions.length; ++iTransition) {
            var destination = activatedTransitions[iTransition].destination;
            destination.resetTickFlagsAndWeight();
          }
        };
        _proto._commitStateUpdates = function _commitStateUpdates(parentContext) {
          var currentNode = this._currentNode,
            activatedTransitions = this._activatedTransitions;
            this._updateContextGenerator;
          this._commitStateUpdate(currentNode, parentContext);
          for (var iTransition = 0; iTransition < activatedTransitions.length; ++iTransition) {
            var transition = activatedTransitions[iTransition];
            var destination = transition.destination;
            this._commitStateUpdate(destination, parentContext);
          }
        };
        _proto._commitStateUpdate = function _commitStateUpdate(state, parentContext) {
          var updateContextGenerator = this._updateContextGenerator;
          if (state.testTickFlag(StateTickFlag.UPDATED)) {
            return;
          }
          state.setTickFlag(StateTickFlag.UPDATED);
          if (state.kind === NodeKind.animation) {
            state.update(parentContext.deltaTime, this._controller);
          } else if (state.kind === NodeKind.procedural) {
            var updateContext = updateContextGenerator.generate(parentContext.deltaTime, parentContext.indicativeWeight * state.absoluteWeight);
            state.update(updateContext);
          }
        };
        _proto._sample = function _sample(context) {
          var currentNode = this._currentNode,
            activatedTransitions = this._activatedTransitions;
          var passthroughWeight = 1.0;
          var finalPose = null;
          var sumActualBlendedWeight = 0.0;
          if (currentNode.kind === NodeKind.animation) {
            var _currentNode$evaluate;
            finalPose = (_currentNode$evaluate = currentNode.evaluate(context)) !== null && _currentNode$evaluate !== void 0 ? _currentNode$evaluate : this._pushNullishPose(context);
          } else if (currentNode.kind === NodeKind.procedural) {
            var _currentNode$evaluate2;
            finalPose = (_currentNode$evaluate2 = currentNode.evaluate(context)) !== null && _currentNode$evaluate2 !== void 0 ? _currentNode$evaluate2 : this._pushNullishPose(context);
          } else {
            passthroughWeight -= currentNode.absoluteWeight;
            finalPose = null;
          }
          if (finalPose) {
            sumActualBlendedWeight = currentNode.absoluteWeight;
          }
          currentNode.setTickFlag(StateTickFlag.EVALUATED);
          for (var iTransition = 0; iTransition < activatedTransitions.length; ++iTransition) {
            var transition = activatedTransitions[iTransition];
            var destination = transition.destination;
            if (destination.testTickFlag(StateTickFlag.EVALUATED)) {
              continue;
            }
            destination.setTickFlag(StateTickFlag.EVALUATED);
            var destAbsoluteWeight = destination.absoluteWeight;
            var destPose = void 0;
            if (destination.kind === NodeKind.empty) {
              passthroughWeight -= destAbsoluteWeight;
              destPose = null;
            } else {
              var _destination$evaluate;
              destPose = (_destination$evaluate = destination.evaluate(context)) !== null && _destination$evaluate !== void 0 ? _destination$evaluate : this._pushNullishPose(context);
            }
            if (!destPose) {
              continue;
            }
            if (!finalPose) {
              finalPose = destPose;
            } else {
              sumActualBlendedWeight += destAbsoluteWeight;
              if (sumActualBlendedWeight) {
                var t = destAbsoluteWeight / sumActualBlendedWeight;
                blendPoseInto(finalPose, destPose, t);
                context.popPose();
              } else {
                finalPose = destPose;
              }
            }
          }
          this.passthroughWeight = passthroughWeight;
          return finalPose;
        };
        _proto._pushNullishPose = function _pushNullishPose(context) {
          return this._additive ? context.pushZeroDeltaPose() : context.pushDefaultedPose();
        };
        _proto._matchNextTransition = function _matchNextTransition(sourceState) {
          var transition = this._matchTransition(sourceState, sourceState);
          if (transition) {
            return transition;
          }
          if (sourceState.kind === NodeKind.animation || sourceState.kind === NodeKind.procedural) {
            var _transition = this._matchAnyScoped(sourceState);
            if (_transition) {
              return _transition;
            }
          }
          return null;
        };
        _proto._matchAnyScoped = function _matchAnyScoped(realNode) {
          for (var ancestor = realNode.stateMachine; ancestor !== null; ancestor = ancestor.parent) {
            var transition = this._matchTransition(ancestor.any, realNode);
            if (transition) {
              return transition;
            }
          }
          return null;
        };
        _proto._matchTransition = function _matchTransition(node, realNode) {
          assertIsTrue(node === realNode || node.kind === NodeKind.any);
          var conditionEvaluationContext = this._conditionEvaluationContext;
          conditionEvaluationContext.set(realNode);
          var outgoingTransitions = node.outgoingTransitions;
          var nTransitions = outgoingTransitions.length;
          for (var iTransition = 0; iTransition < nTransitions; ++iTransition) {
            var transition = outgoingTransitions[iTransition];
            if (transition.activated) {
              continue;
            }
            var conditions = transition.conditions;
            var nConditions = conditions.length;
            if (nConditions === 0) {
              if (node.kind === NodeKind.entry || node.kind === NodeKind.exit) {
                {
                  conditionEvaluationContext.unset();
                }
                return transition;
              }
              if (!transition.exitConditionEnabled) {
                continue;
              }
            }
            if (realNode.kind === NodeKind.animation && transition.exitConditionEnabled) {
              var exitTime = realNode.duration * transition.exitCondition;
              var currentStateTime = realNode.time;
              if (currentStateTime < exitTime) {
                break;
              }
            }
            var satisfied = true;
            for (var iCondition = 0; iCondition < nConditions; ++iCondition) {
              var condition = conditions[iCondition];
              if (!condition.eval(this._conditionEvaluationContext)) {
                satisfied = false;
                break;
              }
            }
            if (!satisfied) {
              continue;
            }
            {
              conditionEvaluationContext.unset();
            }
            return transition;
          }
          {
            conditionEvaluationContext.unset();
          }
          return null;
        };
        _proto._activateTransition = function _activateTransition(prefix, lastTransition) {
          var destinationState = lastTransition.to;
          assertIsTrue(isRealState(destinationState));
          var activatedTransition = this._activatedTransitionPool.alloc();
          activatedTransition.reset(prefix, lastTransition);
          this._activatedTransitions.push(activatedTransition);
          var nTransitions = activatedTransition.path.length;
          for (var iTransition = 0; iTransition < nTransitions; ++iTransition) {
            var transition = activatedTransition.path[iTransition];
            this._resetTriggersOnTransition(transition);
          }
          for (var iDetailedTransition = 0; iDetailedTransition < activatedTransition.path.length; ++iDetailedTransition) {
            var detailedTransition = activatedTransition.path[iDetailedTransition];
            this._callEnterMethods(detailedTransition.to);
          }
          assertIsTrue(this._activatedTransitions.length > 0);
          var previousState = this._activatedTransitions.length === 1 ? this._currentNode : this._activatedTransitions[this._activatedTransitions.length - 2].destination;
          if (previousState instanceof EventifiedStateEval) {
            if (previousState.transitionOutEventBinding) {
              this._emit(previousState.transitionOutEventBinding);
            }
          }
          if (lastTransition.startEventBinding) {
            this._emit(lastTransition.startEventBinding);
          }
          if (destinationState instanceof EventifiedStateEval) {
            if (destinationState.transitionInEventBinding) {
              this._emit(destinationState.transitionInEventBinding);
            }
          }
        };
        _proto._updateActivatedTransitions = function _updateActivatedTransitions(deltaTime) {
          var activatedTransitions = this._activatedTransitions;
          var iTransition = activatedTransitions.length - 1;
          var remainingWeight = 1.0;
          var lastTransitionIndex = iTransition;
          for (; iTransition >= 0; --iTransition) {
            var transition = activatedTransitions[iTransition];
            var sourceState = iTransition === 0 ? this._currentNode : activatedTransitions[iTransition - 1].destination;
            transition.update(deltaTime, sourceState);
            if (transition.done) {
              this._dropActivatedTransitions(lastTransitionIndex);
              break;
            }
            var destinationWeight = transition.normalizedElapsedTime * remainingWeight;
            transition.destination.increaseAbsoluteWeight(destinationWeight);
            remainingWeight *= 1.0 - transition.normalizedElapsedTime;
            lastTransitionIndex = iTransition - 1;
          }
          this._currentNode.increaseAbsoluteWeight(remainingWeight);
        };
        _proto._dropActivatedTransitions = function _dropActivatedTransitions(lastTransitionIndex) {
          var activatedTransition = this._activatedTransitions,
            activatedTransitionPool = this._activatedTransitionPool;
          assertIsTrue(lastTransitionIndex >= 0 && lastTransitionIndex < activatedTransition.length);
          var lenSubpath = lastTransitionIndex + 1;
          var lastTransition = activatedTransition[lastTransitionIndex];
          var newCurrentState = lastTransition.destination;
          {
            assertIsTrue(lastTransition.path.length !== 0);
            var lastRealTransition = lastTransition.path[lastTransition.path.length - 1];
            if (lastRealTransition.endEventBinding) {
              this._emit(lastRealTransition.endEventBinding);
            }
          }
          this._callExitMethods(this._currentNode);
          for (var iTransition = 0; iTransition <= lastTransitionIndex; ++iTransition) {
            var transition = activatedTransition[iTransition];
            if (iTransition !== lastTransitionIndex) {
              transition.destination.decreaseActiveReference();
            }
            var iLastExitingDetailedTransition = iTransition === lastTransitionIndex ? transition.path.length - 1 : transition.path.length;
            for (var iDetailedTransition = 0; iDetailedTransition < iLastExitingDetailedTransition; ++iDetailedTransition) {
              var detailedTransition = transition.path[iDetailedTransition];
              this._callExitMethods(detailedTransition.to);
            }
            activatedTransitionPool.free(transition);
          }
          if (lastTransitionIndex === activatedTransition.length - 1) {
            activatedTransition.length = 0;
          } else {
            for (var _iTransition = lastTransitionIndex + 1; _iTransition < activatedTransition.length; ++_iTransition) {
              activatedTransition[_iTransition - lenSubpath] = activatedTransition[_iTransition];
            }
            activatedTransition.length -= lenSubpath;
          }
          this._currentNode.decreaseActiveReference();
          this._currentNode = newCurrentState;
        };
        _proto._resetTriggersOnTransition = function _resetTriggersOnTransition(transition) {
          var triggers = transition.triggers;
          if (triggers) {
            var nTriggers = triggers.length;
            for (var iTrigger = 0; iTrigger < nTriggers; ++iTrigger) {
              var trigger = triggers[iTrigger];
              this._resetTrigger(trigger);
            }
          }
        };
        _proto._resetTrigger = function _resetTrigger(name) {
          var triggerResetFn = this._triggerReset;
          triggerResetFn(name);
        };
        _proto._callEnterMethods = function _callEnterMethods(node) {
          var _node$stateMachine$co;
          var controller = this._controller;
          switch (node.kind) {
            default:
              break;
            case NodeKind.animation:
              {
                node.components.callMotionStateEnterMethods(controller, node.getStatus());
                break;
              }
            case NodeKind.entry:
              (_node$stateMachine$co = node.stateMachine.components) === null || _node$stateMachine$co === void 0 ? void 0 : _node$stateMachine$co.callStateMachineEnterMethods(controller);
              break;
          }
        };
        _proto._callExitMethods = function _callExitMethods(node) {
          var _node$stateMachine$co2;
          var controller = this._controller;
          switch (node.kind) {
            default:
              break;
            case NodeKind.animation:
              {
                node.components.callMotionStateExitMethods(controller, node.getStatus());
                break;
              }
            case NodeKind.exit:
              (_node$stateMachine$co2 = node.stateMachine.components) === null || _node$stateMachine$co2 === void 0 ? void 0 : _node$stateMachine$co2.callStateMachineExitMethods(controller);
              break;
          }
        };
        _proto._emit = function _emit(eventBinding) {
          eventBinding.emit(this._controller.node);
        };
        _createClass(TopLevelStateMachineEvaluation, [{
          key: "exited",
          get: function get() {
            return this._currentNode === this._topLevelExit;
          }
        }]);
        return TopLevelStateMachineEvaluation;
      }();
      function isRealState(stateEval) {
        return stateEval.kind === NodeKind.animation || stateEval.kind === NodeKind.empty || stateEval.kind === NodeKind.procedural;
      }
      function createStateStatusCache() {
        return {
          progress: 0.0
        };
      }
      var emptyClipStatusesIterator = {
        next: function next() {
          return {
            done: true,
            value: undefined
          };
        }
      };
      var emptyClipStatusesIterable = (_emptyClipStatusesIte = {}, _emptyClipStatusesIte[Symbol.iterator] = function () {
        return emptyClipStatusesIterator;
      }, _emptyClipStatusesIte);
      var NodeKind;
      (function (NodeKind) {
        NodeKind[NodeKind["entry"] = 0] = "entry";
        NodeKind[NodeKind["exit"] = 1] = "exit";
        NodeKind[NodeKind["any"] = 2] = "any";
        NodeKind[NodeKind["animation"] = 3] = "animation";
        NodeKind[NodeKind["empty"] = 4] = "empty";
        NodeKind[NodeKind["procedural"] = 5] = "procedural";
      })(NodeKind || (NodeKind = {}));
      var StateEval = function () {
        function StateEval(node) {
          this.name = void 0;
          this.outgoingTransitions = [];
          this._activeReferenceCount = 0;
          this._tickFlags = 0;
          this._absoluteWeight = 0.0;
          this.name = node.name;
        }
        var _proto2 = StateEval.prototype;
        _proto2.setPrefix_debug = function setPrefix_debug(prefix) {
          this.__DEBUG_ID__ = "" + prefix + this.name;
        };
        _proto2.addTransition = function addTransition(transition) {
          this.outgoingTransitions.push(transition);
        };
        _proto2.increaseActiveReference = function increaseActiveReference() {
          if (this._activeReferenceCount === 0) {
            this._absoluteWeight = 0.0;
            this._tickFlags = 0;
          }
          ++this._activeReferenceCount;
        };
        _proto2.decreaseActiveReference = function decreaseActiveReference() {
          {
            this._checkActivated();
          }
          --this._activeReferenceCount;
        };
        _proto2.resetTickFlagsAndWeight = function resetTickFlagsAndWeight() {
          this._checkActivated();
          this._absoluteWeight = 0.0;
          this._tickFlags = 0;
        };
        _proto2.increaseAbsoluteWeight = function increaseAbsoluteWeight(weight) {
          this._absoluteWeight += weight;
        };
        _proto2.testTickFlag = function testTickFlag(flag) {
          {
            this._checkActivated();
          }
          return !!(this._tickFlags & flag);
        };
        _proto2.setTickFlag = function setTickFlag(flag) {
          {
            this._checkActivated();
          }
          assertIsTrue(!this.testTickFlag(flag), "Can not set " + StateTickFlag[flag] + " since it has been set!");
          this._tickFlags |= flag;
        };
        _proto2._checkActivated = function _checkActivated() {
          assertIsTrue(this._activeReferenceCount > 0, "The state has not been activated");
        };
        _createClass(StateEval, [{
          key: "absoluteWeight",
          get: function get() {
            return this._absoluteWeight;
          }
        }, {
          key: "activeReferenceCount",
          get: function get() {
            return this._activeReferenceCount;
          }
        }]);
        return StateEval;
      }();
      var EventifiedStateEval = function (_StateEval) {
        _inheritsLoose(EventifiedStateEval, _StateEval);
        function EventifiedStateEval(state) {
          var _this2;
          _this2 = _StateEval.call(this, state) || this;
          _this2.transitionInEventBinding = undefined;
          _this2.transitionOutEventBinding = undefined;
          if (state.transitionInEventBinding.isBound) {
            _this2.transitionInEventBinding = state.transitionInEventBinding;
          }
          if (state.transitionOutEventBinding.isBound) {
            _this2.transitionOutEventBinding = state.transitionOutEventBinding;
          }
          return _this2;
        }
        return EventifiedStateEval;
      }(StateEval);
      var StateTickFlag;
      (function (StateTickFlag) {
        StateTickFlag[StateTickFlag["UPDATED"] = 1] = "UPDATED";
        StateTickFlag[StateTickFlag["EVALUATED"] = 2] = "EVALUATED";
      })(StateTickFlag || (StateTickFlag = {}));
      var InstantiatedComponents = function () {
        function InstantiatedComponents(node) {
          this._components = node.instantiateComponents();
        }
        var _proto3 = InstantiatedComponents.prototype;
        _proto3.callMotionStateEnterMethods = function callMotionStateEnterMethods(controller, status) {
          this._callMotionStateCallbackIfNonDefault('onMotionStateEnter', controller, status);
        };
        _proto3.callMotionStateUpdateMethods = function callMotionStateUpdateMethods(controller, status) {
          this._callMotionStateCallbackIfNonDefault('onMotionStateUpdate', controller, status);
        };
        _proto3.callMotionStateExitMethods = function callMotionStateExitMethods(controller, status) {
          this._callMotionStateCallbackIfNonDefault('onMotionStateExit', controller, status);
        };
        _proto3.callStateMachineEnterMethods = function callStateMachineEnterMethods(controller) {
          this._callStateMachineCallbackIfNonDefault('onStateMachineEnter', controller);
        };
        _proto3.callStateMachineExitMethods = function callStateMachineExitMethods(controller) {
          this._callStateMachineCallbackIfNonDefault('onStateMachineExit', controller);
        };
        _proto3._callMotionStateCallbackIfNonDefault = function _callMotionStateCallbackIfNonDefault(methodName, controller, status) {
          var components = this._components;
          var nComponents = components.length;
          for (var iComponent = 0; iComponent < nComponents; ++iComponent) {
            var component = components[iComponent];
            if (component[methodName] !== StateMachineComponent.prototype[methodName]) {
              component[methodName](controller, status);
            }
          }
        };
        _proto3._callStateMachineCallbackIfNonDefault = function _callStateMachineCallbackIfNonDefault(methodName, controller) {
          var components = this._components;
          var nComponents = components.length;
          for (var iComponent = 0; iComponent < nComponents; ++iComponent) {
            var component = components[iComponent];
            if (component[methodName] !== StateMachineComponent.prototype[methodName]) {
              component[methodName](controller);
            }
          }
        };
        return InstantiatedComponents;
      }();
      var VMSMEval = function () {
        function VMSMEval(state, context) {
          var _state$motion$createE, _state$motion;
          this._source = null;
          this._baseSpeed = 1.0;
          this._speed = 1.0;
          this._publicState = void 0;
          this._privateState = void 0;
          var name = state.name;
          this._baseSpeed = state.speed;
          this._setSpeedMultiplier(1.0);
          if (state.speedMultiplierEnabled && state.speedMultiplier) {
            var speedMultiplierVarName = state.speedMultiplier;
            var varInstance = context.getVar(speedMultiplierVarName);
            if (validateVariableExistence(varInstance, speedMultiplierVarName)) {
              validateVariableType(varInstance.type, VariableType.FLOAT, speedMultiplierVarName);
              varInstance.bind(this._setSpeedMultiplier, this);
              var initialSpeedMultiplier = varInstance.value;
              this._setSpeedMultiplier(initialSpeedMultiplier);
            }
          }
          var sourceEval = (_state$motion$createE = (_state$motion = state.motion) === null || _state$motion === void 0 ? void 0 : _state$motion[createEval](context, false)) !== null && _state$motion$createE !== void 0 ? _state$motion$createE : null;
          if (sourceEval) {
            Object.defineProperty(sourceEval, '__DEBUG_ID__', {
              value: name
            });
          }
          this._source = sourceEval;
          this._publicState = new VMSMInternalState(this, state, sourceEval === null || sourceEval === void 0 ? void 0 : sourceEval.createPort());
          this._privateState = new VMSMInternalState(this, state, sourceEval === null || sourceEval === void 0 ? void 0 : sourceEval.createPort());
          this.components = new InstantiatedComponents(state);
        }
        var _proto4 = VMSMEval.prototype;
        _proto4.setPrefix_debug = function setPrefix_debug(prefix) {
          this._publicState.setPrefix_debug(prefix);
          this._privateState.setPrefix_debug(prefix);
        };
        _proto4.addTransition = function addTransition(transition) {
          if (transition.to === this._publicState) {
            this._publicState.addTransition(_extends({}, transition, {
              to: this._privateState
            }));
          } else {
            this._publicState.addTransition(transition);
          }
          this._privateState.addTransition(transition);
        };
        _proto4.getClipStatuses = function getClipStatuses(baseWeight) {
          var source = this._source;
          if (!source) {
            return emptyClipStatusesIterable;
          } else {
            var _ref;
            return _ref = {}, _ref[Symbol.iterator] = function () {
              return source.getClipStatuses(baseWeight);
            }, _ref;
          }
        };
        _proto4.overrideClips = function overrideClips(context) {
          var _this$_source;
          (_this$_source = this._source) === null || _this$_source === void 0 ? void 0 : _this$_source.overrideClips(context);
        };
        _proto4._setSpeedMultiplier = function _setSpeedMultiplier(value) {
          this._speed = this._baseSpeed * value;
        };
        _createClass(VMSMEval, [{
          key: "duration",
          get: function get() {
            var _this$_source$duratio, _this$_source2;
            return (_this$_source$duratio = (_this$_source2 = this._source) === null || _this$_source2 === void 0 ? void 0 : _this$_source2.duration) !== null && _this$_source$duratio !== void 0 ? _this$_source$duratio : 0.0;
          }
        }, {
          key: "speed",
          get: function get() {
            return this._speed;
          }
        }, {
          key: "entry",
          get: function get() {
            return this._publicState;
          }
        }, {
          key: "stateMachine",
          get: function get() {
            return this._stateMachine;
          },
          set: function set(value) {
            this._stateMachine = value;
            this._publicState.stateMachine = value;
            this._privateState.stateMachine = value;
          }
        }]);
        return VMSMEval;
      }();
      var VMSMInternalState = function (_EventifiedStateEval) {
        _inheritsLoose(VMSMInternalState, _EventifiedStateEval);
        function VMSMInternalState(container, containerState, port) {
          var _this3;
          _this3 = _EventifiedStateEval.call(this, containerState) || this;
          _this3.kind = NodeKind.animation;
          _this3._container = void 0;
          _this3._progress = 0.0;
          _this3._port = void 0;
          _this3._statusCache = createStateStatusCache();
          _this3._container = container;
          _this3._port = port;
          return _this3;
        }
        var _proto5 = VMSMInternalState.prototype;
        _proto5.reenter = function reenter(initialTimeNormalized) {
          var _this$_port;
          this._progress = initialTimeNormalized;
          (_this$_port = this._port) === null || _this$_port === void 0 ? void 0 : _this$_port.reenter();
        };
        _proto5.getStatus = function getStatus() {
          var stateStatus = this._statusCache;
          {
            stateStatus.__DEBUG_ID__ = this.name;
          }
          stateStatus.progress = normalizeProgress(this._progress);
          return stateStatus;
        };
        _proto5.getClipStatuses = function getClipStatuses(baseWeight) {
          return this._container.getClipStatuses(baseWeight);
        };
        _proto5.update = function update(deltaTime, controller) {
          this._progress = calcProgressUpdate(this._progress, this.duration, deltaTime * this._container.speed);
          this._container.components.callMotionStateUpdateMethods(controller, this.getStatus());
        };
        _proto5.evaluate = function evaluate(context) {
          var _this$_port$evaluate, _this$_port2;
          return (_this$_port$evaluate = (_this$_port2 = this._port) === null || _this$_port2 === void 0 ? void 0 : _this$_port2.evaluate(this._progress, context)) !== null && _this$_port$evaluate !== void 0 ? _this$_port$evaluate : null;
        };
        _createClass(VMSMInternalState, [{
          key: "duration",
          get: function get() {
            return this._container.duration;
          }
        }, {
          key: "components",
          get: function get() {
            return this._container.components;
          }
        }, {
          key: "normalizedTime",
          get: function get() {
            return this._progress;
          }
        }, {
          key: "time",
          get: function get() {
            return this._progress * this._container.duration;
          }
        }]);
        return VMSMInternalState;
      }(EventifiedStateEval);
      function calcProgressUpdate(currentProgress, duration, deltaTime) {
        if (duration === 0.0) {
          return 0.0;
        }
        var progress = currentProgress + deltaTime / duration;
        return progress;
      }
      function normalizeProgress(progress) {
        var signedFrac = progress - Math.trunc(progress);
        return signedFrac >= 0.0 ? signedFrac : 1.0 + signedFrac;
      }
      var SpecialStateEval = function (_StateEval2) {
        _inheritsLoose(SpecialStateEval, _StateEval2);
        function SpecialStateEval(node, kind, name) {
          var _this4;
          _this4 = _StateEval2.call(this, node) || this;
          _this4.kind = void 0;
          _this4.kind = kind;
          return _this4;
        }
        return SpecialStateEval;
      }(StateEval);
      var EmptyStateEval = function (_StateEval3) {
        _inheritsLoose(EmptyStateEval, _StateEval3);
        function EmptyStateEval(node) {
          var _this5;
          _this5 = _StateEval3.call(this, node) || this;
          _this5.kind = NodeKind.empty;
          return _this5;
        }
        return EmptyStateEval;
      }(StateEval);
      var ProceduralPoseStateEval = function (_EventifiedStateEval2) {
        _inheritsLoose(ProceduralPoseStateEval, _EventifiedStateEval2);
        function ProceduralPoseStateEval(state, context) {
          var _this6;
          _this6 = _EventifiedStateEval2.call(this, state) || this;
          _this6.kind = NodeKind.procedural;
          _this6.elapsedTime = 0.0;
          _this6.statusCache = createStateStatusCache();
          _this6._instantiatedPoseGraph = void 0;
          _this6._statusCache = createStateStatusCache();
          _this6._elapsedTime = 0.0;
          var instantiatedPoseGraph = instantiatePoseGraph(state.graph, context, true);
          instantiatedPoseGraph.bind(context);
          _this6._instantiatedPoseGraph = instantiatedPoseGraph;
          {
            _this6._statusCache.__DEBUG_ID__ = state.name;
          }
          _this6._statusCache.progress = 0.0;
          return _this6;
        }
        var _proto6 = ProceduralPoseStateEval.prototype;
        _proto6.settle = function settle(context) {
          this._instantiatedPoseGraph.settle(context);
        };
        _proto6.reenter = function reenter() {
          this._statusCache.progress = 0.0;
          this._instantiatedPoseGraph.reenter();
        };
        _proto6.update = function update(context) {
          this._elapsedTime += context.deltaTime;
          this._instantiatedPoseGraph.update(context);
        };
        _proto6.evaluate = function evaluate(context) {
          var _this$_instantiatedPo;
          return (_this$_instantiatedPo = this._instantiatedPoseGraph.evaluate(context)) !== null && _this$_instantiatedPo !== void 0 ? _this$_instantiatedPo : null;
        };
        _proto6.getStatus = function getStatus() {
          this._statusCache.progress = normalizeProgress(this._elapsedTime);
          return this._statusCache;
        };
        _proto6.countMotionTime = function countMotionTime() {
          return this._instantiatedPoseGraph.countMotionTime();
        };
        return ProceduralPoseStateEval;
      }(EventifiedStateEval);
      var ConditionEvaluationContextImpl = function () {
        function ConditionEvaluationContextImpl() {
          this.sourceStateWeight = 0.0;
          this._sourceState = undefined;
        }
        var _proto7 = ConditionEvaluationContextImpl.prototype;
        _proto7.set = function set(sourceState) {
          this._sourceState = sourceState;
          if (isRealState(sourceState)) {
            assertIsTrue(sourceState.activeReferenceCount);
            this.sourceStateWeight = sourceState.absoluteWeight;
          } else {
            this.sourceStateWeight = 0.0;
          }
        };
        _proto7.unset = function unset() {
          this._sourceState = undefined;
          this.sourceStateWeight = 0.0;
        };
        _createClass(ConditionEvaluationContextImpl, [{
          key: "sourceStateMotionTimeNormalized",
          get: function get() {
            var sourceState = this._sourceState;
            assertIsTrue(sourceState && (sourceState.kind === NodeKind.animation || sourceState.kind === NodeKind.procedural) && sourceState.activeReferenceCount, "State motion time is only defined on activated motion states and procedural pose states.");
            switch (sourceState.kind) {
              case NodeKind.animation:
                return sourceState.normalizedTime;
              case NodeKind.procedural:
                return sourceState.countMotionTime();
              default:
                return 0.0;
            }
          }
        }]);
        return ConditionEvaluationContextImpl;
      }();
      var ActivatedTransition = function () {
        function ActivatedTransition() {
          this.normalizedElapsedTime = 0.0;
          this.path = [];
          this._durationMultiplier = 1.0;
        }
        var _proto8 = ActivatedTransition.prototype;
        _proto8.getAbsoluteDuration = function getAbsoluteDuration(baseDurationState) {
          return this._getAbsoluteDurationUnscaled(baseDurationState) * this._durationMultiplier;
        };
        _proto8.update = function update(deltaTime, fromState) {
          if (!isRealState(fromState)) {
            this.normalizedElapsedTime = 1.0;
            return;
          }
          var transitionDurationAbsolute = this.getAbsoluteDuration(fromState);
          var contrib = 0.0;
          if (transitionDurationAbsolute <= 0.0) {
            contrib = 0.0;
            this.normalizedElapsedTime = 1.0;
          } else {
            var elapsedTransitionTime = this.normalizedElapsedTime * transitionDurationAbsolute;
            var remainTransitionTime = transitionDurationAbsolute - elapsedTransitionTime;
            assertIsTrue(remainTransitionTime >= 0.0);
            contrib = Math.min(remainTransitionTime, deltaTime);
            var newTransitionProgress = clamp01((elapsedTransitionTime + contrib) / transitionDurationAbsolute);
            this.normalizedElapsedTime = newTransitionProgress;
            assertIsTrue(newTransitionProgress >= 0.0 && newTransitionProgress <= 1.0);
          }
        };
        ActivatedTransition.createPool = function createPool(initialCapacity) {
          var destructor = function (transitionInstance) {
            transitionInstance.normalizedElapsedTime = Number.NaN;
          };
          var pool = new Pool(function () {
            return new ActivatedTransition();
          }, initialCapacity, destructor);
          return pool;
        };
        _proto8.reset = function reset(prefix, lastTransition) {
          var destinationState = lastTransition.to;
          assertIsTrue(isRealState(destinationState));
          this.normalizedElapsedTime = 0.0;
          this.destination = destinationState;
          this.path = [].concat(prefix, [lastTransition]);
          var previousActiveReferenceCount = destinationState.activeReferenceCount;
          destinationState.increaseActiveReference();
          if (previousActiveReferenceCount === 0) {
            if (destinationState.kind === NodeKind.animation) {
              var _this$path$ = this.path[0],
                destinationStart = _this$path$.destinationStart,
                isRelativeDestinationStart = _this$path$.relativeDestinationStart;
              var destinationStartRatio = isRelativeDestinationStart ? destinationStart : destinationState.duration === 0 ? 0.0 : destinationStart / destinationState.duration;
              destinationState.reenter(destinationStartRatio);
            } else if (destinationState.kind === NodeKind.procedural) {
              destinationState.reenter();
            }
          }
          assertIsTrue(destinationState.activeReferenceCount > 0);
          this._durationMultiplier = 1.0 - destinationState.absoluteWeight;
        };
        _proto8._getAbsoluteDurationUnscaled = function _getAbsoluteDurationUnscaled(baseDurationState) {
          assertIsTrue(this.path.length !== 0);
          var _this$path$2 = this.path[0],
            duration = _this$path$2.duration,
            normalizedDuration = _this$path$2.normalizedDuration;
          if (!normalizedDuration) {
            return duration;
          }
          var baseDuration = baseDurationState.kind === NodeKind.animation ? baseDurationState.duration : 1.0;
          return baseDuration * duration;
        };
        _createClass(ActivatedTransition, [{
          key: "done",
          get: function get() {
            return approx(this.normalizedElapsedTime, 1.0, 1e-6);
          }
        }]);
        return ActivatedTransition;
      }();

      var _dec$_, _dec2$W, _dec3$J, _class$Z, _class2$X, _initializer$P, _initializer2$I;
      (_dec$_ = ccclass$n(CLASS_NAME_PREFIX_ANIM + "PoseNodeStateMachine"), _dec2$W = poseGraphNodeCategory(POSE_GRAPH_NODE_MENU_PREFIX_POSE), _dec3$J = poseGraphNodeAppearance({
        themeColor: '#CCCCCC',
        inline: true
      }), _dec$_(_class$Z = _dec2$W(_class$Z = _dec3$J(_class$Z = (_class2$X = function (_PoseNode) {
        _inheritsLoose(PoseNodeStateMachine, _PoseNode);
        function PoseNodeStateMachine() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _PoseNode.call.apply(_PoseNode, [this].concat(args)) || this;
          _this.name = _initializer$P && _initializer$P();
          _this.stateMachine = _initializer2$I && _initializer2$I();
          _this._stateMachineEval = void 0;
          return _this;
        }
        var _proto = PoseNodeStateMachine.prototype;
        _proto.__callOnAfterDeserializeRecursive = function __callOnAfterDeserializeRecursive() {
          this.stateMachine._allowEmptyStates = false;
          this.stateMachine.__callOnAfterDeserializeRecursive();
        };
        _proto.bind = function bind(context) {
          assertIsTrue(!this._stateMachineEval);
          this._stateMachineEval = new TopLevelStateMachineEvaluation(this.stateMachine, '', context);
        };
        _proto.settle = function settle(context) {
          var _this$_stateMachineEv;
          (_this$_stateMachineEv = this._stateMachineEval) === null || _this$_stateMachineEv === void 0 ? void 0 : _this$_stateMachineEv.settle(context);
        };
        _proto.reenter = function reenter() {
          var _this$_stateMachineEv2;
          (_this$_stateMachineEv2 = this._stateMachineEval) === null || _this$_stateMachineEv2 === void 0 ? void 0 : _this$_stateMachineEv2.reenter();
        };
        _proto.doUpdate = function doUpdate(context) {
          var stateMachineEval = this._stateMachineEval;
          assertIsTrue(stateMachineEval);
          stateMachineEval.update(context);
          assertIsTrue(stateMachineEval.passthroughWeight > 1.0 - 1e-5);
        };
        _proto.doEvaluate = function doEvaluate(context) {
          var stateMachineEval = this._stateMachineEval;
          assertIsTrue(stateMachineEval);
          var stateMachinePose = stateMachineEval.evaluate(context);
          assertIsTrue(stateMachineEval.passthroughWeight > 1.0 - 1e-5);
          return stateMachinePose;
        };
        return PoseNodeStateMachine;
      }(PoseNode), (_initializer$P = applyDecoratedInitializer(_class2$X.prototype, "name", [serializable$j], function () {
        return '';
      }), _initializer2$I = applyDecoratedInitializer(_class2$X.prototype, "stateMachine", [serializable$j], function () {
        return new StateMachine(false);
      })), _class2$X)) || _class$Z) || _class$Z) || _class$Z);

      var _dec$Z, _dec2$V, _dec3$I, _dec4$z, _dec5$u, _class$Y, _class2$W, _initializer$O, _descriptor$8, _initializer2$H;
      var PoseNodeSampleMotion = (_dec$Z = ccclass$n(CLASS_NAME_PREFIX_ANIM + "PoseNodeSampleMotion"), _dec2$V = poseGraphNodeCategory(POSE_GRAPH_NODE_MENU_PREFIX_POSE), _dec3$I = poseGraphCreateNodeFactory(makeCreateNodeFactory(function (motion) {
        var node = new PoseNodeSampleMotion();
        node.motion = motion;
        return node;
      })), _dec4$z = poseGraphNodeAppearance({
        themeColor: '#D97721'
      }), _dec5$u = input({
        type: PoseGraphType.FLOAT
      }), _dec$Z(_class$Y = _dec2$V(_class$Y = _dec3$I(_class$Y = _dec4$z(_class$Y = (_class2$W = function (_PoseNode) {
        _inheritsLoose(PoseNodeSampleMotion, _PoseNode);
        function PoseNodeSampleMotion() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _PoseNode.call.apply(_PoseNode, [this].concat(args)) || this;
          _this.motion = _initializer$O && _initializer$O();
          _initializerDefineProperty(_this, "time", _descriptor$8, _assertThisInitialized(_this));
          _this.useNormalizedTime = _initializer2$H && _initializer2$H();
          _this._workspace = null;
          return _this;
        }
        var _proto = PoseNodeSampleMotion.prototype;
        _proto.bind = function bind(context) {
          var motion = this.motion;
          if (!motion) {
            return;
          }
          var motionEval = motion[createEval](context, true);
          if (!motionEval) {
            return;
          }
          var workspace = new SampleMotionWorkspace(motionEval, motionEval.createPort());
          this._workspace = workspace;
        };
        _proto.settle = function settle(context) {};
        _proto.reenter = function reenter() {};
        _proto.doUpdate = function doUpdate(context) {};
        _proto.doEvaluate = function doEvaluate(context) {
          var workspace = this._workspace;
          if (!workspace) {
            return context.pushDefaultedPose();
          }
          var time = this.time;
          var normalizedTime = this.useNormalizedTime ? time : time / workspace.motionEval.duration;
          return workspace.motionEvalPort.evaluate(clamp01(normalizedTime), context);
        };
        return PoseNodeSampleMotion;
      }(PoseNode), (_initializer$O = applyDecoratedInitializer(_class2$W.prototype, "motion", [serializable$j], function () {
        return new ClipMotion();
      }), _descriptor$8 = _applyDecoratedDescriptor(_class2$W.prototype, "time", [serializable$j, _dec5$u], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return 0.0;
        }
      }), _initializer2$H = applyDecoratedInitializer(_class2$W.prototype, "useNormalizedTime", [serializable$j], function () {
        return false;
      })), _class2$W)) || _class$Y) || _class$Y) || _class$Y) || _class$Y);
      var SampleMotionWorkspace = function SampleMotionWorkspace(motionEval, motionEvalPort) {
        this.motionEval = motionEval;
        this.motionEvalPort = motionEvalPort;
      };

      var _dec$Y, _dec2$U, _dec3$H, _dec4$y, _dec5$t, _dec6$f, _class$X, _class2$V, _descriptor$7, _descriptor2$3, _descriptor3$1;
      (_dec$Y = ccclass$n(CLASS_NAME_PREFIX_ANIM + "PoseNodeAdditivelyBlend"), _dec2$U = poseGraphNodeCategory(POSE_GRAPH_NODE_MENU_PREFIX_POSE_BLEND), _dec3$H = poseGraphNodeAppearance({
        themeColor: '#72A869'
      }), _dec4$y = input({
        type: PoseGraphType.POSE
      }), _dec5$t = input({
        type: PoseGraphType.POSE
      }), _dec6$f = input({
        type: PoseGraphType.FLOAT
      }), _dec$Y(_class$X = _dec2$U(_class$X = _dec3$H(_class$X = (_class2$V = function (_PoseNode) {
        _inheritsLoose(PoseNodeAdditivelyBlend, _PoseNode);
        function PoseNodeAdditivelyBlend() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _PoseNode.call.apply(_PoseNode, [this].concat(args)) || this;
          _initializerDefineProperty(_this, "basePose", _descriptor$7, _assertThisInitialized(_this));
          _initializerDefineProperty(_this, "additivePose", _descriptor2$3, _assertThisInitialized(_this));
          _initializerDefineProperty(_this, "ratio", _descriptor3$1, _assertThisInitialized(_this));
          return _this;
        }
        var _proto = PoseNodeAdditivelyBlend.prototype;
        _proto.bind = function bind(context) {
          var _this$basePose, _this$additivePose;
          (_this$basePose = this.basePose) === null || _this$basePose === void 0 ? void 0 : _this$basePose.bind(context);
          context._pushAdditiveFlag(true);
          (_this$additivePose = this.additivePose) === null || _this$additivePose === void 0 ? void 0 : _this$additivePose.bind(context);
          context._popAdditiveFlag();
        };
        _proto.settle = function settle(context) {
          var _this$basePose2, _this$additivePose2;
          (_this$basePose2 = this.basePose) === null || _this$basePose2 === void 0 ? void 0 : _this$basePose2.settle(context);
          (_this$additivePose2 = this.additivePose) === null || _this$additivePose2 === void 0 ? void 0 : _this$additivePose2.settle(context);
        };
        _proto.reenter = function reenter() {
          var _this$basePose3, _this$additivePose3;
          (_this$basePose3 = this.basePose) === null || _this$basePose3 === void 0 ? void 0 : _this$basePose3.reenter();
          (_this$additivePose3 = this.additivePose) === null || _this$additivePose3 === void 0 ? void 0 : _this$additivePose3.reenter();
        };
        _proto.doUpdate = function doUpdate(context) {
          var _this$basePose4, _this$additivePose4;
          (_this$basePose4 = this.basePose) === null || _this$basePose4 === void 0 ? void 0 : _this$basePose4.update(context);
          (_this$additivePose4 = this.additivePose) === null || _this$additivePose4 === void 0 ? void 0 : _this$additivePose4.update(context);
        };
        _proto.doEvaluate = function doEvaluate(context) {
          var _this$basePose$evalua, _this$basePose5;
          var basePose = (_this$basePose$evalua = (_this$basePose5 = this.basePose) === null || _this$basePose5 === void 0 ? void 0 : _this$basePose5.evaluate(context, PoseTransformSpaceRequirement.LOCAL)) !== null && _this$basePose$evalua !== void 0 ? _this$basePose$evalua : context.pushDefaultedPose();
          if (!this.additivePose) {
            return basePose;
          }
          var additionalPose = this.additivePose.evaluate(context, PoseTransformSpaceRequirement.LOCAL);
          applyDeltaPose(basePose, additionalPose, this.ratio);
          context.popPose();
          return basePose;
        };
        return PoseNodeAdditivelyBlend;
      }(PoseNode), (_descriptor$7 = _applyDecoratedDescriptor(_class2$V.prototype, "basePose", [serializable$j, _dec4$y], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return null;
        }
      }), _descriptor2$3 = _applyDecoratedDescriptor(_class2$V.prototype, "additivePose", [serializable$j, _dec5$t], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return null;
        }
      }), _descriptor3$1 = _applyDecoratedDescriptor(_class2$V.prototype, "ratio", [serializable$j, _dec6$f], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return 1.0;
        }
      })), _class2$V)) || _class$X) || _class$X) || _class$X);

      function isIgnorableWeight(weight) {
        return weight < 1e-5;
      }

      var _dec$X, _dec2$T, _dec3$G, _dec4$x, _dec5$s, _class$W, _class2$U, _descriptor$6, _descriptor2$2;
      (_dec$X = ccclass$n(CLASS_NAME_PREFIX_ANIM + "PoseNodeBlendInProportion"), _dec2$T = poseGraphNodeCategory(POSE_GRAPH_NODE_MENU_PREFIX_POSE_BLEND), _dec3$G = poseGraphNodeAppearance({
        themeColor: '#72A869'
      }), _dec4$x = input({
        type: PoseGraphType.POSE,
        arraySyncGroup: 'blend-item'
      }), _dec5$s = input({
        type: PoseGraphType.FLOAT,
        arraySyncGroup: 'blend-item',
        arraySyncGroupFollower: true
      }), _dec$X(_class$W = _dec2$T(_class$W = _dec3$G(_class$W = (_class2$U = function (_PoseNode) {
        _inheritsLoose(PoseNodeBlendInProportion, _PoseNode);
        function PoseNodeBlendInProportion() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _PoseNode.call.apply(_PoseNode, [this].concat(args)) || this;
          _initializerDefineProperty(_this, "poses", _descriptor$6, _assertThisInitialized(_this));
          _initializerDefineProperty(_this, "proportions", _descriptor2$2, _assertThisInitialized(_this));
          _this._updateContextGenerator = new AnimationGraphUpdateContextGenerator();
          return _this;
        }
        var _proto = PoseNodeBlendInProportion.prototype;
        _proto.bind = function bind(context) {
          for (var _iterator = _createForOfIteratorHelperLoose(this.poses), _step; !(_step = _iterator()).done;) {
            var pose = _step.value;
            pose === null || pose === void 0 ? void 0 : pose.bind(context);
          }
        };
        _proto.settle = function settle(context) {
          for (var _iterator2 = _createForOfIteratorHelperLoose(this.poses), _step2; !(_step2 = _iterator2()).done;) {
            var pose = _step2.value;
            pose === null || pose === void 0 ? void 0 : pose.settle(context);
          }
        };
        _proto.reenter = function reenter() {
          for (var _iterator3 = _createForOfIteratorHelperLoose(this.poses), _step3; !(_step3 = _iterator3()).done;) {
            var pose = _step3.value;
            pose === null || pose === void 0 ? void 0 : pose.reenter();
          }
        };
        _proto.doUpdate = function doUpdate(context) {
          var updateContextGenerator = this._updateContextGenerator;
          var nInputPoses = this.poses.length;
          for (var iInputPose = 0; iInputPose < nInputPoses; ++iInputPose) {
            var _this$poses$iInputPos;
            var inputPoseWeight = this.proportions[iInputPose];
            if (isIgnorableWeight(inputPoseWeight)) {
              continue;
            }
            var inputPoseUpdateContext = updateContextGenerator.generate(context.deltaTime, context.indicativeWeight * inputPoseWeight);
            (_this$poses$iInputPos = this.poses[iInputPose]) === null || _this$poses$iInputPos === void 0 ? void 0 : _this$poses$iInputPos.update(inputPoseUpdateContext);
          }
        };
        _proto.doEvaluate = function doEvaluate(context) {
          var nInputPoses = this.poses.length;
          var sumWeight = 0.0;
          var finalPose = null;
          for (var iInputPose = 0; iInputPose < nInputPoses; ++iInputPose) {
            var _this$poses$iInputPos2;
            var inputPoseWeight = this.proportions[iInputPose];
            if (isIgnorableWeight(inputPoseWeight)) {
              continue;
            }
            var inputPose = (_this$poses$iInputPos2 = this.poses[iInputPose]) === null || _this$poses$iInputPos2 === void 0 ? void 0 : _this$poses$iInputPos2.evaluate(context, PoseTransformSpaceRequirement.LOCAL);
            if (!inputPose) {
              continue;
            }
            sumWeight += inputPoseWeight;
            if (!finalPose) {
              finalPose = inputPose;
            } else {
              if (sumWeight) {
                var t = inputPoseWeight / sumWeight;
                blendPoseInto(finalPose, inputPose, t);
              }
              context.popPose();
            }
          }
          if (finalPose) {
            return finalPose;
          }
          return context.pushDefaultedPose();
        };
        return PoseNodeBlendInProportion;
      }(PoseNode), (_descriptor$6 = _applyDecoratedDescriptor(_class2$U.prototype, "poses", [serializable$j, _dec4$x], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return [];
        }
      }), _descriptor2$2 = _applyDecoratedDescriptor(_class2$U.prototype, "proportions", [serializable$j, _dec5$s], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return [];
        }
      })), _class2$U)) || _class$W) || _class$W) || _class$W);

      var _dec$W, _dec2$S, _dec3$F, _dec4$w, _dec5$r, _class$V, _class2$T, _descriptor$5, _descriptor2$1, _descriptor3;
      var PoseNodeBlendTwoPoseBase = (_dec$W = ccclass$n(CLASS_NAME_PREFIX_ANIM + "PoseNodeBlendTwoPoseBase"), _dec2$S = poseGraphNodeHide(true), _dec3$F = input({
        type: PoseGraphType.POSE
      }), _dec4$w = input({
        type: PoseGraphType.POSE
      }), _dec5$r = input({
        type: PoseGraphType.FLOAT
      }), _dec$W(_class$V = _dec2$S(_class$V = (_class2$T = function (_PoseNode) {
        _inheritsLoose(PoseNodeBlendTwoPoseBase, _PoseNode);
        function PoseNodeBlendTwoPoseBase() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _PoseNode.call.apply(_PoseNode, [this].concat(args)) || this;
          _initializerDefineProperty(_this, "pose0", _descriptor$5, _assertThisInitialized(_this));
          _initializerDefineProperty(_this, "pose1", _descriptor2$1, _assertThisInitialized(_this));
          _initializerDefineProperty(_this, "ratio", _descriptor3, _assertThisInitialized(_this));
          _this._updateContextGenerator = new AnimationGraphUpdateContextGenerator();
          return _this;
        }
        var _proto = PoseNodeBlendTwoPoseBase.prototype;
        _proto.bind = function bind(context) {
          var _this$pose, _this$pose2;
          (_this$pose = this.pose0) === null || _this$pose === void 0 ? void 0 : _this$pose.bind(context);
          (_this$pose2 = this.pose1) === null || _this$pose2 === void 0 ? void 0 : _this$pose2.bind(context);
        };
        _proto.settle = function settle(context) {
          var _this$pose3, _this$pose4;
          (_this$pose3 = this.pose0) === null || _this$pose3 === void 0 ? void 0 : _this$pose3.settle(context);
          (_this$pose4 = this.pose1) === null || _this$pose4 === void 0 ? void 0 : _this$pose4.settle(context);
        };
        _proto.reenter = function reenter() {
          var _this$pose5, _this$pose6;
          (_this$pose5 = this.pose0) === null || _this$pose5 === void 0 ? void 0 : _this$pose5.reenter();
          (_this$pose6 = this.pose1) === null || _this$pose6 === void 0 ? void 0 : _this$pose6.reenter();
        };
        _proto.doUpdate = function doUpdate(context) {
          var pose0 = this.pose0,
            pose1 = this.pose1,
            updateContextGenerator = this._updateContextGenerator,
            ratio = this.ratio;
          {
            var updateContext = updateContextGenerator.generate(context.deltaTime, context.indicativeWeight * (1.0 - ratio));
            pose0 === null || pose0 === void 0 ? void 0 : pose0.update(updateContext);
          }
          {
            var _updateContext = updateContextGenerator.generate(context.deltaTime, context.indicativeWeight * ratio);
            pose1 === null || pose1 === void 0 ? void 0 : pose1.update(_updateContext);
          }
        };
        _proto.doEvaluate = function doEvaluate(context) {
          var _this$pose0$evaluate, _this$pose7, _this$pose1$evaluate, _this$pose8;
          var spaceRequirement = PoseTransformSpaceRequirement.LOCAL;
          if (!this.pose0 || !this.pose1) {
            return PoseNodeBlendTwoPoseBase.evaluateDefaultPose(context, spaceRequirement);
          }
          var pose0 = (_this$pose0$evaluate = (_this$pose7 = this.pose0) === null || _this$pose7 === void 0 ? void 0 : _this$pose7.evaluate(context, spaceRequirement)) !== null && _this$pose0$evaluate !== void 0 ? _this$pose0$evaluate : PoseNodeBlendTwoPoseBase.evaluateDefaultPose(context, spaceRequirement);
          var pose1 = (_this$pose1$evaluate = (_this$pose8 = this.pose1) === null || _this$pose8 === void 0 ? void 0 : _this$pose8.evaluate(context, spaceRequirement)) !== null && _this$pose1$evaluate !== void 0 ? _this$pose1$evaluate : PoseNodeBlendTwoPoseBase.evaluateDefaultPose(context, spaceRequirement);
          this.doBlend(pose0, pose1, this.ratio);
          context.popPose();
          return pose0;
        };
        return PoseNodeBlendTwoPoseBase;
      }(PoseNode), (_descriptor$5 = _applyDecoratedDescriptor(_class2$T.prototype, "pose0", [serializable$j, _dec3$F], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return null;
        }
      }), _descriptor2$1 = _applyDecoratedDescriptor(_class2$T.prototype, "pose1", [serializable$j, _dec4$w], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return null;
        }
      }), _descriptor3 = _applyDecoratedDescriptor(_class2$T.prototype, "ratio", [serializable$j, _dec5$r], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return 1.0;
        }
      })), _class2$T)) || _class$V) || _class$V);

      var _dec$V, _dec2$R, _dec3$E, _class$U;
      (_dec$V = ccclass$n(CLASS_NAME_PREFIX_ANIM + "PoseNodeBlendTwoPose"), _dec2$R = poseGraphNodeCategory(POSE_GRAPH_NODE_MENU_PREFIX_POSE_BLEND), _dec3$E = poseGraphNodeAppearance({
        themeColor: '#72A869'
      }), _dec$V(_class$U = _dec2$R(_class$U = _dec3$E(_class$U = function (_PoseNodeBlendTwoPose) {
        _inheritsLoose(PoseNodeBlendTwoPose, _PoseNodeBlendTwoPose);
        function PoseNodeBlendTwoPose() {
          return _PoseNodeBlendTwoPose.apply(this, arguments) || this;
        }
        var _proto = PoseNodeBlendTwoPose.prototype;
        _proto.doBlend = function doBlend(pose0, pose1, ratio) {
          return blendPoseInto(pose0, pose1, ratio);
        };
        return PoseNodeBlendTwoPose;
      }(PoseNodeBlendTwoPoseBase)) || _class$U) || _class$U) || _class$U);

      var _dec$U, _dec2$Q, _dec3$D, _dec4$v, _class$T, _class2$S, _initializer$N;
      (_dec$U = ccclass$n(CLASS_NAME_PREFIX_ANIM + "PoseNodeFilteringBlend"), _dec2$Q = poseGraphNodeCategory(POSE_GRAPH_NODE_MENU_PREFIX_POSE_BLEND), _dec3$D = poseGraphNodeAppearance({
        themeColor: '#72A869'
      }), _dec4$v = type$7(AnimationMask), _dec$U(_class$T = _dec2$Q(_class$T = _dec3$D(_class$T = (_class2$S = function (_PoseNodeBlendTwoPose) {
        _inheritsLoose(PoseNodeFilteringBlend, _PoseNodeBlendTwoPose);
        function PoseNodeFilteringBlend() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _PoseNodeBlendTwoPose.call.apply(_PoseNodeBlendTwoPose, [this].concat(args)) || this;
          _this.mask = _initializer$N && _initializer$N();
          _this._transformFilter = undefined;
          return _this;
        }
        var _proto = PoseNodeFilteringBlend.prototype;
        _proto.settle = function settle(context) {
          _PoseNodeBlendTwoPose.prototype.settle.call(this, context);
          if (this.mask) {
            var transformFilter = context.createTransformFilter(this.mask);
            this._transformFilter = transformFilter;
          }
        };
        _proto.doBlend = function doBlend(pose0, pose1, ratio) {
          blendPoseInto(pose0, pose1, ratio, this._transformFilter);
        };
        return PoseNodeFilteringBlend;
      }(PoseNodeBlendTwoPoseBase), (_initializer$N = applyDecoratedInitializer(_class2$S.prototype, "mask", [serializable$j, _dec4$v], function () {
        return null;
      })), _class2$S)) || _class$T) || _class$T) || _class$T);

      var POSE_GRAPH_NODE_MENU_PREFIX_CHOOSE = POSE_GRAPH_NODE_MENU_PREFIX_POSE + "/" + "i18n:ENGINE.animation_graph.pose_graph_node_sub_categories.pose_nodes_choose/";

      var _dec$T, _dec2$P, _class$S, _class2$R, _initializer$M, _initializer2$G;
      var ZERO_ALTERING_DURATION_THRESHOLD = 1e-5;
      var PoseNodeChoosePoseBase = (_dec$T = ccclass$n(CLASS_NAME_PREFIX_ANIM + "PoseNodeChoosePoseBase"), _dec2$P = poseGraphNodeHide(), _dec$T(_class$S = _dec2$P(_class$S = (_class2$R = function (_PoseNode) {
        _inheritsLoose(PoseNodeChoosePoseBase, _PoseNode);
        function PoseNodeChoosePoseBase(initialChoiceCount) {
          var _this;
          if (initialChoiceCount === void 0) {
            initialChoiceCount = 0;
          }
          _this = _PoseNode.call(this) || this;
          _this._poses = _initializer$M && _initializer$M();
          _this._fadeInDurations = _initializer2$G && _initializer2$G();
          _this._updateContextGenerator = new AnimationGraphUpdateContextGenerator();
          _this._evaluationRecord = undefined;
          _this._poses.length = initialChoiceCount;
          _this._poses.fill(null);
          _this._fadeInDurations.length = initialChoiceCount;
          _this._fadeInDurations.fill(0.0);
          return _this;
        }
        var _proto = PoseNodeChoosePoseBase.prototype;
        _proto.bind = function bind(context) {
          for (var _iterator = _createForOfIteratorHelperLoose(this._poses), _step; !(_step = _iterator()).done;) {
            var pose = _step.value;
            pose === null || pose === void 0 ? void 0 : pose.bind(context);
          }
          var evaluationRecord = new EvaluationRecord(this._poses.length, this.getChosenIndex());
          this._evaluationRecord = evaluationRecord;
        };
        _proto.settle = function settle(context) {
          for (var _iterator2 = _createForOfIteratorHelperLoose(this._poses), _step2; !(_step2 = _iterator2()).done;) {
            var pose = _step2.value;
            pose === null || pose === void 0 ? void 0 : pose.settle(context);
          }
        };
        _proto.reenter = function reenter() {
          for (var _iterator3 = _createForOfIteratorHelperLoose(this._poses), _step3; !(_step3 = _iterator3()).done;) {
            var pose = _step3.value;
            pose === null || pose === void 0 ? void 0 : pose.reenter();
          }
        };
        _proto.doUpdate = function doUpdate(context) {
          var poses = this._poses,
            evaluationRecord = this._evaluationRecord;
          assertIsTrue(evaluationRecord);
          evaluationRecord.update(context.deltaTime, this.getChosenIndex(), this._fadeInDurations);
          if (evaluationRecord.allWeightsAreZero()) {
            return;
          }
          var nPoses = poses.length;
          var items = evaluationRecord.items;
          assertIsTrue(items.length === nPoses);
          for (var iPose = 0; iPose < nPoses; ++iPose) {
            var weight = items[iPose].weight;
            if (isIgnorableWeight(weight)) {
              continue;
            }
            var pose = poses[iPose];
            var itemUpdateContext = this._updateContextGenerator.generate(context.deltaTime, context.indicativeWeight * weight);
            pose === null || pose === void 0 ? void 0 : pose.update(itemUpdateContext);
          }
        };
        _proto.doEvaluate = function doEvaluate(context) {
          var poses = this._poses,
            evaluationRecord = this._evaluationRecord;
          assertIsTrue(evaluationRecord);
          var spaceRequirement = PoseTransformSpaceRequirement.LOCAL;
          var nPoses = poses.length;
          var items = evaluationRecord.items;
          assertIsTrue(items.length === poses.length);
          var finalPose = null;
          if (!evaluationRecord.allWeightsAreZero()) {
            var sumWeight = 0.0;
            for (var iInputPose = 0; iInputPose < nPoses; ++iInputPose) {
              var _poses$iInputPose;
              var inputPoseWeight = evaluationRecord.items[iInputPose].weight;
              if (isIgnorableWeight(inputPoseWeight)) {
                continue;
              }
              var inputPose = (_poses$iInputPose = poses[iInputPose]) === null || _poses$iInputPose === void 0 ? void 0 : _poses$iInputPose.evaluate(context, PoseTransformSpaceRequirement.LOCAL);
              if (!inputPose) {
                continue;
              }
              sumWeight += inputPoseWeight;
              if (!finalPose) {
                finalPose = inputPose;
              } else {
                if (sumWeight) {
                  var t = inputPoseWeight / sumWeight;
                  blendPoseInto(finalPose, inputPose, t);
                }
                context.popPose();
              }
            }
          }
          if (finalPose) {
            return finalPose;
          }
          return PoseNodeChoosePoseBase.evaluateDefaultPose(context, spaceRequirement);
        };
        _proto.getChosenIndex = function getChosenIndex() {
          return 0;
        };
        return PoseNodeChoosePoseBase;
      }(PoseNode), (_initializer$M = applyDecoratedInitializer(_class2$R.prototype, "_poses", [serializable$j], function () {
        return [];
      }), _initializer2$G = applyDecoratedInitializer(_class2$R.prototype, "_fadeInDurations", [serializable$j], function () {
        return [];
      })), _class2$R)) || _class$S) || _class$S);
      var EvaluationRecord = function () {
        function EvaluationRecord(itemCount, initialChosenIndex) {
          this._items = void 0;
          this._chosenPoseIndex = -1;
          this._elapsedTransitionTime = 0.0;
          this._blendingDuration = 0.0;
          var items = Array.from({
            length: itemCount
          }, function () {
            return new ItemEvaluationRecord();
          });
          if (initialChosenIndex >= 0 && initialChosenIndex < itemCount) {
            items[initialChosenIndex].selfSourceWeight = 1.0;
            items[initialChosenIndex].selfTargetWeight = 1.0;
            items[initialChosenIndex].weight = 1.0;
          }
          this._items = items;
        }
        var _proto2 = EvaluationRecord.prototype;
        _proto2.allWeightsAreZero = function allWeightsAreZero() {
          return this._chosenPoseIndex < 0;
        };
        _proto2.update = function update(deltaTime, newChoseIndex, fadeInDurations) {
          assertIsTrue(deltaTime >= 0.0);
          this._checkAlternation(newChoseIndex, fadeInDurations);
          if (this._chosenPoseIndex < 0) {
            return;
          }
          var elapsedTransitionTime = this._elapsedTransitionTime,
            blendingDuration = this._blendingDuration,
            items = this._items;
          if (elapsedTransitionTime >= blendingDuration) {
            return;
          }
          var nPoses = items.length;
          var sumWeight = 0.0;
          var newUniformTransformRatio = 0.0;
          var remain = blendingDuration - elapsedTransitionTime;
          if (deltaTime > remain) {
            this._elapsedTransitionTime = blendingDuration;
            newUniformTransformRatio = 1.0;
          } else {
            this._elapsedTransitionTime += deltaTime;
            newUniformTransformRatio = this._elapsedTransitionTime / blendingDuration;
          }
          assertIsTrue(newUniformTransformRatio >= 0.0 && newUniformTransformRatio <= 1.0);
          for (var iPose = 0; iPose < nPoses; ++iPose) {
            var item = items[iPose];
            var selfWeight = lerp(item.selfSourceWeight, item.selfTargetWeight, newUniformTransformRatio);
            sumWeight += selfWeight;
            item.weight = selfWeight;
          }
          if (!isIgnorableWeight(sumWeight)) {
            for (var _iPose = 0; _iPose < nPoses; ++_iPose) {
              var _item = items[_iPose];
              _item.weight /= sumWeight;
            }
          } else {
            assertIsTrue(items.every(function (item) {
              return item.weight === 0.0;
            }));
          }
        };
        _proto2._checkAlternation = function _checkAlternation(newChoseIndex, fadeInDurations) {
          var items = this._items,
            oldChoseIndex = this._chosenPoseIndex;
          var nPoses = items.length;
          if (!nPoses) {
            return;
          }
          if (newChoseIndex === oldChoseIndex) {
            return;
          }
          if (newChoseIndex < 0 || newChoseIndex >= nPoses) {
            return;
          }
          var newFadeInDuration = Math.max(fadeInDurations[newChoseIndex], 0.0);
          if (newFadeInDuration < ZERO_ALTERING_DURATION_THRESHOLD) {
            for (var iPose = 0; iPose < nPoses; ++iPose) {
              var item = items[iPose];
              if (iPose === newChoseIndex) {
                item.selfSourceWeight = 1.0;
                item.selfTargetWeight = 1.0;
                item.weight = 1.0;
              } else {
                item.selfSourceWeight = 0.0;
                item.selfTargetWeight = 0.0;
                item.weight = 0.0;
              }
            }
          } else {
            var oldUniformTransitionRatio = this._blendingDuration < ZERO_ALTERING_DURATION_THRESHOLD ? 1.0 : this._elapsedTransitionTime / this._blendingDuration;
            for (var _iPose2 = 0; _iPose2 < nPoses; ++_iPose2) {
              var _item2 = items[_iPose2];
              _item2.selfSourceWeight = lerp(_item2.selfSourceWeight, _item2.selfTargetWeight, oldUniformTransitionRatio);
              if (_iPose2 === newChoseIndex) {
                _item2.selfTargetWeight = 1.0;
              } else {
                _item2.selfTargetWeight = 0.0;
              }
            }
          }
          this._chosenPoseIndex = newChoseIndex;
          this._elapsedTransitionTime = 0.0;
          this._blendingDuration = newFadeInDuration;
        };
        _createClass(EvaluationRecord, [{
          key: "items",
          get: function get() {
            return this._items;
          }
        }]);
        return EvaluationRecord;
      }();
      var ItemEvaluationRecord = function ItemEvaluationRecord() {
        this.selfSourceWeight = 0.0;
        this.selfTargetWeight = 0.0;
        this.weight = 0.0;
      };

      var _dec$S, _dec2$O, _dec3$C, _dec4$u, _dec5$q, _dec6$e, _dec7$b, _dec8$8, _class$R, _class2$Q, _descriptor$4;
      (_dec$S = ccclass$n(CLASS_NAME_PREFIX_ANIM + "PoseNodeChoosePoseByBoolean"), _dec2$O = poseGraphNodeCategory(POSE_GRAPH_NODE_MENU_PREFIX_CHOOSE), _dec3$C = poseGraphNodeAppearance({
        themeColor: '#D07979'
      }), _dec4$u = input({
        type: PoseGraphType.POSE
      }), _dec5$q = input({
        type: PoseGraphType.POSE
      }), _dec6$e = input({
        type: PoseGraphType.FLOAT
      }), _dec7$b = input({
        type: PoseGraphType.FLOAT
      }), _dec8$8 = input({
        type: PoseGraphType.BOOLEAN
      }), _dec$S(_class$R = _dec2$O(_class$R = _dec3$C(_class$R = (_class2$Q = function (_PoseNodeChoosePoseBa) {
        _inheritsLoose(PoseNodeChoosePoseByBoolean, _PoseNodeChoosePoseBa);
        function PoseNodeChoosePoseByBoolean() {
          var _this;
          _this = _PoseNodeChoosePoseBa.call(this, 2) || this;
          _initializerDefineProperty(_this, "choice", _descriptor$4, _assertThisInitialized(_this));
          return _this;
        }
        var _proto = PoseNodeChoosePoseByBoolean.prototype;
        _proto.getChosenIndex = function getChosenIndex() {
          return this.choice ? 0 : 1;
        };
        _createClass(PoseNodeChoosePoseByBoolean, [{
          key: "truePose",
          get: function get() {
            return this._poses[0];
          },
          set: function set(value) {
            this._poses[0] = value;
          }
        }, {
          key: "falsePose",
          get: function get() {
            return this._poses[1];
          },
          set: function set(value) {
            this._poses[1] = value;
          }
        }, {
          key: "trueFadeInDuration",
          get: function get() {
            return this._fadeInDurations[0];
          },
          set: function set(value) {
            this._fadeInDurations[0] = value;
          }
        }, {
          key: "falseFadeInDuration",
          get: function get() {
            return this._fadeInDurations[1];
          },
          set: function set(value) {
            this._fadeInDurations[1] = value;
          }
        }]);
        return PoseNodeChoosePoseByBoolean;
      }(PoseNodeChoosePoseBase), (_applyDecoratedDescriptor(_class2$Q.prototype, "truePose", [_dec4$u], Object.getOwnPropertyDescriptor(_class2$Q.prototype, "truePose"), _class2$Q.prototype), _applyDecoratedDescriptor(_class2$Q.prototype, "falsePose", [_dec5$q], Object.getOwnPropertyDescriptor(_class2$Q.prototype, "falsePose"), _class2$Q.prototype), _applyDecoratedDescriptor(_class2$Q.prototype, "trueFadeInDuration", [_dec6$e], Object.getOwnPropertyDescriptor(_class2$Q.prototype, "trueFadeInDuration"), _class2$Q.prototype), _applyDecoratedDescriptor(_class2$Q.prototype, "falseFadeInDuration", [_dec7$b], Object.getOwnPropertyDescriptor(_class2$Q.prototype, "falseFadeInDuration"), _class2$Q.prototype), _descriptor$4 = _applyDecoratedDescriptor(_class2$Q.prototype, "choice", [serializable$j, _dec8$8], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return true;
        }
      })), _class2$Q)) || _class$R) || _class$R) || _class$R);

      var _dec$R, _dec2$N, _dec3$B, _dec4$t, _dec5$p, _dec6$d, _class$Q, _class2$P, _descriptor$3;
      (_dec$R = ccclass$n(CLASS_NAME_PREFIX_ANIM + "PoseNodeChoosePoseByIndex"), _dec2$N = poseGraphNodeCategory(POSE_GRAPH_NODE_MENU_PREFIX_CHOOSE), _dec3$B = poseGraphNodeAppearance({
        themeColor: '#D07979'
      }), _dec4$t = input({
        type: PoseGraphType.POSE,
        arraySyncGroup: 'choose-item'
      }), _dec5$p = input({
        type: PoseGraphType.FLOAT,
        arraySyncGroup: 'choose-item',
        arraySyncGroupFollower: true
      }), _dec6$d = input({
        type: PoseGraphType.INTEGER
      }), _dec$R(_class$Q = _dec2$N(_class$Q = _dec3$B(_class$Q = (_class2$P = function (_PoseNodeChoosePoseBa) {
        _inheritsLoose(PoseNodeChoosePoseByIndex, _PoseNodeChoosePoseBa);
        function PoseNodeChoosePoseByIndex() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _PoseNodeChoosePoseBa.call.apply(_PoseNodeChoosePoseBa, [this].concat(args)) || this;
          _initializerDefineProperty(_this, "choice", _descriptor$3, _assertThisInitialized(_this));
          return _this;
        }
        var _proto = PoseNodeChoosePoseByIndex.prototype;
        _proto.getChosenIndex = function getChosenIndex() {
          return this.choice;
        };
        _createClass(PoseNodeChoosePoseByIndex, [{
          key: "poses",
          get: function get() {
            return this._poses;
          },
          set: function set(value) {
            this._poses = value;
          }
        }, {
          key: "fadeInDurations",
          get: function get() {
            return this._fadeInDurations;
          },
          set: function set(value) {
            this._fadeInDurations = value;
          }
        }]);
        return PoseNodeChoosePoseByIndex;
      }(PoseNodeChoosePoseBase), (_applyDecoratedDescriptor(_class2$P.prototype, "poses", [_dec4$t], Object.getOwnPropertyDescriptor(_class2$P.prototype, "poses"), _class2$P.prototype), _applyDecoratedDescriptor(_class2$P.prototype, "fadeInDurations", [_dec5$p], Object.getOwnPropertyDescriptor(_class2$P.prototype, "fadeInDurations"), _class2$P.prototype), _descriptor$3 = _applyDecoratedDescriptor(_class2$P.prototype, "choice", [serializable$j, _dec6$d], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return 0;
        }
      })), _class2$P)) || _class$Q) || _class$Q) || _class$Q);

      var _dec$Q, _dec2$M, _class$P, _class2$O, _initializer$L, _initializer2$F, _initializer3$u;
      var IntensityType;
      (function (IntensityType) {
        IntensityType[IntensityType["VALUE"] = 0] = "VALUE";
        IntensityType[IntensityType["AUXILIARY_CURVE"] = 1] = "AUXILIARY_CURVE";
      })(IntensityType || (IntensityType = {}));
      ccenum(IntensityType);
      var IntensitySpecification = (_dec$Q = ccclass$n(CLASS_NAME_PREFIX_ANIM + "IntensitySpecification"), _dec2$M = type$7(IntensityType), _dec$Q(_class$P = (_class2$O = function () {
        function IntensitySpecification() {
          this.type = _initializer$L && _initializer$L();
          this.value = _initializer2$F && _initializer2$F();
          this.auxiliaryCurveName = _initializer3$u && _initializer3$u();
          this._handle = undefined;
        }
        var _proto = IntensitySpecification.prototype;
        _proto.bind = function bind(context) {
          if (this.type === IntensityType.AUXILIARY_CURVE && this.auxiliaryCurveName) {
            var handle = context.bindAuxiliaryCurve(this.auxiliaryCurveName);
            this._handle = handle;
          }
        };
        _proto.evaluate = function evaluate(pose) {
          if (this.type === IntensityType.AUXILIARY_CURVE && this._handle) {
            var value = pose.auxiliaryCurves[this._handle.index];
            return value;
          }
          return this.value;
        };
        return IntensitySpecification;
      }(), (_initializer$L = applyDecoratedInitializer(_class2$O.prototype, "type", [_dec2$M, serializable$j], function () {
        return IntensityType.VALUE;
      }), _initializer2$F = applyDecoratedInitializer(_class2$O.prototype, "value", [serializable$j], function () {
        return 1.0;
      }), _initializer3$u = applyDecoratedInitializer(_class2$O.prototype, "auxiliaryCurveName", [serializable$j], function () {
        return '';
      })), _class2$O)) || _class$P);

      var _dec$P, _dec2$L, _dec3$A, _class4$5, _class5$7, _descriptor$2;
      var TransformModification = function TransformModification() {
        this.transformIndex = -1;
        this.transform = new Transform();
      };
      var TransformModificationQueue = function () {
        function TransformModificationQueue() {
          this._pool = new Pool(function () {
            return new TransformModification();
          }, 3);
          this._array = new CachedArray(3);
          this._debugLastTransformIndex = -1;
        }
        var _proto = TransformModificationQueue.prototype;
        _proto.push = function push(transformIndex, transform) {
          {
            assertIsTrue(transformIndex > this._debugLastTransformIndex, "Unexpected transform modification order");
            this._debugLastTransformIndex = transformIndex;
          }
          var mod = this._pool.alloc();
          mod.transformIndex = transformIndex;
          Transform.copy(mod.transform, transform);
          this._array.push(mod);
        };
        _proto.clear = function clear() {
          var length = this._array.length;
          for (var iMod = 0; iMod < length; ++iMod) {
            var mod = this._array.get(iMod);
            assertIsTrue(mod);
            this._pool.free(mod);
          }
          this._array.clear();
          {
            this._debugLastTransformIndex = -1;
          }
        };
        _createClass(TransformModificationQueue, [{
          key: "length",
          get: function get() {
            return this._array.length;
          }
        }, {
          key: "array",
          get: function get() {
            return this._array.array;
          }
        }]);
        return TransformModificationQueue;
      }();
      var PoseTransformSpaceFlagTable = function () {
        function PoseTransformSpaceFlagTable(nTransforms) {
          this._transformFlags = [];
          this._transformFlags = new Array(nTransforms);
        }
        var _proto2 = PoseTransformSpaceFlagTable.prototype;
        _proto2.clear = function clear() {
          this._transformFlags.fill(false);
        };
        _proto2.test = function test(transformIndex) {
          return this._transformFlags[transformIndex];
        };
        _proto2.set = function set(transformIndex) {
          this._transformFlags[transformIndex] = true;
        };
        _proto2.unset = function unset(transformIndex) {
          this._transformFlags[transformIndex] = false;
        };
        return PoseTransformSpaceFlagTable;
      }();
      var cacheTransform_spaceConversion = new Transform();
      var cacheParentTransform_spaceConversion = new Transform();
      function applyTransformModificationQueue(context, pose, queue, spaceFlagTable) {
        var nMods = queue.length;
        if (nMods === 0) {
          return;
        }
        {
          var debugLastModTransformIndex = -1;
          for (var iMod = 0; iMod < nMods; ++iMod) {
            var transformIndex = queue.array[iMod].transformIndex;
            assertIsTrue(transformIndex > debugLastModTransformIndex);
            debugLastModTransformIndex = transformIndex;
          }
        }
        if (pose._poseTransformSpace === PoseTransformSpace.LOCAL) {
          for (var _iMod = 0; _iMod < nMods; ++_iMod) {
            var _queue$array$_iMod = queue.array[_iMod],
              _transformIndex = _queue$array$_iMod.transformIndex,
              transform = _queue$array$_iMod.transform;
            pose.transforms.setTransform(_transformIndex, transform);
          }
          return;
        }
        assertIsTrue(pose._poseTransformSpace === PoseTransformSpace.COMPONENT);
        spaceFlagTable.clear();
        var firstTransformToConvert = queue.array[0].transformIndex;
        var lastTransformToConvert = firstTransformToConvert;
        for (var _iMod2 = 0; _iMod2 < nMods; ++_iMod2) {
          var _transformIndex2 = queue.array[_iMod2].transformIndex;
          spaceFlagTable.set(_transformIndex2);
          lastTransformToConvert = _transformIndex2;
        }
        for (var _transformIndex3 = firstTransformToConvert; _transformIndex3 < pose.transforms.length; ++_transformIndex3) {
          var parentTransformIndex = context.parentTable[_transformIndex3];
          if (parentTransformIndex < 0) {
            continue;
          }
          if (spaceFlagTable.test(parentTransformIndex)) {
            spaceFlagTable.set(_transformIndex3);
            lastTransformToConvert = _transformIndex3;
          }
        }
        for (var _transformIndex4 = lastTransformToConvert; _transformIndex4 >= firstTransformToConvert; --_transformIndex4) {
          if (spaceFlagTable.test(_transformIndex4)) {
            var _parentTransformIndex = context.parentTable[_transformIndex4];
            if (_parentTransformIndex >= 0) {
              var _transform = pose.transforms.getTransform(_transformIndex4, cacheTransform_spaceConversion);
              var parentTransform = pose.transforms.getTransform(_parentTransformIndex, cacheParentTransform_spaceConversion);
              Transform.calculateRelative(_transform, _transform, parentTransform);
              pose.transforms.setTransform(_transformIndex4, _transform);
            }
          }
        }
        for (var _iMod3 = 0; _iMod3 < nMods; ++_iMod3) {
          var _queue$array$_iMod2 = queue.array[_iMod3],
            _transformIndex5 = _queue$array$_iMod2.transformIndex,
            _transform2 = _queue$array$_iMod2.transform;
          pose.transforms.setTransform(_transformIndex5, _transform2);
          spaceFlagTable.unset(_transformIndex5);
        }
        for (var _transformIndex6 = firstTransformToConvert; _transformIndex6 <= lastTransformToConvert; ++_transformIndex6) {
          if (spaceFlagTable.test(_transformIndex6)) {
            var _parentTransformIndex2 = context.parentTable[_transformIndex6];
            assertIsTrue(_parentTransformIndex2 >= 0);
            var _transform3 = pose.transforms.getTransform(_transformIndex6, cacheTransform_spaceConversion);
            var _parentTransform = pose.transforms.getTransform(_parentTransformIndex2, cacheParentTransform_spaceConversion);
            Transform.multiply(_transform3, _parentTransform, _transform3);
            pose.transforms.setTransform(_transformIndex6, _transform3);
          }
        }
      }
      var PoseNodeModifyPoseBase = (_dec$P = ccclass$n(CLASS_NAME_PREFIX_ANIM + "PoseNodeModifyPoseBase"), _dec2$L = poseGraphNodeHide(), _dec3$A = input({
        type: PoseGraphType.POSE
      }), _dec$P(_class4$5 = _dec2$L(_class4$5 = (_class5$7 = function (_PoseNode) {
        _inheritsLoose(PoseNodeModifyPoseBase, _PoseNode);
        function PoseNodeModifyPoseBase() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _PoseNode.call.apply(_PoseNode, [this].concat(args)) || this;
          _initializerDefineProperty(_this, "pose", _descriptor$2, _assertThisInitialized(_this));
          _this._modificationQueue = new TransformModificationQueue();
          _this._spaceFlagTable = new PoseTransformSpaceFlagTable(0);
          return _this;
        }
        var _proto3 = PoseNodeModifyPoseBase.prototype;
        _proto3.settle = function settle(context) {
          var _this$pose;
          (_this$pose = this.pose) === null || _this$pose === void 0 ? void 0 : _this$pose.settle(context);
          this._spaceFlagTable = new PoseTransformSpaceFlagTable(context.transformCount);
        };
        _proto3.reenter = function reenter() {
          var _this$pose2;
          (_this$pose2 = this.pose) === null || _this$pose2 === void 0 ? void 0 : _this$pose2.reenter();
        };
        _proto3.bind = function bind(context) {
          var _this$pose3;
          (_this$pose3 = this.pose) === null || _this$pose3 === void 0 ? void 0 : _this$pose3.bind(context);
        };
        _proto3.doUpdate = function doUpdate(context) {
          var _this$pose4;
          (_this$pose4 = this.pose) === null || _this$pose4 === void 0 ? void 0 : _this$pose4.update(context);
        };
        _proto3.doEvaluate = function doEvaluate(context) {
          var _this$pose$evaluate, _this$pose5;
          var poseTransformSpaceRequirement = this.getPoseTransformSpaceRequirement();
          var inputPose = (_this$pose$evaluate = (_this$pose5 = this.pose) === null || _this$pose5 === void 0 ? void 0 : _this$pose5.evaluate(context, poseTransformSpaceRequirement)) !== null && _this$pose$evaluate !== void 0 ? _this$pose$evaluate : PoseNode.evaluateDefaultPose(context, poseTransformSpaceRequirement);
          var modificationQueue = this._modificationQueue;
          assertIsTrue(modificationQueue.length === 0);
          this.modifyPose(context, inputPose, modificationQueue);
          applyTransformModificationQueue(context, inputPose, modificationQueue, this._spaceFlagTable);
          modificationQueue.clear();
          return inputPose;
        };
        return PoseNodeModifyPoseBase;
      }(PoseNode), (_descriptor$2 = _applyDecoratedDescriptor(_class5$7.prototype, "pose", [serializable$j, _dec3$A], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return null;
        }
      })), _class5$7)) || _class4$5) || _class4$5);

      var _dec$O, _dec2$K, _dec3$z, _dec4$s, _dec5$o, _dec6$c, _dec7$a, _dec8$7, _dec9$7, _class$O, _class2$N, _initializer$K, _initializer2$E, _descriptor$1, _initializer3$t, _descriptor2, _initializer4$l, _initializer5$f;
      var TransformOperation;
      (function (TransformOperation) {
        TransformOperation[TransformOperation["LEAVE_UNCHANGED"] = 0] = "LEAVE_UNCHANGED";
        TransformOperation[TransformOperation["REPLACE"] = 1] = "REPLACE";
        TransformOperation[TransformOperation["ADD"] = 2] = "ADD";
      })(TransformOperation || (TransformOperation = {}));
      ccenum(TransformOperation);
      var APPLY_INTENSITY_EPSILON = 1e-5;
      var cacheTransform$1 = new Transform();
      (_dec$O = ccclass$n(CLASS_NAME_PREFIX_ANIM + "PoseNodeApplyTransform"), _dec2$K = poseGraphNodeCategory(POSE_GRAPH_NODE_MENU_PREFIX_POSE), _dec3$z = poseGraphNodeAppearance({
        themeColor: '#72A869'
      }), _dec4$s = type$7(TransformOperation), _dec5$o = input({
        type: PoseGraphType.VEC3
      }), _dec6$c = type$7(TransformOperation), _dec7$a = input({
        type: PoseGraphType.QUAT
      }), _dec8$7 = type$7(TransformSpace), _dec9$7 = input({
        type: PoseGraphType.FLOAT
      }), _dec$O(_class$O = _dec2$K(_class$O = _dec3$z(_class$O = (_class2$N = function (_PoseNodeModifyPoseBa) {
        _inheritsLoose(PoseNodeApplyTransform, _PoseNodeModifyPoseBa);
        function PoseNodeApplyTransform() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _PoseNodeModifyPoseBa.call.apply(_PoseNodeModifyPoseBa, [this].concat(args)) || this;
          _this.node = _initializer$K && _initializer$K();
          _this.positionOperation = _initializer2$E && _initializer2$E();
          _initializerDefineProperty(_this, "position", _descriptor$1, _assertThisInitialized(_this));
          _this.rotationOperation = _initializer3$t && _initializer3$t();
          _initializerDefineProperty(_this, "rotation", _descriptor2, _assertThisInitialized(_this));
          _this.intensity = _initializer4$l && _initializer4$l();
          _this.transformSpace = _initializer5$f && _initializer5$f();
          _this._transformHandle = null;
          return _this;
        }
        var _proto = PoseNodeApplyTransform.prototype;
        _proto.bind = function bind(context) {
          var nodeName = this.node;
          _PoseNodeModifyPoseBa.prototype.bind.call(this, context);
          if (!nodeName) {
            return;
          }
          var transformHandle = context.bindTransformByName(nodeName);
          if (!transformHandle) {
            error("Failed to bind transform " + nodeName);
            return;
          }
          this._transformHandle = transformHandle;
          this.intensity.bind(context);
        };
        _proto.getPoseTransformSpaceRequirement = function getPoseTransformSpaceRequirement() {
          return PoseTransformSpaceRequirement.NO;
        };
        _proto.modifyPose = function modifyPose(context, inputPose, modificationQueue) {
          var transformHandle = this._transformHandle;
          if (!transformHandle) {
            return inputPose;
          }
          var intensity = this.intensity.evaluate(inputPose);
          if (intensity < APPLY_INTENSITY_EPSILON) {
            return inputPose;
          }
          var fullIntensity = approx(intensity, 1.0, APPLY_INTENSITY_EPSILON);
          var transformIndex = transformHandle.index;
          var nodeTransform = inputPose.transforms.getTransform(transformIndex, cacheTransform$1);
          var rotationOperation = this.rotationOperation;
          if (rotationOperation !== TransformOperation.LEAVE_UNCHANGED) {
            var rotation = this.rotation,
              rotationSpace = this.transformSpace;
            context._convertPoseSpaceTransformToTargetSpace(nodeTransform, rotationSpace, inputPose, transformIndex);
            switch (rotationOperation) {
              default:
              case TransformOperation.REPLACE:
                replaceRotation(nodeTransform, rotation, intensity, fullIntensity);
                break;
              case TransformOperation.ADD:
                addRotation(nodeTransform, rotation, intensity, fullIntensity);
                break;
            }
            context._convertTransformToPoseTransformSpace(nodeTransform, rotationSpace, inputPose, transformIndex);
          }
          var positionOperation = this.positionOperation;
          if (positionOperation !== TransformOperation.LEAVE_UNCHANGED) {
            var position = this.position,
              positionSpace = this.transformSpace;
            context._convertPoseSpaceTransformToTargetSpace(nodeTransform, positionSpace, inputPose, transformIndex);
            switch (positionOperation) {
              default:
              case TransformOperation.REPLACE:
                replacePosition(nodeTransform, position, intensity, fullIntensity);
                break;
              case TransformOperation.ADD:
                addPosition(nodeTransform, position, intensity, fullIntensity);
                break;
            }
            context._convertTransformToPoseTransformSpace(nodeTransform, positionSpace, inputPose, transformIndex);
          }
          modificationQueue.push(transformIndex, nodeTransform);
          return inputPose;
        };
        _createClass(PoseNodeApplyTransform, [{
          key: "intensityValue",
          get: function get() {
            return this.intensity.value;
          },
          set: function set(value) {
            this.intensity.value = value;
          }
        }]);
        return PoseNodeApplyTransform;
      }(PoseNodeModifyPoseBase), (_initializer$K = applyDecoratedInitializer(_class2$N.prototype, "node", [serializable$j], function () {
        return '';
      }), _initializer2$E = applyDecoratedInitializer(_class2$N.prototype, "positionOperation", [serializable$j, _dec4$s], function () {
        return TransformOperation.LEAVE_UNCHANGED;
      }), _descriptor$1 = _applyDecoratedDescriptor(_class2$N.prototype, "position", [serializable$j, _dec5$o], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return new Vec3();
        }
      }), _initializer3$t = applyDecoratedInitializer(_class2$N.prototype, "rotationOperation", [serializable$j, _dec6$c], function () {
        return TransformOperation.LEAVE_UNCHANGED;
      }), _descriptor2 = _applyDecoratedDescriptor(_class2$N.prototype, "rotation", [serializable$j, _dec7$a], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return new Quat();
        }
      }), _initializer4$l = applyDecoratedInitializer(_class2$N.prototype, "intensity", [serializable$j], function () {
        return new IntensitySpecification();
      }), _initializer5$f = applyDecoratedInitializer(_class2$N.prototype, "transformSpace", [serializable$j, _dec8$7], function () {
        return TransformSpace.WORLD;
      }), _applyDecoratedDescriptor(_class2$N.prototype, "intensityValue", [_dec9$7], Object.getOwnPropertyDescriptor(_class2$N.prototype, "intensityValue"), _class2$N.prototype)), _class2$N)) || _class$O) || _class$O) || _class$O);
      var _ref = function () {
          var cacheInput = new Vec3();
          var cacheResult = new Vec3();
          return {
            replace: replace,
            add: add
          };
          function replace(transform, value, intensity, fullIntensity) {
            if (fullIntensity) {
              transform.position = value;
            } else {
              var inputPosition = Vec3.copy(cacheInput, transform.position);
              Vec3.lerp(inputPosition, inputPosition, value, intensity);
              transform.position = inputPosition;
            }
          }
          function add(transform, value, intensity, fullIntensity) {
            var result = cacheResult;
            if (fullIntensity) {
              Vec3.copy(result, value);
            } else {
              Vec3.slerp(result, Vec3.ZERO, value, intensity);
            }
            Vec3.add(result, transform.position, result);
            transform.position = result;
          }
        }(),
        replacePosition = _ref.replace,
        addPosition = _ref.add;
      var _ref2 = function () {
          var cacheInput = new Quat();
          var cacheResult = new Quat();
          return {
            replace: replace,
            add: add
          };
          function replace(transform, value, intensity, fullIntensity) {
            if (fullIntensity) {
              transform.rotation = value;
            } else {
              var inputRotation = Quat.copy(cacheInput, transform.rotation);
              Quat.slerp(inputRotation, inputRotation, value, intensity);
              transform.rotation = inputRotation;
            }
          }
          function add(transform, value, intensity, fullIntensity) {
            var inputRotation = Quat.copy(cacheInput, transform.rotation);
            var resultRotation = cacheResult;
            if (fullIntensity) {
              Quat.copy(resultRotation, value);
            } else {
              Quat.slerp(resultRotation, Quat.IDENTITY, value, intensity);
            }
            Quat.multiply(resultRotation, resultRotation, inputRotation);
            transform.rotation = resultRotation;
          }
        }(),
        replaceRotation = _ref2.replace,
        addRotation = _ref2.add;

      var _dec$N, _dec2$J, _dec3$y, _dec4$r, _class$N, _class2$M, _initializer$J, _initializer2$D, _initializer3$s;
      var cacheTransform = new Transform();
      var CopySpace;
      (function (CopySpace) {
        CopySpace[CopySpace["LOCAL"] = 0] = "LOCAL";
        CopySpace[CopySpace["COMPONENT"] = 1] = "COMPONENT";
      })(CopySpace || (CopySpace = {}));
      ccenum(CopySpace);
      (_dec$N = ccclass$n(CLASS_NAME_PREFIX_ANIM + "PoseNodeCopyTransform"), _dec2$J = poseGraphNodeCategory(POSE_GRAPH_NODE_MENU_PREFIX_POSE), _dec3$y = poseGraphNodeAppearance({
        themeColor: '#72A869'
      }), _dec4$r = type$7(CopySpace), _dec$N(_class$N = _dec2$J(_class$N = _dec3$y(_class$N = (_class2$M = function (_PoseNodeModifyPoseBa) {
        _inheritsLoose(PoseNodeCopyTransform, _PoseNodeModifyPoseBa);
        function PoseNodeCopyTransform() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _PoseNodeModifyPoseBa.call.apply(_PoseNodeModifyPoseBa, [this].concat(args)) || this;
          _this.sourceNodeName = _initializer$J && _initializer$J();
          _this.targetNodeName = _initializer2$D && _initializer2$D();
          _this.space = _initializer3$s && _initializer3$s();
          _this._workspace = undefined;
          return _this;
        }
        var _proto = PoseNodeCopyTransform.prototype;
        _proto.bind = function bind(context) {
          _PoseNodeModifyPoseBa.prototype.bind.call(this, context);
          var sourceTransformHandle = context.bindTransformByName(this.sourceNodeName);
          var targetTransformHandle = context.bindTransformByName(this.targetNodeName);
          if (!sourceTransformHandle || !targetTransformHandle) {
            sourceTransformHandle === null || sourceTransformHandle === void 0 ? void 0 : sourceTransformHandle.destroy();
            targetTransformHandle === null || targetTransformHandle === void 0 ? void 0 : targetTransformHandle.destroy();
            return;
          }
          this._workspace = new Workspace$1(sourceTransformHandle, targetTransformHandle);
        };
        _proto.modifyPose = function modifyPose(context, inputPose) {
          var workspace = this._workspace;
          if (!workspace) {
            return;
          }
          var sourceTransformIndex = workspace.hSource.index,
            targetTransformIndex = workspace.hTarget.index;
          var transform = inputPose.transforms.getTransform(sourceTransformIndex, cacheTransform);
          inputPose.transforms.setTransform(targetTransformIndex, transform);
        };
        _proto.getPoseTransformSpaceRequirement = function getPoseTransformSpaceRequirement() {
          return this.space === CopySpace.COMPONENT ? PoseTransformSpaceRequirement.COMPONENT : PoseTransformSpaceRequirement.LOCAL;
        };
        return PoseNodeCopyTransform;
      }(PoseNodeModifyPoseBase), (_initializer$J = applyDecoratedInitializer(_class2$M.prototype, "sourceNodeName", [serializable$j], function () {
        return '';
      }), _initializer2$D = applyDecoratedInitializer(_class2$M.prototype, "targetNodeName", [serializable$j], function () {
        return '';
      }), _initializer3$s = applyDecoratedInitializer(_class2$M.prototype, "space", [serializable$j, _dec4$r], function () {
        return CopySpace.COMPONENT;
      })), _class2$M)) || _class$N) || _class$N) || _class$N);
      var Workspace$1 = function Workspace(hSource, hTarget) {
        this.hSource = hSource;
        this.hTarget = hTarget;
      };

      var _dec$M, _dec2$I, _dec3$x, _dec4$q, _class$M, _class2$L, _initializer$I, _descriptor, _initializer2$C;
      var SetAuxiliaryCurveFlag;
      (function (SetAuxiliaryCurveFlag) {
        SetAuxiliaryCurveFlag[SetAuxiliaryCurveFlag["LEAVE_UNCHANGED"] = 0] = "LEAVE_UNCHANGED";
        SetAuxiliaryCurveFlag[SetAuxiliaryCurveFlag["REPLACE"] = 1] = "REPLACE";
        SetAuxiliaryCurveFlag[SetAuxiliaryCurveFlag["ADD"] = 2] = "ADD";
      })(SetAuxiliaryCurveFlag || (SetAuxiliaryCurveFlag = {}));
      ccenum(SetAuxiliaryCurveFlag);
      (_dec$M = ccclass$n(CLASS_NAME_PREFIX_ANIM + "PoseNodeSetAuxiliaryCurve"), _dec2$I = poseGraphNodeCategory(POSE_GRAPH_NODE_MENU_PREFIX_POSE), _dec3$x = input({
        type: PoseGraphType.FLOAT
      }), _dec4$q = type$7(SetAuxiliaryCurveFlag), _dec$M(_class$M = _dec2$I(_class$M = (_class2$L = function (_PoseNodeModifyPoseBa) {
        _inheritsLoose(PoseNodeSetAuxiliaryCurve, _PoseNodeModifyPoseBa);
        function PoseNodeSetAuxiliaryCurve() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _PoseNodeModifyPoseBa.call.apply(_PoseNodeModifyPoseBa, [this].concat(args)) || this;
          _this.curveName = _initializer$I && _initializer$I();
          _initializerDefineProperty(_this, "curveValue", _descriptor, _assertThisInitialized(_this));
          _this.flag = _initializer2$C && _initializer2$C();
          _this._handle = undefined;
          return _this;
        }
        var _proto = PoseNodeSetAuxiliaryCurve.prototype;
        _proto.bind = function bind(context) {
          _PoseNodeModifyPoseBa.prototype.bind.call(this, context);
          if (this.curveName) {
            this._handle = context.bindAuxiliaryCurve(this.curveName);
          }
        };
        _proto.getPoseTransformSpaceRequirement = function getPoseTransformSpaceRequirement() {
          return PoseTransformSpaceRequirement.NO;
        };
        _proto.modifyPose = function modifyPose(context, inputPose) {
          var handle = this._handle;
          if (!handle) {
            return;
          }
          switch (this.flag) {
            case SetAuxiliaryCurveFlag.REPLACE:
              inputPose.auxiliaryCurves[handle.index] = this.curveValue;
              break;
            case SetAuxiliaryCurveFlag.ADD:
              inputPose.auxiliaryCurves[handle.index] += this.curveValue;
              break;
            case SetAuxiliaryCurveFlag.LEAVE_UNCHANGED:
          }
        };
        return PoseNodeSetAuxiliaryCurve;
      }(PoseNodeModifyPoseBase), (_initializer$I = applyDecoratedInitializer(_class2$L.prototype, "curveName", [serializable$j], function () {
        return '';
      }), _descriptor = _applyDecoratedDescriptor(_class2$L.prototype, "curveValue", [serializable$j, _dec3$x], {
        configurable: true,
        enumerable: true,
        writable: true,
        initializer: function initializer() {
          return 0.0;
        }
      }), _initializer2$C = applyDecoratedInitializer(_class2$L.prototype, "flag", [serializable$j, _dec4$q], function () {
        return SetAuxiliaryCurveFlag.REPLACE;
      })), _class2$L)) || _class$M) || _class$M);

      var TwoBoneIKDebugger = function () {
        function TwoBoneIKDebugger() {
          this._node = void 0;
          this._meshRenderer = void 0;
          var node = new Node$1();
          legacyCC.director.getScene().addChild(node);
          var meshRenderer = node.addComponent(MeshRenderer);
          meshRenderer.material = function () {
            var material = new Material();
            material.reset({
              effectName: 'builtin-unlit',
              states: {
                primitive: PrimitiveMode.LINE_LIST
              },
              defines: {
                USE_VERTEX_COLOR: true
              }
            });
            return material;
          }();
          this._node = node;
          this._meshRenderer = meshRenderer;
        }
        var _proto = TwoBoneIKDebugger.prototype;
        _proto.draw = function draw(a, b, c) {
          var color1 = Color$1.RED;
          var color2 = Color$1.BLUE;
          var positions = [a.x, a.y, a.z, b.x, b.y, b.z, b.x, b.y, b.z, c.x, c.y, c.z];
          var colors = [color1.x, color1.y, color1.z, color1.w, color1.x, color1.y, color1.z, color1.w, color2.x, color2.y, color2.z, color2.w, color2.x, color2.y, color2.z, color2.w];
          var mesh = _createMesh({
            positions: positions,
            colors: colors,
            primitiveMode: PrimitiveMode.LINE_LIST
          });
          this._meshRenderer.mesh = mesh;
        };
        return TwoBoneIKDebugger;
      }();
      var debuggerMap = new WeakMap();
      function debugTwoBoneIKDraw(key, a, b, c) {
        if (typeof key !== 'object' || !key) {
          return;
        }
        var ikDebugger = debuggerMap.get(key);
        if (!ikDebugger) {
          ikDebugger = new TwoBoneIKDebugger();
          debuggerMap.set(key, ikDebugger);
        }
        ikDebugger.draw(a, b, c);
      }

      var TwoBoneIKPositionSanityChecker = function () {
        function TwoBoneIKPositionSanityChecker() {
          this._a = new Vec3();
        }
        var _proto = TwoBoneIKPositionSanityChecker.prototype;
        _proto.reset = function reset(a, b, c) {
          Vec3.copy(this._a, a);
          this._dAB = Vec3.distance(a, b);
          this._dBC = Vec3.distance(b, c);
        };
        _proto.check = function check(_a, _b, _c) {
          var CHECK_EPSILON = 1e-3;
          var dAB = Vec3.distance(_a, _b);
          var dBC = Vec3.distance(_b, _c);
          if (!approx(Vec3.distance(_a, this._a), 0.0, CHECK_EPSILON)) {
            debugger;
            return false;
          }
          if (!approx(dAB, this._dAB, CHECK_EPSILON)) {
            debugger;
            return false;
          }
          if (!approx(dBC, this._dBC, CHECK_EPSILON)) {
            debugger;
            return false;
          }
          return true;
        };
        return TwoBoneIKPositionSanityChecker;
      }();
      var solveTwoBoneIK = function () {
        var cacheQuat = new Quat();
        var cacheHint = new Vec3();
        var cacheBSolved = new Vec3();
        var cacheCSolved = new Vec3();
        var calculateRotationBetweenRays = function () {
          var cacheVec3_1 = new Vec3();
          var cacheVec3_2 = new Vec3();
          return function (out, sourceOrigin, sourceDestination, targetOrigin, targetDestination) {
            return Quat.rotationTo(out, Vec3.subtract(cacheVec3_1, sourceDestination, sourceOrigin).normalize(), Vec3.subtract(cacheVec3_2, targetDestination, targetOrigin).normalize());
          };
        }();
        return function (root, middle, end, target, middlePositionHint, debugKey) {
          var hint = Vec3.copy(cacheHint, middlePositionHint !== null && middlePositionHint !== void 0 ? middlePositionHint : middle.position);
          var pA = root.position;
          var pB = middle.position;
          var pC = end.position;
          end.rotation;
          {
            if (typeof debugKey !== undefined) {
              debugTwoBoneIKDraw(debugKey, pA, pB, pC);
            }
          }
          var bSolved = cacheBSolved;
          var cSolved = cacheCSolved;
          solveTwoBoneIKPositions(pA, pB, pC, target, hint, bSolved, cSolved);
          var qA = calculateRotationBetweenRays(cacheQuat, pA, pB, pA, bSolved);
          Quat.multiply(qA, qA, root.rotation);
          root.rotation = qA;
          var qB = calculateRotationBetweenRays(cacheQuat, pB, pC, bSolved, cSolved);
          Quat.multiply(qB, qB, middle.rotation);
          middle.rotation = qB;
          middle.position = bSolved;
          end.position = cSolved;
        };
      }();
      var solveTwoBoneIKPositions = function () {
        var cacheDirAT = new Vec3();
        var cacheDirAB = new Vec3();
        var cacheDirHeightLine = new Vec3();
        var cacheSanityChecker = new TwoBoneIKPositionSanityChecker() ;
        return function (a, b, c, target, middleTarget, bSolved, cSolved) {
          var sanityCheck = cacheSanityChecker ? function () {
            cacheSanityChecker === null || cacheSanityChecker === void 0 ? void 0 : cacheSanityChecker.reset(a, b, c);
            return function () {
              return cacheSanityChecker.check(a, bSolved, cSolved);
            };
          }() : undefined;
          var dAB = Vec3.distance(a, b);
          var dBC = Vec3.distance(b, c);
          var dAT = Vec3.distance(a, target);
          var dirAT = Vec3.subtract(cacheDirAT, target, a);
          dirAT.normalize();
          var chainLength = dAB + dBC;
          if (dAT >= chainLength) {
            Vec3.scaleAndAdd(bSolved, a, dirAT, dAB);
            Vec3.scaleAndAdd(cSolved, a, dirAT, chainLength);
            sanityCheck === null || sanityCheck === void 0 ? void 0 : sanityCheck();
            return;
          }
          Vec3.copy(cSolved, target);
          var cosḂAT = clamp$1((dAB * dAB + dAT * dAT - dBC * dBC) / (2 * dAB * dAT), -1.0, 1.0);
          var dirAB = Vec3.subtract(cacheDirAB, middleTarget, a);
          var dirHeightLine = Vec3.projectOnPlane(cacheDirHeightLine, dirAB, dirAT);
          dirHeightLine.normalize();
          var dAD = dAB * cosḂAT;
          var hSqr = dAB * dAB - dAD * dAD;
          if (hSqr < 0) {
            debugger;
          }
          var h = Math.sqrt(hSqr);
          Vec3.scaleAndAdd(bSolved, a, dirAT, dAD);
          Vec3.scaleAndAdd(bSolved, bSolved, dirHeightLine, h);
          sanityCheck === null || sanityCheck === void 0 ? void 0 : sanityCheck();
        };
      }();

      var POSE_GRAPH_NODE_MENU_PREFIX_IK = POSE_GRAPH_NODE_MENU_PREFIX_POSE + "/" + "i18n:ENGINE.animation_graph.pose_graph_node_sub_categories.pose_nodes_ik/";

      var _dec$L, _dec2$H, _dec3$w, _class$L, _class2$K, _initializer$H, _initializer2$B, _initializer3$r, _initializer4$k, _dec4$p, _dec5$n, _dec6$b, _dec7$9, _class4$4, _class5$6, _initializer5$e, _initializer6$b, _initializer7$a, _initializer8$9;
      var cacheRootTransform = new Transform();
      var cacheMiddleTransform = new Transform();
      var cacheEndEffectorTransform = new Transform();
      var cacheEndEffectorTargetPosition = new Vec3();
      var cachePoleTargetPosition = new Vec3();
      var cacheTransform_evaluateTarget = new Transform();
      var TargetSpecificationType;
      (function (TargetSpecificationType) {
        TargetSpecificationType[TargetSpecificationType["NONE"] = 0] = "NONE";
        TargetSpecificationType[TargetSpecificationType["VALUE"] = 1] = "VALUE";
        TargetSpecificationType[TargetSpecificationType["BONE"] = 2] = "BONE";
      })(TargetSpecificationType || (TargetSpecificationType = {}));
      ccenum(TargetSpecificationType);
      var TargetSpecification = (_dec$L = ccclass$n(CLASS_NAME_PREFIX_ANIM + "PoseNodeTwoBoneIKSolver.TargetSpecification"), _dec2$H = type$7(TargetSpecificationType), _dec3$w = type$7(TransformSpace), _dec$L(_class$L = (_class2$K = function () {
        function TargetSpecification(type) {
          this.type = _initializer$H && _initializer$H();
          this.targetPosition = _initializer2$B && _initializer2$B();
          this.targetPositionSpace = _initializer3$r && _initializer3$r();
          this.targetBone = _initializer4$k && _initializer4$k();
          this._sourceBoneHandle = undefined;
          this._targetBoneHandle = undefined;
          if (typeof type !== 'undefined') {
            this.type = type;
          }
        }
        var _proto = TargetSpecification.prototype;
        _proto.bind = function bind(context, sourceBoneHandle) {
          this._sourceBoneHandle = sourceBoneHandle;
          if (this.type === TargetSpecificationType.BONE && this.targetBone) {
            var _context$bindTransfor;
            this._targetBoneHandle = (_context$bindTransfor = context.bindTransformByName(this.targetBone)) !== null && _context$bindTransfor !== void 0 ? _context$bindTransfor : undefined;
          }
        };
        _proto.evaluate = function evaluate(outTargetPosition, pose, context) {
          assertIsTrue(this._sourceBoneHandle);
          if (this._targetBoneHandle) {
            pose.transforms.getPosition(this._targetBoneHandle.index, outTargetPosition);
          } else if (this.type === TargetSpecificationType.NONE) {
            pose.transforms.getPosition(this._sourceBoneHandle.index, outTargetPosition);
          } else {
            var targetTransform = Transform.setIdentity(cacheTransform_evaluateTarget);
            targetTransform.position = this.targetPosition;
            context._convertTransformToPoseTransformSpace(targetTransform, this.targetPositionSpace, pose, this._sourceBoneHandle.index);
            Vec3.copy(outTargetPosition, targetTransform.position);
          }
          return outTargetPosition;
        };
        return TargetSpecification;
      }(), (_initializer$H = applyDecoratedInitializer(_class2$K.prototype, "type", [serializable$j, _dec2$H], function () {
        return TargetSpecificationType.VALUE;
      }), _initializer2$B = applyDecoratedInitializer(_class2$K.prototype, "targetPosition", [serializable$j], function () {
        return new Vec3();
      }), _initializer3$r = applyDecoratedInitializer(_class2$K.prototype, "targetPositionSpace", [serializable$j, _dec3$w], function () {
        return TransformSpace.WORLD;
      }), _initializer4$k = applyDecoratedInitializer(_class2$K.prototype, "targetBone", [serializable$j], function () {
        return '';
      })), _class2$K)) || _class$L);
      (_dec4$p = ccclass$n(CLASS_NAME_PREFIX_ANIM + "PoseNodeTwoBoneIKSolver"), _dec5$n = poseGraphNodeCategory(POSE_GRAPH_NODE_MENU_PREFIX_IK), _dec6$b = input({
        type: PoseGraphType.VEC3
      }), _dec7$9 = input({
        type: PoseGraphType.VEC3
      }), _dec4$p(_class4$4 = _dec5$n(_class4$4 = (_class5$6 = function (_PoseNodeModifyPoseBa) {
        _inheritsLoose(PoseNodeTwoBoneIKSolver, _PoseNodeModifyPoseBa);
        function PoseNodeTwoBoneIKSolver() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _PoseNodeModifyPoseBa.call.apply(_PoseNodeModifyPoseBa, [this].concat(args)) || this;
          _this.debug = _initializer5$e && _initializer5$e();
          _this.endEffectorBoneName = _initializer6$b && _initializer6$b();
          _this.endEffectorTarget = _initializer7$a && _initializer7$a();
          _this.poleTarget = _initializer8$9 && _initializer8$9();
          _this._workspace = undefined;
          return _this;
        }
        var _proto2 = PoseNodeTwoBoneIKSolver.prototype;
        _proto2.bind = function bind(context) {
          _PoseNodeModifyPoseBa.prototype.bind.call(this, context);
          if (this.endEffectorBoneName) {
            var parentBoneName = context.getParentBoneNameByName(this.endEffectorBoneName);
            var ikRootBoneName = parentBoneName ? context.getParentBoneNameByName(parentBoneName) : '';
            if (parentBoneName && ikRootBoneName) {
              var _hEndEffector = context.bindTransformByName(this.endEffectorBoneName);
              var _hMiddle = context.bindTransformByName(parentBoneName);
              var hIKRoot = context.bindTransformByName(ikRootBoneName);
              if (!_hEndEffector || !_hMiddle || !hIKRoot) {
                _hEndEffector === null || _hEndEffector === void 0 ? void 0 : _hEndEffector.destroy();
                _hMiddle === null || _hMiddle === void 0 ? void 0 : _hMiddle.destroy();
                hIKRoot === null || hIKRoot === void 0 ? void 0 : hIKRoot.destroy();
              } else {
                this.endEffectorTarget.bind(context, _hEndEffector);
                this.poleTarget.bind(context, _hMiddle);
                this._workspace = new Workspace(_hEndEffector, _hMiddle, hIKRoot);
              }
            }
          }
        };
        _proto2.getPoseTransformSpaceRequirement = function getPoseTransformSpaceRequirement() {
          return PoseTransformSpaceRequirement.COMPONENT;
        };
        _proto2.modifyPose = function modifyPose(context, inputPose, modificationQueue) {
          var workspace = this._workspace;
          if (!workspace) {
            return;
          }
          var iRootTransform = workspace.hRoot.index,
            iMiddleTransform = workspace.hMiddle.index,
            iEndEffectorTransform = workspace.hEndEffector.index;
          var rootTransform = inputPose.transforms.getTransform(iRootTransform, cacheRootTransform);
          var middleTransform = inputPose.transforms.getTransform(iMiddleTransform, cacheMiddleTransform);
          var endEffectorTransform = inputPose.transforms.getTransform(iEndEffectorTransform, cacheEndEffectorTransform);
          var endEffectorTargetPosition = this.endEffectorTarget.evaluate(cacheEndEffectorTargetPosition, inputPose, context);
          var poleTargetPosition = this.poleTarget.evaluate(cachePoleTargetPosition, inputPose, context);
          solveTwoBoneIK(rootTransform, middleTransform, endEffectorTransform, endEffectorTargetPosition, poleTargetPosition, this.debug ? this : undefined);
          modificationQueue.push(iRootTransform, rootTransform);
          modificationQueue.push(iMiddleTransform, middleTransform);
          modificationQueue.push(iEndEffectorTransform, endEffectorTransform);
        };
        _createClass(PoseNodeTwoBoneIKSolver, [{
          key: "endEffectorTargetPosition",
          get: function get() {
            return this.endEffectorTarget.targetPosition;
          },
          set: function set(value) {
            Vec3.copy(this.endEffectorTarget.targetPosition, value);
          }
        }, {
          key: "poleTargetPosition",
          get: function get() {
            return this.poleTarget.targetPosition;
          },
          set: function set(value) {
            Vec3.copy(this.poleTarget.targetPosition, value);
          }
        }]);
        return PoseNodeTwoBoneIKSolver;
      }(PoseNodeModifyPoseBase), (_initializer5$e = applyDecoratedInitializer(_class5$6.prototype, "debug", [serializable$j], function () {
        return false;
      }), _initializer6$b = applyDecoratedInitializer(_class5$6.prototype, "endEffectorBoneName", [serializable$j], function () {
        return '';
      }), _initializer7$a = applyDecoratedInitializer(_class5$6.prototype, "endEffectorTarget", [serializable$j], function () {
        return new TargetSpecification(TargetSpecificationType.VALUE);
      }), _applyDecoratedDescriptor(_class5$6.prototype, "endEffectorTargetPosition", [_dec6$b], Object.getOwnPropertyDescriptor(_class5$6.prototype, "endEffectorTargetPosition"), _class5$6.prototype), _initializer8$9 = applyDecoratedInitializer(_class5$6.prototype, "poleTarget", [serializable$j], function () {
        return new TargetSpecification(TargetSpecificationType.NONE);
      }), _applyDecoratedDescriptor(_class5$6.prototype, "poleTargetPosition", [_dec7$9], Object.getOwnPropertyDescriptor(_class5$6.prototype, "poleTargetPosition"), _class5$6.prototype)), _class5$6)) || _class4$4) || _class4$4);
      var Workspace = function Workspace(hEndEffector, hMiddle, hRoot) {
        this.hEndEffector = hEndEffector;
        this.hMiddle = hMiddle;
        this.hRoot = hRoot;
      };

      var _dec$K, _dec2$G, _class$K, _class2$J, _initializer$G, _dec3$v, _dec4$o, _dec5$m, _class4$3, _dec6$a, _dec7$8, _dec8$6, _class5$5, _dec9$6, _dec10$4, _dec11$3, _class6$1, _dec12$3, _dec13$3, _dec14$2, _class7$3, _dec15$2, _dec16$2, _dec17$2, _class8$3;
      var createNodeFactory = {
        listEntries: function listEntries(context) {
          var entries = [];
          for (var _iterator = _createForOfIteratorHelperLoose(context.animationGraph.variables), _step; !(_step = _iterator()).done;) {
            var _step$value = _step.value,
              variableName = _step$value[0],
              type = _step$value[1].type;
            if (type === VariableType.TRIGGER) {
              continue;
            }
            var poseGraphType = void 0;
            switch (type) {
              default:
                break;
              case VariableType.FLOAT:
                poseGraphType = PoseGraphType.FLOAT;
                break;
              case VariableType.INTEGER:
                poseGraphType = PoseGraphType.INTEGER;
                break;
              case VariableType.BOOLEAN:
                poseGraphType = PoseGraphType.BOOLEAN;
                break;
              case VariableType.VEC3_experimental:
                poseGraphType = PoseGraphType.VEC3;
                break;
              case VariableType.QUAT_experimental:
                poseGraphType = PoseGraphType.QUAT;
                break;
            }
            if (typeof poseGraphType === 'undefined') {
              continue;
            }
            entries.push({
              arg: {
                name: variableName,
                type: poseGraphType
              },
              menu: variableName
            });
          }
          return entries;
        },
        create: function create(arg) {
          var node;
          switch (arg.type) {
            default:
              throw new Error("Bad create node arg: " + PoseGraphType[arg.type]);
            case PoseGraphType.FLOAT:
              node = new PVNodeGetVariableFloat();
              break;
            case PoseGraphType.INTEGER:
              node = new PVNodeGetVariableInteger();
              break;
            case PoseGraphType.BOOLEAN:
              node = new PVNodeGetVariableBoolean();
              break;
            case PoseGraphType.VEC3:
              node = new PVNodeGetVariableVec3();
              break;
            case PoseGraphType.QUAT:
              node = new PVNodeGetVariableQuat();
              break;
          }
          node.variableName = arg.name;
          return node;
        }
      };
      var PVNodeGetVariableBase = (_dec$K = ccclass$n(CLASS_NAME_PREFIX_ANIM + "PVNodeGetVariableBase"), _dec2$G = poseGraphCreateNodeFactory(createNodeFactory), _dec$K(_class$K = _dec2$G(_class$K = (_class2$J = function (_SingleOutputPVNode) {
        _inheritsLoose(PVNodeGetVariableBase, _SingleOutputPVNode);
        function PVNodeGetVariableBase() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _SingleOutputPVNode.call.apply(_SingleOutputPVNode, [this].concat(args)) || this;
          _this.variableName = _initializer$G && _initializer$G();
          _this._varInstance = undefined;
          return _this;
        }
        var _proto = PVNodeGetVariableBase.prototype;
        _proto.link = function link(context) {
          this._varInstance = context.getVar(this.variableName);
        };
        return PVNodeGetVariableBase;
      }(SingleOutputPVNode), (_initializer$G = applyDecoratedInitializer(_class2$J.prototype, "variableName", [serializable$j], function () {
        return '';
      })), _class2$J)) || _class$K) || _class$K);
      var PVNodeGetVariableFloat = (_dec3$v = ccclass$n(CLASS_NAME_PREFIX_ANIM + "PVNodeGetVariableFloat"), _dec4$o = poseGraphNodeHide(), _dec5$m = poseGraphNodeAppearance({
        inline: true,
        themeColor: '#8471CF'
      }), _dec3$v(_class4$3 = _dec4$o(_class4$3 = _dec5$m(_class4$3 = function (_PVNodeGetVariableBas) {
        _inheritsLoose(PVNodeGetVariableFloat, _PVNodeGetVariableBas);
        function PVNodeGetVariableFloat() {
          return _PVNodeGetVariableBas.call(this, PoseGraphType.FLOAT) || this;
        }
        var _proto2 = PVNodeGetVariableFloat.prototype;
        _proto2.selfEvaluateDefaultOutput = function selfEvaluateDefaultOutput() {
          var _this$_varInstance;
          return (_this$_varInstance = this._varInstance) === null || _this$_varInstance === void 0 ? void 0 : _this$_varInstance.value;
        };
        return PVNodeGetVariableFloat;
      }(PVNodeGetVariableBase)) || _class4$3) || _class4$3) || _class4$3);
      var PVNodeGetVariableInteger = (_dec6$a = ccclass$n(CLASS_NAME_PREFIX_ANIM + "PVNodeGetVariableInteger"), _dec7$8 = poseGraphNodeHide(), _dec8$6 = poseGraphNodeAppearance({
        inline: true,
        themeColor: '#2A90DC'
      }), _dec6$a(_class5$5 = _dec7$8(_class5$5 = _dec8$6(_class5$5 = function (_PVNodeGetVariableBas2) {
        _inheritsLoose(PVNodeGetVariableInteger, _PVNodeGetVariableBas2);
        function PVNodeGetVariableInteger() {
          return _PVNodeGetVariableBas2.call(this, PoseGraphType.INTEGER) || this;
        }
        var _proto3 = PVNodeGetVariableInteger.prototype;
        _proto3.selfEvaluateDefaultOutput = function selfEvaluateDefaultOutput() {
          var _this$_varInstance2;
          return (_this$_varInstance2 = this._varInstance) === null || _this$_varInstance2 === void 0 ? void 0 : _this$_varInstance2.value;
        };
        return PVNodeGetVariableInteger;
      }(PVNodeGetVariableBase)) || _class5$5) || _class5$5) || _class5$5);
      var PVNodeGetVariableBoolean = (_dec9$6 = ccclass$n(CLASS_NAME_PREFIX_ANIM + "PVNodeGetVariableBoolean"), _dec10$4 = poseGraphNodeHide(), _dec11$3 = poseGraphNodeAppearance({
        inline: true,
        themeColor: '#D07979'
      }), _dec9$6(_class6$1 = _dec10$4(_class6$1 = _dec11$3(_class6$1 = function (_PVNodeGetVariableBas3) {
        _inheritsLoose(PVNodeGetVariableBoolean, _PVNodeGetVariableBas3);
        function PVNodeGetVariableBoolean() {
          return _PVNodeGetVariableBas3.call(this, PoseGraphType.BOOLEAN) || this;
        }
        var _proto4 = PVNodeGetVariableBoolean.prototype;
        _proto4.selfEvaluateDefaultOutput = function selfEvaluateDefaultOutput() {
          var _this$_varInstance3;
          return (_this$_varInstance3 = this._varInstance) === null || _this$_varInstance3 === void 0 ? void 0 : _this$_varInstance3.value;
        };
        return PVNodeGetVariableBoolean;
      }(PVNodeGetVariableBase)) || _class6$1) || _class6$1) || _class6$1);
      var PVNodeGetVariableVec3 = (_dec12$3 = ccclass$n(CLASS_NAME_PREFIX_ANIM + "PVNodeGetVariableVec3"), _dec13$3 = poseGraphNodeHide(), _dec14$2 = poseGraphNodeAppearance({
        inline: true,
        themeColor: '#D97721'
      }), _dec12$3(_class7$3 = _dec13$3(_class7$3 = _dec14$2(_class7$3 = function (_PVNodeGetVariableBas4) {
        _inheritsLoose(PVNodeGetVariableVec3, _PVNodeGetVariableBas4);
        function PVNodeGetVariableVec3() {
          return _PVNodeGetVariableBas4.call(this, PoseGraphType.VEC3) || this;
        }
        var _proto5 = PVNodeGetVariableVec3.prototype;
        _proto5.selfEvaluateDefaultOutput = function selfEvaluateDefaultOutput() {
          var _this$_varInstance4;
          return (_this$_varInstance4 = this._varInstance) === null || _this$_varInstance4 === void 0 ? void 0 : _this$_varInstance4.value;
        };
        return PVNodeGetVariableVec3;
      }(PVNodeGetVariableBase)) || _class7$3) || _class7$3) || _class7$3);
      var PVNodeGetVariableQuat = (_dec15$2 = ccclass$n(CLASS_NAME_PREFIX_ANIM + "PVNodeGetVariableQuat"), _dec16$2 = poseGraphNodeHide(), _dec17$2 = poseGraphNodeAppearance({
        inline: true,
        themeColor: '#B169C4'
      }), _dec15$2(_class8$3 = _dec16$2(_class8$3 = _dec17$2(_class8$3 = function (_PVNodeGetVariableBas5) {
        _inheritsLoose(PVNodeGetVariableQuat, _PVNodeGetVariableBas5);
        function PVNodeGetVariableQuat() {
          return _PVNodeGetVariableBas5.call(this, PoseGraphType.QUAT) || this;
        }
        var _proto6 = PVNodeGetVariableQuat.prototype;
        _proto6.selfEvaluateDefaultOutput = function selfEvaluateDefaultOutput() {
          var _this$_varInstance5;
          return (_this$_varInstance5 = this._varInstance) === null || _this$_varInstance5 === void 0 ? void 0 : _this$_varInstance5.value;
        };
        return PVNodeGetVariableQuat;
      }(PVNodeGetVariableBase)) || _class8$3) || _class8$3) || _class8$3);

      var MAX_ANIMATION_LAYER = 32;

      var RuntimeMotionSyncManager = function () {
        function RuntimeMotionSyncManager() {
          this._groups = [];
        }
        var _proto = RuntimeMotionSyncManager.prototype;
        _proto.register = function register(syncInfo) {
          var groupName = syncInfo.group;
          var group = this._groups.find(function (group) {
            return group.name === groupName;
          });
          if (!group) {
            group = new Group(groupName);
            this._groups.push(group);
          }
          return group.addMember();
        };
        _proto.sync = function sync() {
          for (var _iterator = _createForOfIteratorHelperLoose(this._groups), _step; !(_step = _iterator()).done;) {
            var group = _step.value;
            group.sync();
          }
        };
        return RuntimeMotionSyncManager;
      }();
      var Group = function () {
        function Group(name) {
          this._lastLeader = undefined;
          this._records = [];
          this.name = name;
        }
        var _proto2 = Group.prototype;
        _proto2.addMember = function addMember() {
          var record = new RuntimeMotionSyncRecordImpl();
          this._records.push(record);
          return record;
        };
        _proto2.sync = function sync() {
          var records = this._records;
          var nRecords = records.length;
          assertIsTrue(nRecords > 0);
          var lastLeader = this._lastLeader;
          this._lastLeader = undefined;
          if (records.every(function (r) {
            return !r.active;
          })) {
            return;
          }
          records.sort(function (a, b) {
            var kA = a.active ? a.weight : -1.0;
            var kB = b.active ? b.weight : -1.0;
            return kB - kA;
          });
          {
            var firstInactiveRecord = records.findIndex(function (r) {
              return !r.active;
            });
            assertIsTrue((firstInactiveRecord < 0 ? [] : records.slice(firstInactiveRecord)).every(function (r) {
              return !r.active;
            }));
          }
          var leaderIndex = 0;
          var leaderWeight = records[0].weight;
          if (records[leaderIndex] !== lastLeader) {
            for (var iRecord = 0; iRecord < nRecords; ++iRecord) {
              var record = records[iRecord];
              if (!record.active || !approx(record.weight, leaderWeight, 1e-6)) {
                break;
              }
              if (record === lastLeader) {
                leaderIndex = iRecord;
                break;
              }
            }
          }
          assertIsTrue(records[leaderIndex].active);
          this._lastLeader = records[leaderIndex];
          var leaderNormalizedTime = records[leaderIndex].normalizedTime;
          for (var _iRecord = 0; _iRecord < nRecords; ++_iRecord) {
            var _record = records[_iRecord];
            if (!_record.active) {
              break;
            }
            _record.normalizedTime = leaderNormalizedTime;
            _record.reset();
          }
        };
        return Group;
      }();
      var RuntimeMotionSyncRecordImpl = function () {
        function RuntimeMotionSyncRecordImpl() {
          this.normalizedTime = 0.0;
          this.weight = 0.0;
          this.active = false;
        }
        var _proto3 = RuntimeMotionSyncRecordImpl.prototype;
        _proto3.notifyRenter = function notifyRenter(normalizedTime) {
          this.reset();
          this.normalizedTime = normalizedTime;
        };
        _proto3.notifyUpdate = function notifyUpdate(normalizedDeltaTime, weight) {
          this.normalizedTime += normalizedDeltaTime;
          if (this.active) {
            this.weight += weight;
          } else {
            this.active = true;
            this.weight = weight;
          }
        };
        _proto3.reset = function reset() {
          this.active = false;
          this.weight = 0.0;
        };
        _proto3.getSyncedEnterTime = function getSyncedEnterTime() {
          return this.normalizedTime;
        };
        return RuntimeMotionSyncRecordImpl;
      }();

      var StashRecordState;
      (function (StashRecordState) {
        StashRecordState[StashRecordState["UNINITIALIZED"] = 0] = "UNINITIALIZED";
        StashRecordState[StashRecordState["UNSETTLED"] = 1] = "UNSETTLED";
        StashRecordState[StashRecordState["SETTLED"] = 2] = "SETTLED";
        StashRecordState[StashRecordState["UP_TO_DATE"] = 3] = "UP_TO_DATE";
        StashRecordState[StashRecordState["OUTDATED"] = 4] = "OUTDATED";
        StashRecordState[StashRecordState["UPDATING"] = 5] = "UPDATING";
        StashRecordState[StashRecordState["UPDATED"] = 6] = "UPDATED";
        StashRecordState[StashRecordState["EVALUATING"] = 7] = "EVALUATING";
        StashRecordState[StashRecordState["EVALUATED"] = 8] = "EVALUATED";
      })(StashRecordState || (StashRecordState = {}));
      var RuntimeStashRecord = function () {
        function RuntimeStashRecord(_allocator) {
          this._state = StashRecordState.UNINITIALIZED;
          this._instantiatedPoseGraph = undefined;
          this._maxRequestedUpdateTime = 0.0;
          this._evaluationCache = null;
          this._updateContextGenerator = new AnimationGraphUpdateContextGenerator();
          this._allocator = _allocator;
        }
        var _proto = RuntimeStashRecord.prototype;
        _proto.set = function set(stash, context) {
          assertIsTrue(this._state === StashRecordState.UNINITIALIZED, "The stash has already been set.");
          var instantiatedPoseGraph = instantiatePoseGraph(stash.graph, context);
          instantiatedPoseGraph.bind(context);
          this._instantiatedPoseGraph = instantiatedPoseGraph;
          this._state = StashRecordState.UNSETTLED;
        };
        _proto.settle = function settle(context) {
          assertIsTrue(this._state === StashRecordState.UNSETTLED || this._state === StashRecordState.SETTLED);
          assertIsTrue(this._instantiatedPoseGraph);
          this._instantiatedPoseGraph.settle(context);
          this._state = StashRecordState.SETTLED;
        };
        _proto.reset = function reset() {
          switch (this._state) {
            case StashRecordState.SETTLED:
            case StashRecordState.OUTDATED:
              break;
            case StashRecordState.UP_TO_DATE:
              this._state = StashRecordState.OUTDATED;
              break;
            case StashRecordState.UPDATED:
            case StashRecordState.EVALUATED:
              if (this._evaluationCache) {
                this._allocator.destroyPose(this._evaluationCache);
                this._evaluationCache = null;
              }
              this._maxRequestedUpdateTime = 0.0;
              this._state = StashRecordState.UP_TO_DATE;
              break;
            case StashRecordState.UNINITIALIZED:
            default:
              assertIsTrue(false, "Unexpected stash state");
          }
        };
        _proto.reenter = function reenter() {
          switch (this._state) {
            default:
              assertIsTrue(false, "Unexpected stash state " + this._state + " when reenter().");
              break;
            case StashRecordState.UP_TO_DATE:
            case StashRecordState.UPDATED:
              break;
            case StashRecordState.SETTLED:
            case StashRecordState.OUTDATED:
              {
                this._state = StashRecordState.UP_TO_DATE;
                assertIsTrue(this._instantiatedPoseGraph);
                this._instantiatedPoseGraph.reenter();
                break;
              }
          }
        };
        _proto.requestUpdate = function requestUpdate(context) {
          var deltaTime = context.deltaTime;
          assertIsTrue(this._state === StashRecordState.OUTDATED || this._state === StashRecordState.UP_TO_DATE || this._state === StashRecordState.UPDATING || this._state === StashRecordState.UPDATED);
          assertIsTrue(this._instantiatedPoseGraph);
          if (this._state === StashRecordState.UPDATING) {
            return;
          }
          var diffDeltaTime = Math.max(0.0, deltaTime - this._maxRequestedUpdateTime);
          if (this._state === StashRecordState.UPDATED) {
            if (approx(diffDeltaTime, 0.0, 1e-8)) {
              return;
            } else {
              {
                error("Arrived here indicates a violent of PR #14990. Please report the BUG.");
                return;
              }
            }
          }
          this._state = StashRecordState.UPDATING;
          this._maxRequestedUpdateTime = Math.max(deltaTime, this._maxRequestedUpdateTime);
          var updateContext = this._updateContextGenerator.generate(diffDeltaTime, context.indicativeWeight);
          this._instantiatedPoseGraph.update(updateContext);
          this._state = StashRecordState.UPDATED;
        };
        _proto.evaluate = function evaluate(context) {
          switch (this._state) {
            default:
              assertIsTrue(false, "Unexpected stash state " + this._state + " when evaluate().");
              break;
            case StashRecordState.EVALUATING:
              this._state = StashRecordState.EVALUATED;
              break;
            case StashRecordState.EVALUATED:
              break;
            case StashRecordState.UPDATED:
              {
                var _this$_instantiatedPo;
                assertIsTrue(!this._evaluationCache);
                this._state = StashRecordState.EVALUATING;
                var _pose = (_this$_instantiatedPo = this._instantiatedPoseGraph) === null || _this$_instantiatedPo === void 0 ? void 0 : _this$_instantiatedPo.evaluate(context);
                this._state = StashRecordState.EVALUATED;
                if (_pose) {
                  var heapPose = this._allocator.allocatePose();
                  heapPose.transforms.set(_pose.transforms);
                  heapPose.auxiliaryCurves.set(_pose.auxiliaryCurves);
                  this._evaluationCache = heapPose;
                  context.popPose();
                }
                this._state = StashRecordState.EVALUATED;
                break;
              }
          }
          assertIsTrue(this._state === StashRecordState.EVALUATED);
          assertIsTrue(this._instantiatedPoseGraph);
          return this._evaluationCache ? context.pushDuplicatedPose(this._evaluationCache) : null;
        };
        return RuntimeStashRecord;
      }();
      var RuntimeStashManager = function () {
        function RuntimeStashManager(allocator) {
          this._allocator = void 0;
          this._stashEvaluations = {};
          this._allocator = allocator;
        }
        var _proto2 = RuntimeStashManager.prototype;
        _proto2.bindStash = function bindStash(id) {
          return this._stashEvaluations[id];
        };
        _proto2.getStash = function getStash(id) {
          return this._stashEvaluations[id];
        };
        _proto2.addStash = function addStash(id) {
          this._stashEvaluations[id] = new RuntimeStashRecord(this._allocator);
        };
        _proto2.setStash = function setStash(id, stash, context) {
          assertIsTrue(id in this._stashEvaluations);
          this._stashEvaluations[id].set(stash, context);
        };
        _proto2.reset = function reset() {
          for (var stashId in this._stashEvaluations) {
            var record = this._stashEvaluations[stashId];
            record.reset();
          }
        };
        _proto2.settle = function settle(context) {
          for (var stashId in this._stashEvaluations) {
            var record = this._stashEvaluations[stashId];
            record.settle(context);
          }
        };
        return RuntimeStashManager;
      }();

      var DefaultTopLevelPoseNode = function (_PoseNode) {
        _inheritsLoose(DefaultTopLevelPoseNode, _PoseNode);
        function DefaultTopLevelPoseNode(graph, bindingContext, poseStashAllocator) {
          var _this;
          _this = _PoseNode.call(this) || this;
          _this._layerRecords = void 0;
          var layerEvaluationRecords = graph.layers.map(function (layer) {
            var record = new LayerEvaluationRecord(layer, bindingContext, poseStashAllocator);
            return record;
          });
          _this._layerRecords = layerEvaluationRecords;
          return _this;
        }
        var _proto = DefaultTopLevelPoseNode.prototype;
        _proto.reenter = function reenter() {};
        _proto.bind = function bind(_context) {};
        _proto.settle = function settle(context) {
          var layerRecords = this._layerRecords;
          var nLayers = layerRecords.length;
          for (var iLayer = 0; iLayer < nLayers; ++iLayer) {
            layerRecords[iLayer].settle(context);
          }
        };
        _proto.getLayerWeight = function getLayerWeight(layerIndex) {
          assertIsTrue(layerIndex >= 0 && layerIndex < this._layerRecords.length, "Invalid layer index");
          return this._layerRecords[layerIndex].weight;
        };
        _proto.setLayerWeight = function setLayerWeight(layerIndex, weight) {
          assertIsTrue(layerIndex >= 0 && layerIndex < this._layerRecords.length, "Invalid layer index");
          this._layerRecords[layerIndex].weight = weight;
        };
        _proto.getLayerTopLevelStateMachineEvaluation = function getLayerTopLevelStateMachineEvaluation(layerIndex) {
          return this._layerRecords[layerIndex].stateMachineEvaluation;
        };
        _proto.overrideClips = function overrideClips(context) {
          var layerRecords = this._layerRecords;
          var nLayers = layerRecords.length;
          for (var iLayer = 0; iLayer < nLayers; ++iLayer) {
            var layerRecord = layerRecords[iLayer];
            context._pushAdditiveFlag(layerRecord.additive);
            layerRecord.stateMachineEvaluation.overrideClips(context);
            context._popAdditiveFlag();
          }
        };
        _proto.doUpdate = function doUpdate(context) {
          var layerRecords = this._layerRecords;
          var nLayers = layerRecords.length;
          for (var iLayer = 0; iLayer < nLayers; ++iLayer) {
            layerRecords[iLayer].update(context);
          }
        };
        _proto.doEvaluate = function doEvaluate(context) {
          var finalPose = context.pushDefaultedPose();
          var layerRecords = this._layerRecords;
          var nLayers = layerRecords.length;
          for (var iLayer = 0; iLayer < nLayers; ++iLayer) {
            var layer = layerRecords[iLayer];
            var layerPose = layer.stateMachineEvaluation.evaluate(context);
            var layerActualWeight = layer.weight * layer.stateMachineEvaluation.passthroughWeight;
            var transformFilter = layer.transformFilter;
            if (layer.additive) {
              applyDeltaPose(finalPose, layerPose, layerActualWeight, transformFilter);
            } else {
              blendPoseInto(finalPose, layerPose, layerActualWeight, transformFilter);
            }
            context.popPose();
            layer.postEvaluate();
          }
          return finalPose;
        };
        _createClass(DefaultTopLevelPoseNode, [{
          key: "layerCount",
          get: function get() {
            return this._layerRecords.length;
          }
        }]);
        return DefaultTopLevelPoseNode;
      }(PoseNode);
      var LayerEvaluationRecord = function () {
        function LayerEvaluationRecord(layer, bindingContext, poseStashAllocator) {
          var _layer$mask;
          this.additive = false;
          this.weight = 0.0;
          this._topLevelStateMachineEval = void 0;
          this._stashManager = void 0;
          this._motionSyncManager = void 0;
          this._mask = undefined;
          this.transformFilter = undefined;
          var stashManager = new RuntimeStashManager(poseStashAllocator);
          for (var _iterator = _createForOfIteratorHelperLoose(layer.stashes()), _step; !(_step = _iterator()).done;) {
            var _step$value = _step.value,
              stashId = _step$value[0];
              _step$value[1];
            stashManager.addStash(stashId);
          }
          this._stashManager = stashManager;
          var motionSyncManager = new RuntimeMotionSyncManager();
          this._motionSyncManager = motionSyncManager;
          bindingContext._setLayerWideContextProperties(stashManager, motionSyncManager);
          for (var _iterator2 = _createForOfIteratorHelperLoose(layer.stashes()), _step2; !(_step2 = _iterator2()).done;) {
            var _step2$value = _step2.value,
              _stashId = _step2$value[0],
              stash = _step2$value[1];
            stashManager.setStash(_stashId, stash, bindingContext);
          }
          this.weight = layer.weight;
          var additive = this.additive = layer.additive;
          this._mask = (_layer$mask = layer.mask) !== null && _layer$mask !== void 0 ? _layer$mask : undefined;
          bindingContext._pushAdditiveFlag(additive);
          this._topLevelStateMachineEval = new TopLevelStateMachineEvaluation(layer.stateMachine, layer.name, bindingContext);
          bindingContext._popAdditiveFlag();
          bindingContext._unsetLayerWideContextProperties();
        }
        var _proto2 = LayerEvaluationRecord.prototype;
        _proto2.settle = function settle(context) {
          if (this._mask) {
            this.transformFilter = context.createTransformFilter(this._mask);
          }
          this._stashManager.settle(context);
          this._topLevelStateMachineEval.settle(context);
        };
        _proto2.update = function update(context) {
          this.stateMachineEvaluation.update(context);
          this._motionSyncManager.sync();
        };
        _proto2.postEvaluate = function postEvaluate() {
          this._stashManager.reset();
        };
        _createClass(LayerEvaluationRecord, [{
          key: "stateMachineEvaluation",
          get: function get() {
            return this._topLevelStateMachineEval;
          }
        }]);
        return LayerEvaluationRecord;
      }();

      var AnimationGraphEval = function () {
        function AnimationGraphEval(graph, root, controller, clipOverrides) {
          this._currentTransitionCache = {
            duration: 0.0,
            time: 0.0
          };
          this._rootPoseNode = void 0;
          this._varInstances = {};
          this._hasAutoTrigger = false;
          this._auxiliaryCurveRegistry = new AuxiliaryCurveRegistry();
          this._poseLayoutMaintainer = void 0;
          this._bindingContext = void 0;
          this._settleContext = void 0;
          this._rootUpdateContextGenerator = new AnimationGraphUpdateContextGenerator();
          {
            if (graph.layers.length >= MAX_ANIMATION_LAYER) {
              throw new Error("Max layer count exceeds. " + ("Allowed: " + MAX_ANIMATION_LAYER + ", actual: " + graph.layers.length));
            }
          }
          for (var _iterator = _createForOfIteratorHelperLoose(graph.variables), _step; !(_step = _iterator()).done;) {
            var _step$value = _step.value,
              name = _step$value[0],
              variable = _step$value[1];
            var varInstance = variable[createInstanceTag]();
            this._varInstances[name] = varInstance;
            if (varInstance instanceof VarInstanceTrigger) {
              if (varInstance.resetMode === TriggerResetMode.NEXT_FRAME_OR_AFTER_CONSUMED) {
                this._hasAutoTrigger = true;
              }
            }
          }
          var poseLayoutMaintainer = new AnimationGraphPoseLayoutMaintainer(root, this._auxiliaryCurveRegistry);
          this._poseLayoutMaintainer = poseLayoutMaintainer;
          var bindingContext = new AnimationGraphBindingContext(root, poseLayoutMaintainer, this._varInstances, controller);
          bindingContext._setClipOverrides(clipOverrides !== null && clipOverrides !== void 0 ? clipOverrides : undefined);
          this._bindingContext = bindingContext;
          var settleContext = new AnimationGraphSettleContext(poseLayoutMaintainer);
          this._settleContext = settleContext;
          poseLayoutMaintainer.startBind();
          var poseStashAllocator = new DeferredPoseStashAllocator();
          this._poseStashAllocator = poseStashAllocator;
          this._rootPoseNode = new DefaultTopLevelPoseNode(graph, bindingContext, poseStashAllocator);
          this._root = root;
          this._initializeContexts();
        }
        var _proto = AnimationGraphEval.prototype;
        _proto.destroy = function destroy() {
          this._evaluationContext.destroy();
        };
        _proto._destroyAfterException_debugging = function _destroyAfterException_debugging() {
          var stackSize = this._evaluationContext._stackSize_debugging;
          if (stackSize !== 0) {
            for (var i = 0; i < stackSize; ++i) {
              this._evaluationContext.popPose();
            }
          }
          this._evaluationContext.destroy();
        };
        _proto.update = function update(deltaTime) {
          var evaluationContext = this._evaluationContext,
            poseLayoutMaintainer = this._poseLayoutMaintainer,
            rootUpdateContextGenerator = this._rootUpdateContextGenerator,
            rootPoseNode = this._rootPoseNode;
          var updateContext = rootUpdateContextGenerator.generate(deltaTime, 1.0);
          rootPoseNode.update(updateContext);
          var finalPose = rootPoseNode.evaluate(evaluationContext, PoseTransformSpaceRequirement.LOCAL);
          if (this._hasAutoTrigger) {
            var varInstances = this._varInstances;
            for (var varName in varInstances) {
              var varInstance = varInstances[varName];
              if (varInstance instanceof VarInstanceTrigger && varInstance.resetMode === TriggerResetMode.NEXT_FRAME_OR_AFTER_CONSUMED) {
                varInstance.value = false;
              }
            }
          }
          poseLayoutMaintainer.apply(finalPose);
          evaluationContext.popPose();
          {
            assertIsTrue(evaluationContext.allocatedPoseCount === 0, "Pose leaked.");
            assertIsTrue(this._poseStashAllocator.allocatedPoseCount === 0, "Pose leaked.");
          }
        };
        _proto.getVariables = function getVariables() {
          return Object.entries(this._varInstances);
        };
        _proto.getCurrentStateStatus = function getCurrentStateStatus(layer) {
          return this._rootPoseNode.getLayerTopLevelStateMachineEvaluation(layer).getCurrentStateStatus();
        };
        _proto.getCurrentClipStatuses = function getCurrentClipStatuses(layer) {
          return this._rootPoseNode.getLayerTopLevelStateMachineEvaluation(layer).getCurrentClipStatuses();
        };
        _proto.getCurrentTransition = function getCurrentTransition(layer) {
          var currentTransition = this._currentTransitionCache;
          var isInTransition = this._rootPoseNode.getLayerTopLevelStateMachineEvaluation(layer).getCurrentTransition(currentTransition);
          return isInTransition ? currentTransition : null;
        };
        _proto.getNextStateStatus = function getNextStateStatus(layer) {
          return this._rootPoseNode.getLayerTopLevelStateMachineEvaluation(layer).getNextStateStatus();
        };
        _proto.getNextClipStatuses = function getNextClipStatuses(layer) {
          return this._rootPoseNode.getLayerTopLevelStateMachineEvaluation(layer).getNextClipStatuses();
        };
        _proto.getValue = function getValue(name) {
          var varInstance = this._varInstances[name];
          if (!varInstance) {
            return undefined;
          } else {
            return varInstance.value;
          }
        };
        _proto.setValue = function setValue(name, value) {
          var varInstance = this._varInstances[name];
          if (!varInstance) {
            return;
          }
          varInstance.value = value;
        };
        _proto.getLayerWeight = function getLayerWeight(layerIndex) {
          return this._rootPoseNode.getLayerWeight(layerIndex);
        };
        _proto.setLayerWeight = function setLayerWeight(layerIndex, weight) {
          this._rootPoseNode.setLayerWeight(layerIndex, weight);
        };
        _proto.overrideClips = function overrideClips(overrides) {
          var poseLayoutMaintainer = this._poseLayoutMaintainer;
          poseLayoutMaintainer.startBind();
          this._bindingContext._setClipOverrides(overrides);
          this._rootPoseNode.overrideClips(this._bindingContext);
          this._updateAfterPossiblePoseLayoutChange();
        };
        _proto.getAuxiliaryCurveValue = function getAuxiliaryCurveValue(curveName) {
          return this._auxiliaryCurveRegistry.get(curveName);
        };
        _proto._initializeContexts = function _initializeContexts() {
          var poseLayoutMaintainer = this._poseLayoutMaintainer;
          void poseLayoutMaintainer.endBind();
          this._createOrUpdateTransformFilters();
          var evaluationContext = poseLayoutMaintainer.createEvaluationContext();
          this._evaluationContext = evaluationContext;
          poseLayoutMaintainer.fetchDefaultTransforms(evaluationContext[defaultTransformsTag]);
          poseLayoutMaintainer.resetPoseStashAllocator(this._poseStashAllocator);
        };
        _proto._updateAfterPossiblePoseLayoutChange = function _updateAfterPossiblePoseLayoutChange() {
          var poseLayoutMaintainer = this._poseLayoutMaintainer;
          var layoutChangeFlags = poseLayoutMaintainer.endBind();
          if (layoutChangeFlags === 0) {
            return;
          }
          if (layoutChangeFlags & LayoutChangeFlag.TRANSFORM_COUNT || layoutChangeFlags & LayoutChangeFlag.TRANSFORM_ORDER) {
            this._createOrUpdateTransformFilters();
          }
          var evaluationContextRecreated = false;
          if (layoutChangeFlags & LayoutChangeFlag.TRANSFORM_COUNT || layoutChangeFlags & LayoutChangeFlag.AUXILIARY_CURVE_COUNT) {
            var evaluationContext = poseLayoutMaintainer.createEvaluationContext();
            this._evaluationContext.destroy();
            this._evaluationContext = evaluationContext;
            evaluationContextRecreated = true;
            poseLayoutMaintainer.resetPoseStashAllocator(this._poseStashAllocator);
          }
          if (evaluationContextRecreated || layoutChangeFlags & LayoutChangeFlag.TRANSFORM_COUNT || layoutChangeFlags & LayoutChangeFlag.TRANSFORM_ORDER) {
            poseLayoutMaintainer.fetchDefaultTransforms(this._evaluationContext[defaultTransformsTag]);
          }
        };
        _proto._createOrUpdateTransformFilters = function _createOrUpdateTransformFilters() {
          this._rootPoseNode.settle(this._settleContext);
        };
        _createClass(AnimationGraphEval, [{
          key: "layerCount",
          get: function get() {
            return this._rootPoseNode.layerCount;
          }
        }]);
        return AnimationGraphEval;
      }();

      var _dec$J, _dec2$F, _dec3$u, _class$J, _class2$I, _initializer$F;
      var ccclass = ccclass$n,
        type = type$7,
        serializable = serializable$j,
        formerlySerializedAs = formerlySerializedAs$4;
      var AnimationController = (_dec$J = ccclass('cc.animation.AnimationController'), _dec2$F = type(AnimationGraphLike), _dec3$u = formerlySerializedAs('graph'), _dec$J(_class$J = (_class2$I = function (_Component) {
        _inheritsLoose(AnimationController, _Component);
        function AnimationController() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Component.call.apply(_Component, [this].concat(args)) || this;
          _this._graph = _initializer$F && _initializer$F();
          _this._graphEval = null;
          return _this;
        }
        var _proto = AnimationController.prototype;
        _proto.__preload = function __preload() {
          var graph = this.graph;
          if (graph) {
            var originalGraph;
            var clipOverrides = null;
            if (graph instanceof AnimationGraphVariant) {
              if (!graph.original) {
                return;
              }
              originalGraph = graph.original;
              clipOverrides = graph.clipOverrides;
            } else {
              assertIsTrue(graph instanceof AnimationGraph);
              originalGraph = graph;
            }
            var graphEval = new AnimationGraphEval(originalGraph, this.node, this, clipOverrides);
            this._graphEval = graphEval;
          }
        };
        _proto.onDestroy = function onDestroy() {
          var _this$_graphEval;
          (_this$_graphEval = this._graphEval) === null || _this$_graphEval === void 0 ? void 0 : _this$_graphEval.destroy();
        };
        _proto.update = function update(deltaTime) {
          var _this$_graphEval2;
          (_this$_graphEval2 = this._graphEval) === null || _this$_graphEval2 === void 0 ? void 0 : _this$_graphEval2.update(deltaTime);
        };
        _proto.getVariables = function getVariables() {
          var graphEval = this._graphEval;
          assertIsNonNullable(graphEval);
          return graphEval.getVariables();
        };
        _proto.setValue = function setValue(name, value) {
          return this.setValue_experimental(name, value);
        };
        _proto.setValue_experimental = function setValue_experimental(name, value) {
          var graphEval = this._graphEval;
          assertIsNonNullable(graphEval);
          graphEval.setValue(name, value);
        };
        _proto.getValue = function getValue(name) {
          var value = this.getValue_experimental(name);
          if (typeof value === 'object') {
            {
              warn("Obtaining variable \"" + name + "\" is not of primitive type, " + "which is currently supported experimentally and should be explicitly obtained through this.getValue_experimental()");
            }
            return undefined;
          } else {
            return value;
          }
        };
        _proto.getValue_experimental = function getValue_experimental(name) {
          var graphEval = this._graphEval;
          assertIsNonNullable(graphEval);
          return graphEval.getValue(name);
        };
        _proto.getCurrentStateStatus = function getCurrentStateStatus(layer) {
          var graphEval = this._graphEval;
          assertIsNonNullable(graphEval);
          return graphEval.getCurrentStateStatus(layer);
        };
        _proto.getCurrentClipStatuses = function getCurrentClipStatuses(layer) {
          var graphEval = this._graphEval;
          assertIsNonNullable(graphEval);
          return graphEval.getCurrentClipStatuses(layer);
        };
        _proto.getCurrentTransition = function getCurrentTransition(layer) {
          var graphEval = this._graphEval;
          assertIsNonNullable(graphEval);
          return graphEval.getCurrentTransition(layer);
        };
        _proto.getNextStateStatus = function getNextStateStatus(layer) {
          var graphEval = this._graphEval;
          assertIsNonNullable(graphEval);
          return graphEval.getNextStateStatus(layer);
        };
        _proto.getNextClipStatuses = function getNextClipStatuses(layer) {
          var graphEval = this._graphEval;
          assertIsNonNullable(graphEval);
          return graphEval.getNextClipStatuses(layer);
        };
        _proto.getLayerWeight = function getLayerWeight(layer) {
          var graphEval = this._graphEval;
          assertIsNonNullable(graphEval);
          return graphEval.getLayerWeight(layer);
        };
        _proto.setLayerWeight = function setLayerWeight(layer, weight) {
          var graphEval = this._graphEval;
          assertIsNonNullable(graphEval);
          return graphEval.setLayerWeight(layer, weight);
        };
        _proto.overrideClips_experimental = function overrideClips_experimental(overrides) {
          var graphEval = this._graphEval;
          assertIsNonNullable(graphEval);
          graphEval.overrideClips(overrides);
        };
        _proto.getAuxiliaryCurveValue_experimental = function getAuxiliaryCurveValue_experimental(curveName) {
          var graphEval = this._graphEval;
          if (!graphEval) {
            return 0.0;
          }
          return graphEval.getAuxiliaryCurveValue(curveName);
        };
        _createClass(AnimationController, [{
          key: "graph",
          get: function get() {
            return this._graph;
          },
          set: function set(value) {
            this._graph = value;
          }
        }, {
          key: "layerCount",
          get: function get() {
            var _this$_graphEval$laye, _this$_graphEval3;
            return (_this$_graphEval$laye = (_this$_graphEval3 = this._graphEval) === null || _this$_graphEval3 === void 0 ? void 0 : _this$_graphEval3.layerCount) !== null && _this$_graphEval$laye !== void 0 ? _this$_graphEval$laye : 0;
          }
        }]);
        return AnimationController;
      }(Component), (_applyDecoratedDescriptor(_class2$I.prototype, "graph", [_dec2$F], Object.getOwnPropertyDescriptor(_class2$I.prototype, "graph"), _class2$I.prototype), _initializer$F = applyDecoratedInitializer(_class2$I.prototype, "_graph", [serializable, _dec3$u], function () {
        return null;
      })), _class2$I)) || _class$J);

      var animation = /*#__PURE__*/Object.freeze({
        __proto__: null,
        UniformProxyFactory: UniformProxyFactory,
        MorphWeightValueProxy: MorphWeightValueProxy,
        MorphWeightsValueProxy: MorphWeightsValueProxy,
        MorphWeightsAllValueProxy: MorphWeightsAllValueProxy,
        Track: Track,
        TrackPath: TrackPath,
        RealTrack: RealTrack,
        VectorTrack: VectorTrack,
        QuatTrack: QuatTrack,
        ColorTrack: ColorTrack,
        SizeTrack: SizeTrack,
        ObjectTrack: ObjectTrack,
        isPropertyPath: isPropertyPath,
        isCustomPath: isCustomPath,
        HierarchyPath: HierarchyPath,
        ComponentPath: ComponentPath,
        CubicSplineVec2Value: CubicSplineVec2Value,
        CubicSplineVec3Value: CubicSplineVec3Value,
        CubicSplineVec4Value: CubicSplineVec4Value,
        CubicSplineQuatValue: CubicSplineQuatValue,
        CubicSplineNumberValue: CubicSplineNumberValue,
        AnimationController: AnimationController,
        get VariableType () { return VariableType; },
        StateMachineComponent: StateMachineComponent
      });
      exports('ai', animation);

      var BlendStateBuffer = function () {
        function BlendStateBuffer() {
          this._nodeBlendStates = new Map();
        }
        var _proto = BlendStateBuffer.prototype;
        _proto.createWriter = function createWriter(node, property, host, constants) {
          var propertyBlendState = this.ref(node, property);
          return new BlendStateWriterInternal(node, property, propertyBlendState, host, constants);
        };
        _proto.destroyWriter = function destroyWriter(writer) {
          var internal = writer;
          this.deRef(internal.node, internal.property);
        };
        _proto.ref = function ref(node, property) {
          var nodeBlendState = this._nodeBlendStates.get(node);
          if (!nodeBlendState) {
            nodeBlendState = this.createNodeBlendState();
            this._nodeBlendStates.set(node, nodeBlendState);
          }
          var propertyBlendState = nodeBlendState.refProperty(node, property);
          return propertyBlendState;
        };
        _proto.deRef = function deRef(node, property) {
          var nodeBlendState = this._nodeBlendStates.get(node);
          if (!nodeBlendState) {
            return;
          }
          nodeBlendState.deRefProperty(property);
          if (nodeBlendState.empty) {
            this._nodeBlendStates["delete"](node);
          }
        };
        _proto.apply = function apply() {
          this._nodeBlendStates.forEach(function (nodeBlendState, node) {
            nodeBlendState.apply(node);
          });
        };
        return BlendStateBuffer;
      }();
      var BlendStateWriterInternal = function () {
        function BlendStateWriterInternal(_node, _property, _propertyBlendState, _host, _constants) {
          this._node = _node;
          this._property = _property;
          this._propertyBlendState = _propertyBlendState;
          this._host = _host;
          this._constants = _constants;
        }
        var _proto2 = BlendStateWriterInternal.prototype;
        _proto2.getValue = function getValue() {
          return this._node[this._property];
        };
        _proto2.setValue = function setValue(value) {
          var propertyBlendState = this._propertyBlendState,
            host = this._host;
          var weight = host.weight;
          propertyBlendState.blend(value, weight);
        };
        _createClass(BlendStateWriterInternal, [{
          key: "node",
          get: function get() {
            return this._node;
          }
        }, {
          key: "property",
          get: function get() {
            return this._property;
          }
        }]);
        return BlendStateWriterInternal;
      }();
      var TransformApplyFlag;
      (function (TransformApplyFlag) {
        TransformApplyFlag[TransformApplyFlag["POSITION"] = 1] = "POSITION";
        TransformApplyFlag[TransformApplyFlag["ROTATION"] = 2] = "ROTATION";
        TransformApplyFlag[TransformApplyFlag["SCALE"] = 4] = "SCALE";
        TransformApplyFlag[TransformApplyFlag["EULER_ANGLES"] = 8] = "EULER_ANGLES";
      })(TransformApplyFlag || (TransformApplyFlag = {}));
      TransformApplyFlag.POSITION | TransformApplyFlag.ROTATION | TransformApplyFlag.SCALE | TransformApplyFlag.EULER_ANGLES;
      var LegacyVec3PropertyBlendState = function () {
        function LegacyVec3PropertyBlendState() {
          this.refCount = 0;
          this.accumulatedWeight = 0.0;
          this.result = new Vec3();
        }
        var _proto3 = LegacyVec3PropertyBlendState.prototype;
        _proto3.blend = function blend(value, weight) {
          this.accumulatedWeight = mixAveragedVec3(this.result, this.result, this.accumulatedWeight, value, weight);
        };
        _proto3.reset = function reset() {
          this.accumulatedWeight = 0.0;
          Vec3.zero(this.result);
        };
        return LegacyVec3PropertyBlendState;
      }();
      var LegacyQuatPropertyBlendState = function () {
        function LegacyQuatPropertyBlendState() {
          this.refCount = 0;
          this.accumulatedWeight = 0.0;
          this.result = new Quat();
        }
        var _proto4 = LegacyQuatPropertyBlendState.prototype;
        _proto4.blend = function blend(value, weight) {
          this.accumulatedWeight = mixAveragedQuat(this.result, this.result, this.accumulatedWeight, value, weight);
        };
        _proto4.reset = function reset() {
          this.accumulatedWeight = 0.0;
          Quat.identity(this.result);
        };
        return LegacyQuatPropertyBlendState;
      }();
      var NodeBlendState = function () {
        function NodeBlendState() {
          this._transformApplyFlags = 0;
          this._properties = {};
        }
        var _proto5 = NodeBlendState.prototype;
        _proto5.refProperty = function refProperty(node, property) {
          var _properties$property, _properties$property2;
          var properties = this._properties;
          var propertyBlendState;
          switch (property) {
            default:
            case 'position':
            case 'scale':
            case 'eulerAngles':
              propertyBlendState = (_properties$property = properties[property]) !== null && _properties$property !== void 0 ? _properties$property : properties[property] = this._createVec3BlendState(node[property]);
              break;
            case 'rotation':
              propertyBlendState = (_properties$property2 = properties[property]) !== null && _properties$property2 !== void 0 ? _properties$property2 : properties[property] = this._createQuatBlendState(node.rotation);
              break;
          }
          ++propertyBlendState.refCount;
          return propertyBlendState;
        };
        _proto5.deRefProperty = function deRefProperty(property) {
          var properties = this._properties;
          var propertyBlendState = properties[property];
          if (!propertyBlendState) {
            return;
          }
          --propertyBlendState.refCount;
          if (propertyBlendState.refCount > 0) {
            return;
          }
          delete properties[property];
        };
        _proto5.apply = function apply(node) {
          var transformApplyFlags = this._transformApplyFlags,
            _this$_properties = this._properties,
            position = _this$_properties.position,
            scale = _this$_properties.scale,
            rotation = _this$_properties.rotation,
            eulerAngles = _this$_properties.eulerAngles;
          if (!transformApplyFlags) {
            return;
          }
          var t;
          var s;
          var r;
          if (position && transformApplyFlags & TransformApplyFlag.POSITION) {
            t = position.result;
          }
          if (scale && transformApplyFlags & TransformApplyFlag.SCALE) {
            s = scale.result;
          }
          if (eulerAngles && transformApplyFlags & TransformApplyFlag.EULER_ANGLES) {
            r = eulerAngles.result;
          }
          if (rotation && transformApplyFlags & TransformApplyFlag.ROTATION) {
            r = rotation.result;
          }
          if (r || t || s) {
            node.setRTS(r, t, s);
          }
          this._transformApplyFlags = 0;
        };
        _createClass(NodeBlendState, [{
          key: "empty",
          get: function get() {
            var properties = this._properties;
            return !properties.position && !properties.rotation && !properties.eulerAngles && !properties.scale;
          }
        }]);
        return NodeBlendState;
      }();
      var LegacyNodeBlendState = function (_NodeBlendState) {
        _inheritsLoose(LegacyNodeBlendState, _NodeBlendState);
        function LegacyNodeBlendState() {
          return _NodeBlendState.apply(this, arguments) || this;
        }
        var _proto6 = LegacyNodeBlendState.prototype;
        _proto6.apply = function apply(node) {
          var _this$_properties2 = this._properties,
            position = _this$_properties2.position,
            scale = _this$_properties2.scale,
            rotation = _this$_properties2.rotation,
            eulerAngles = _this$_properties2.eulerAngles;
          if (position && position.accumulatedWeight) {
            this._transformApplyFlags |= TransformApplyFlag.POSITION;
            if (position.accumulatedWeight < 1.0) {
              position.blend(node.position, 1.0 - position.accumulatedWeight);
            }
          }
          if (scale && scale.accumulatedWeight) {
            this._transformApplyFlags |= TransformApplyFlag.SCALE;
            if (scale.accumulatedWeight < 1.0) {
              scale.blend(node.scale, 1.0 - scale.accumulatedWeight);
            }
          }
          if (eulerAngles && eulerAngles.accumulatedWeight) {
            this._transformApplyFlags |= TransformApplyFlag.EULER_ANGLES;
            if (eulerAngles.accumulatedWeight < 1.0) {
              eulerAngles.blend(node.eulerAngles, 1.0 - eulerAngles.accumulatedWeight);
            }
          }
          if (rotation && rotation.accumulatedWeight) {
            this._transformApplyFlags |= TransformApplyFlag.ROTATION;
            if (rotation.accumulatedWeight < 1.0) {
              rotation.blend(node.rotation, 1.0 - rotation.accumulatedWeight);
            }
          }
          _NodeBlendState.prototype.apply.call(this, node);
          position === null || position === void 0 ? void 0 : position.reset();
          scale === null || scale === void 0 ? void 0 : scale.reset();
          rotation === null || rotation === void 0 ? void 0 : rotation.reset();
          eulerAngles === null || eulerAngles === void 0 ? void 0 : eulerAngles.reset();
        };
        _proto6._createVec3BlendState = function _createVec3BlendState(_currentValue) {
          return new LegacyVec3PropertyBlendState();
        };
        _proto6._createQuatBlendState = function _createQuatBlendState(_currentValue) {
          return new LegacyQuatPropertyBlendState();
        };
        return LegacyNodeBlendState;
      }(NodeBlendState);
      var LegacyBlendStateBuffer = function (_BlendStateBuffer) {
        _inheritsLoose(LegacyBlendStateBuffer, _BlendStateBuffer);
        function LegacyBlendStateBuffer() {
          return _BlendStateBuffer.apply(this, arguments) || this;
        }
        var _proto7 = LegacyBlendStateBuffer.prototype;
        _proto7.createNodeBlendState = function createNodeBlendState() {
          return new LegacyNodeBlendState();
        };
        return LegacyBlendStateBuffer;
      }(BlendStateBuffer);
      function mixAveragedVec3(result, previous, accumulatedWeight, input, weight) {
        var newSum = accumulatedWeight + weight;
        if (weight === 1.0 && !accumulatedWeight) {
          Vec3.copy(result, input);
        } else if (newSum) {
          var t = weight / newSum;
          Vec3.lerp(result, result, input, t);
        }
        return newSum;
      }
      function mixAveragedQuat(result, previous, accumulatedWeight, input, weight) {
        var newSum = accumulatedWeight + weight;
        if (weight === 1.0 && !accumulatedWeight) {
          Quat.copy(result, input);
        } else if (newSum) {
          var t = weight / newSum;
          Quat.slerp(result, previous, input, t);
        }
        return newSum;
      }

      var _class$I, _class2$H;
      var AnimationManager = exports('ar', ccclass$n(_class$I = (_class2$H = function (_System) {
        _inheritsLoose(AnimationManager, _System);
        function AnimationManager() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _System.call.apply(_System, [this].concat(args)) || this;
          _this._anims = new MutableForwardIterator([]);
          _this._crossFades = new MutableForwardIterator([]);
          _this._delayEvents = [];
          _this._blendStateBuffer = new LegacyBlendStateBuffer();
          _this._sockets = [];
          return _this;
        }
        var _proto = AnimationManager.prototype;
        _proto.addCrossFade = function addCrossFade(crossFade) {
          var index = this._crossFades.array.indexOf(crossFade);
          if (index === -1) {
            this._crossFades.push(crossFade);
          }
        };
        _proto.removeCrossFade = function removeCrossFade(crossFade) {
          var index = this._crossFades.array.indexOf(crossFade);
          if (index >= 0) {
            this._crossFades.fastRemoveAt(index);
          } else {
            errorID(3907);
          }
        };
        _proto.update = function update(dt) {
          var _delayEvents = this._delayEvents,
            crossFadesIter = this._crossFades,
            _sockets = this._sockets;
          {
            var crossFades = crossFadesIter.array;
            for (crossFadesIter.i = 0; crossFadesIter.i < crossFades.length; ++crossFadesIter.i) {
              var crossFade = crossFades[crossFadesIter.i];
              crossFade.update(dt);
            }
          }
          var iterator = this._anims;
          var array = iterator.array;
          for (iterator.i = 0; iterator.i < array.length; ++iterator.i) {
            var anim = array[iterator.i];
            if (!anim.isMotionless) {
              anim.update(dt);
            }
          }
          this._blendStateBuffer.apply();
          var stamp = director.getTotalFrames();
          for (var i = 0, l = _sockets.length; i < l; i++) {
            var _sockets$i = _sockets[i],
              target = _sockets$i.target,
              transform = _sockets$i.transform;
            target.matrix = getWorldMatrix(transform, stamp);
          }
          for (var _i = 0, _l = _delayEvents.length; _i < _l; _i++) {
            var event = _delayEvents[_i];
            event.fn.apply(event.thisArg, event.args);
          }
          _delayEvents.length = 0;
        };
        _proto.destruct = function destruct() {};
        _proto.addAnimation = function addAnimation(anim) {
          var index = this._anims.array.indexOf(anim);
          if (index === -1) {
            this._anims.push(anim);
          }
        };
        _proto.removeAnimation = function removeAnimation(anim) {
          var index = this._anims.array.indexOf(anim);
          if (index >= 0) {
            this._anims.fastRemoveAt(index);
          } else {
            errorID(3907);
          }
        };
        _proto.pushDelayEvent = function pushDelayEvent(fn, thisArg, args) {
          this._delayEvents.push({
            fn: fn,
            thisArg: thisArg,
            args: args
          });
        };
        _proto.addSockets = function addSockets(root, sockets) {
          var _this2 = this;
          var _loop = function _loop() {
            var socket = sockets[i];
            if (_this2._sockets.find(function (s) {
              return s.target === socket.target;
            })) {
              return 1;
            }
            var targetNode = root.getChildByPath(socket.path);
            var transform = socket.target && targetNode && getTransform(targetNode, root);
            if (transform) {
              _this2._sockets.push({
                target: socket.target,
                transform: transform
              });
            }
          };
          for (var i = 0; i < sockets.length; ++i) {
            if (_loop()) continue;
          }
        };
        _proto.removeSockets = function removeSockets(root, sockets) {
          for (var i = 0; i < sockets.length; ++i) {
            var socketToRemove = sockets[i];
            for (var j = 0; j < this._sockets.length; ++j) {
              var socket = this._sockets[j];
              if (socket.target === socketToRemove.target) {
                deleteTransform(socket.transform.node);
                this._sockets[j] = this._sockets[this._sockets.length - 1];
                this._sockets.length--;
                break;
              }
            }
          }
        };
        _createClass(AnimationManager, [{
          key: "blendState",
          get: function get() {
            return this._blendStateBuffer;
          }
        }]);
        return AnimationManager;
      }(System), _class2$H.ID = 'animation', _class2$H)) || _class$I);
      director.on(Director.EVENT_INIT, function () {
        var animationManager = new AnimationManager();
        director.registerSystem(AnimationManager.ID, animationManager, System.Priority.HIGH);
      });
      legacyCC.AnimationManager = AnimationManager;

      var CrossFade = function (_Playable) {
        _inheritsLoose(CrossFade, _Playable);
        function CrossFade(scheduler) {
          var _this;
          _this = _Playable.call(this) || this;
          _this._managedStates = [];
          _this._fadings = [];
          _this._scheduled = false;
          _this._scheduler = scheduler !== null && scheduler !== void 0 ? scheduler : getGlobalAnimationManager();
          return _this;
        }
        var _proto = CrossFade.prototype;
        _proto.update = function update(deltaTime) {
          if (this.isMotionless) {
            return;
          }
          var managedStates = this._managedStates;
          var fadings = this._fadings;
          if (managedStates.length === 1 && fadings.length === 1) {
            var state = managedStates[0].state;
            if (state) {
              state.weight = 1.0;
            }
          } else {
            this._calculateWeights(deltaTime);
          }
          if (managedStates.length === 1 && fadings.length === 1) {
            this._unscheduleThis();
          }
        };
        _proto.crossFade = function crossFade(state, duration) {
          var _target$state;
          if (this._managedStates.length === 0) {
            duration = 0;
          }
          if (duration === 0) {
            this.clear();
          }
          var target = this._managedStates.find(function (weightedState) {
            return weightedState.state === state;
          });
          if (!target) {
            target = {
              state: state,
              reference: 0
            };
            if (state) {
              state.play();
            }
            this._managedStates.push(target);
          } else if ((_target$state = target.state) !== null && _target$state !== void 0 && _target$state.isMotionless) {
            target.state.play();
          }
          ++target.reference;
          this._fadings.unshift({
            easeDuration: duration,
            easeTime: 0,
            target: target
          });
          if (!this.isMotionless) {
            this._scheduleThis();
          }
        };
        _proto.clear = function clear() {
          for (var iManagedState = 0; iManagedState < this._managedStates.length; ++iManagedState) {
            var state = this._managedStates[iManagedState].state;
            if (state) {
              state.stop();
            }
          }
          this._managedStates.length = 0;
          this._fadings.length = 0;
        };
        _proto.onPlay = function onPlay() {
          _Playable.prototype.onPlay.call(this);
          this._scheduleThis();
        };
        _proto.onPause = function onPause() {
          _Playable.prototype.onPause.call(this);
          for (var iManagedState = 0; iManagedState < this._managedStates.length; ++iManagedState) {
            var state = this._managedStates[iManagedState].state;
            if (state) {
              state.pause();
            }
          }
          this._unscheduleThis();
        };
        _proto.onResume = function onResume() {
          _Playable.prototype.onResume.call(this);
          for (var iManagedState = 0; iManagedState < this._managedStates.length; ++iManagedState) {
            var state = this._managedStates[iManagedState].state;
            if (state) {
              state.resume();
            }
          }
          this._scheduleThis();
        };
        _proto.onStop = function onStop() {
          _Playable.prototype.onStop.call(this);
          this.clear();
        };
        _proto._calculateWeights = function _calculateWeights(deltaTime) {
          var managedStates = this._managedStates;
          var fadings = this._fadings;
          for (var iManagedState = 0; iManagedState < managedStates.length; ++iManagedState) {
            var state = managedStates[iManagedState].state;
            if (state) {
              state.weight = 0;
            }
          }
          var absoluteWeight = 1.0;
          var deadFadingBegin = fadings.length;
          for (var iFading = 0; iFading < fadings.length; ++iFading) {
            var fading = fadings[iFading];
            fading.easeTime += deltaTime;
            var relativeWeight = fading.easeDuration === 0 ? 1 : clamp01(fading.easeTime / fading.easeDuration);
            var weight = relativeWeight * absoluteWeight;
            absoluteWeight *= 1.0 - relativeWeight;
            if (fading.target.state) {
              fading.target.state.weight += weight;
            }
            if (fading.easeTime >= fading.easeDuration) {
              deadFadingBegin = iFading + 1;
              fading.easeTime = fading.easeDuration;
              break;
            }
          }
          if (deadFadingBegin !== fadings.length) {
            for (var iDeadFading = deadFadingBegin; iDeadFading < fadings.length; ++iDeadFading) {
              var deadFading = fadings[iDeadFading];
              --deadFading.target.reference;
              if (deadFading.target.reference <= 0) {
                if (deadFading.target.state) {
                  deadFading.target.state.stop();
                }
                remove(this._managedStates, deadFading.target);
              }
            }
            fadings.splice(deadFadingBegin);
          }
        };
        _proto._scheduleThis = function _scheduleThis() {
          if (!this._scheduled) {
            this._scheduler.addCrossFade(this);
            this._scheduled = true;
          }
        };
        _proto._unscheduleThis = function _unscheduleThis() {
          if (this._scheduled) {
            this._scheduler.removeCrossFade(this);
            this._scheduled = false;
          }
        };
        return CrossFade;
      }(Playable);

      var _dec$I, _dec2$E, _dec3$t, _dec4$n, _dec5$l, _class$H, _class2$G, _initializer$E, _initializer2$A, _initializer3$q, _class3$l;
      var Animation = exports('al', (_dec$I = ccclass$n('cc.Animation'), _dec2$E = executionOrder$1(99), _dec3$t = type$7([AnimationClip]), _dec4$n = type$7(AnimationClip), _dec5$l = type$7([AnimationClip]), _dec$I(_class$H = _dec2$E(_class$H = (_class2$G = (_class3$l = function (_Eventify) {
        _inheritsLoose(Animation, _Eventify);
        function Animation() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Eventify.call.apply(_Eventify, [this].concat(args)) || this;
          _this.playOnLoad = _initializer$E && _initializer$E();
          _this._crossFade = new CrossFade();
          _this._nameToState = createMap(true);
          _this._clips = _initializer2$A && _initializer2$A();
          _this._defaultClip = _initializer3$q && _initializer3$q();
          _this._hasBeenPlayed = false;
          return _this;
        }
        var _proto = Animation.prototype;
        _proto.onLoad = function onLoad() {
          this.clips = this._clips;
          for (var stateName in this._nameToState) {
            var state = this._nameToState[stateName];
            state.initialize(this.node);
          }
        };
        _proto.start = function start() {
          if (this.playOnLoad && !this._hasBeenPlayed && this._defaultClip) {
            this.crossFade(this._defaultClip.name, 0);
          }
        };
        _proto.onEnable = function onEnable() {
          this._crossFade.resume();
        };
        _proto.onDisable = function onDisable() {
          this._crossFade.pause();
        };
        _proto.onDestroy = function onDestroy() {
          this._crossFade.stop();
          for (var name in this._nameToState) {
            var state = this._nameToState[name];
            state.destroy();
          }
          this._nameToState = createMap(true);
        };
        _proto.play = function play(name) {
          this._hasBeenPlayed = true;
          if (!name) {
            if (!this._defaultClip) {
              return;
            }
            name = this._defaultClip.name;
          }
          this.crossFade(name, 0);
        };
        _proto.crossFade = function crossFade(name, duration) {
          if (duration === void 0) {
            duration = 0.3;
          }
          this._hasBeenPlayed = true;
          var state = this._nameToState[name];
          if (state) {
            this.doPlayOrCrossFade(state, duration);
          }
        };
        _proto.pause = function pause() {
          this._crossFade.pause();
        };
        _proto.resume = function resume() {
          this._crossFade.resume();
        };
        _proto.stop = function stop() {
          this._crossFade.stop();
        };
        _proto.getState = function getState(name) {
          var state = this._nameToState[name];
          if (state && !state.curveLoaded) {
            state.initialize(this.node);
          }
          return state || null;
        };
        _proto.createState = function createState(clip, name) {
          name = name || clip.name;
          this.removeState(name);
          return this._doCreateState(clip, name);
        };
        _proto.removeState = function removeState(name) {
          var state = this._nameToState[name];
          if (state) {
            state.allowLastFrameEvent(false);
            state.stop();
            delete this._nameToState[name];
          }
        };
        _proto.addClip = function addClip(clip, name) {
          if (!contains$2(this._clips, clip)) {
            this._clips.push(clip);
          }
          return this.createState(clip, name);
        };
        _proto.removeClip = function removeClip(clip, force) {
          var removalState;
          for (var name in this._nameToState) {
            var state = this._nameToState[name];
            var stateClip = state.clip;
            if (stateClip === clip) {
              removalState = state;
              break;
            }
          }
          if (clip === this._defaultClip) {
            if (force) {
              this._defaultClip = null;
            } else {
              {
                warnID(3902);
              }
              return;
            }
          }
          if (removalState && removalState.isPlaying) {
            if (force) {
              removalState.stop();
            } else {
              {
                warnID(3903);
              }
              return;
            }
          }
          this._clips = this._clips.filter(function (item) {
            return item !== clip;
          });
          if (removalState) {
            delete this._nameToState[removalState.name];
          }
        };
        _proto.on = function on(type, callback, thisArg, once) {
          var ret = _Eventify.prototype.on.call(this, type, callback, thisArg, once);
          if (type === EventType$5.LASTFRAME) {
            this._syncAllowLastFrameEvent();
          }
          return ret;
        };
        _proto.once = function once(type, callback, thisArg) {
          var ret = _Eventify.prototype.once.call(this, type, callback, thisArg);
          if (type === EventType$5.LASTFRAME) {
            this._syncAllowLastFrameEvent();
          }
          return ret;
        };
        _proto.off = function off(type, callback, thisArg) {
          _Eventify.prototype.off.call(this, type, callback, thisArg);
          if (type === EventType$5.LASTFRAME) {
            this._syncDisallowLastFrameEvent();
          }
        };
        _proto._createState = function _createState(clip, name) {
          return new AnimationState(clip, name);
        };
        _proto._doCreateState = function _doCreateState(clip, name) {
          var state = this._createState(clip, name);
          state._setEventTarget(this);
          state.allowLastFrameEvent(this.hasEventListener(EventType$5.LASTFRAME));
          if (this.node) {
            state.initialize(this.node);
          }
          this._nameToState[state.name] = state;
          return state;
        };
        _proto.doPlayOrCrossFade = function doPlayOrCrossFade(state, duration) {
          this._crossFade.play();
          this._crossFade.crossFade(state, duration);
        };
        _proto._removeStateOfAutomaticClip = function _removeStateOfAutomaticClip(clip) {
          for (var name in this._nameToState) {
            var state = this._nameToState[name];
            if (equalClips(clip, state.clip)) {
              state.stop();
              delete this._nameToState[name];
            }
          }
        };
        _proto._syncAllowLastFrameEvent = function _syncAllowLastFrameEvent() {
          if (this.hasEventListener(EventType$5.LASTFRAME)) {
            for (var stateName in this._nameToState) {
              this._nameToState[stateName].allowLastFrameEvent(true);
            }
          }
        };
        _proto._syncDisallowLastFrameEvent = function _syncDisallowLastFrameEvent() {
          if (!this.hasEventListener(EventType$5.LASTFRAME)) {
            for (var stateName in this._nameToState) {
              this._nameToState[stateName].allowLastFrameEvent(false);
            }
          }
        };
        _createClass(Animation, [{
          key: "clips",
          get: function get() {
            return this._clips;
          },
          set: function set(value) {
            var _this2 = this;
            if (this._crossFade) {
              this._crossFade.clear();
            }
            for (var _iterator = _createForOfIteratorHelperLoose(this._clips), _step; !(_step = _iterator()).done;) {
              var clip = _step.value;
              if (clip) {
                this._removeStateOfAutomaticClip(clip);
              }
            }
            for (var _iterator2 = _createForOfIteratorHelperLoose(value), _step2; !(_step2 = _iterator2()).done;) {
              var _clip = _step2.value;
              if (_clip) {
                this.createState(_clip);
              }
            }
            var newDefaultClip = value.find(function (clip) {
              return equalClips(clip, _this2._defaultClip);
            });
            if (newDefaultClip) {
              this._defaultClip = newDefaultClip;
            } else {
              this._defaultClip = null;
            }
            this._clips = value;
          }
        }, {
          key: "defaultClip",
          get: function get() {
            return this._defaultClip;
          },
          set: function set(value) {
            this._defaultClip = value;
            if (!value) {
              return;
            }
            var isBoundedDefaultClip = this._clips.findIndex(function (clip) {
              return equalClips(clip, value);
            }) >= 0;
            if (!isBoundedDefaultClip) {
              this._clips.push(value);
              this.createState(value);
            }
          }
        }]);
        return Animation;
      }(Eventify(Component)), _class3$l.EventType = EventType$5, _class3$l), (_applyDecoratedDescriptor(_class2$G.prototype, "clips", [_dec3$t], Object.getOwnPropertyDescriptor(_class2$G.prototype, "clips"), _class2$G.prototype), _applyDecoratedDescriptor(_class2$G.prototype, "defaultClip", [_dec4$n], Object.getOwnPropertyDescriptor(_class2$G.prototype, "defaultClip"), _class2$G.prototype), _initializer$E = applyDecoratedInitializer(_class2$G.prototype, "playOnLoad", [serializable$j], function () {
        return false;
      }), _initializer2$A = applyDecoratedInitializer(_class2$G.prototype, "_clips", [_dec5$l], function () {
        return [];
      }), _initializer3$q = applyDecoratedInitializer(_class2$G.prototype, "_defaultClip", [serializable$j], function () {
        return null;
      })), _class2$G)) || _class$H) || _class$H));
      function equalClips(clip1, clip2) {
        if (clip1 === clip2) {
          return true;
        }
        return !!clip1 && !!clip2 && clip1._uuid === clip2._uuid && clip1._uuid;
      }
      legacyCC.Animation = Animation;
      legacyCC.AnimationComponent = Animation;
      setClassAlias(Animation, 'cc.AnimationComponent');

      var AudioEvent;
      (function (AudioEvent) {
        AudioEvent["PLAYED"] = "play";
        AudioEvent["PAUSED"] = "pause";
        AudioEvent["STOPPED"] = "stop";
        AudioEvent["SEEKED"] = "seeked";
        AudioEvent["ENDED"] = "ended";
        AudioEvent["INTERRUPTION_BEGIN"] = "interruptionBegin";
        AudioEvent["INTERRUPTION_END"] = "interruptionEnd";
        AudioEvent["USER_GESTURE"] = "on_gesture";
      })(AudioEvent || (AudioEvent = {}));
      var AudioType;
      (function (AudioType) {
        AudioType[AudioType["DOM_AUDIO"] = 0] = "DOM_AUDIO";
        AudioType[AudioType["WEB_AUDIO"] = 1] = "WEB_AUDIO";
        AudioType[AudioType["MINIGAME_AUDIO"] = 2] = "MINIGAME_AUDIO";
        AudioType[AudioType["NATIVE_AUDIO"] = 3] = "NATIVE_AUDIO";
        AudioType[AudioType["UNKNOWN_AUDIO"] = 4] = "UNKNOWN_AUDIO";
      })(AudioType || (AudioType = {}));
      var AudioState;
      (function (AudioState) {
        AudioState[AudioState["INIT"] = 0] = "INIT";
        AudioState[AudioState["PLAYING"] = 1] = "PLAYING";
        AudioState[AudioState["PAUSED"] = 2] = "PAUSED";
        AudioState[AudioState["STOPPED"] = 3] = "STOPPED";
        AudioState[AudioState["INTERRUPTED"] = 4] = "INTERRUPTED";
      })(AudioState || (AudioState = {}));
      var AudioPCMDataView = exports('aw', function () {
        function AudioPCMDataView() {
          this._bufferView = void 0;
          this._normalizeFactor = 1;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          if (args.length === 2) {
            this._bufferView = args[0];
            this._normalizeFactor = args[1];
          } else {
            var _arrayBuffer = args[0];
            var _Ctor = args[1];
            var _normalizeFactor = args[2];
            this._bufferView = new _Ctor(_arrayBuffer);
            this._normalizeFactor = _normalizeFactor;
          }
        }
        var _proto = AudioPCMDataView.prototype;
        _proto.getData = function getData(offset) {
          return this._bufferView[offset] * this._normalizeFactor;
        };
        _createClass(AudioPCMDataView, [{
          key: "length",
          get: function get() {
            return this._bufferView.length;
          }
        }]);
        return AudioPCMDataView;
      }());

      function removeUnneededCalls(instance) {
        var size = instance._operationQueue.length;
        var tmpQueue = instance._operationQueue.slice();
        var reserveOps = [];
        var seekSearched = false;
        for (var i = size - 1; i >= 0; i--) {
          var opInfo = tmpQueue[i];
          if (opInfo.op === 'stop') {
            reserveOps.push(opInfo);
            break;
          } else if (opInfo.op === 'seek') {
            if (!seekSearched) {
              reserveOps.push(opInfo);
              seekSearched = true;
            }
          } else if (seekSearched) {
            reserveOps.push(opInfo);
            break;
          } else if (reserveOps.length === 0) {
            reserveOps.push(opInfo);
          }
        }
        instance._operationQueue = reserveOps.reverse();
      }
      var operationId = 0;
      function _tryCallingRecursively(target, opInfo) {
        var _opInfo$func;
        if (opInfo.invoking) {
          return;
        }
        opInfo.invoking = true;
        (_opInfo$func = opInfo.func).call.apply(_opInfo$func, [target].concat(opInfo.args)).then(function () {
          opInfo.invoking = false;
          target._operationQueue.shift();
          target._eventTarget.emit(opInfo.id.toString());
          removeUnneededCalls(target);
          var nextOpInfo = target._operationQueue[0];
          if (nextOpInfo) {
            _tryCallingRecursively(target, nextOpInfo);
          }
        })["catch"](function (e) {});
      }
      function enqueueOperation(target, propertyKey, descriptor) {
        var originalOperation = descriptor.value;
        descriptor.value = function () {
          var _this = this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          return new Promise(function (resolve) {
            var id = operationId++;
            var instance = _this;
            instance._operationQueue.push({
              op: propertyKey,
              id: id,
              func: originalOperation,
              args: args,
              invoking: false
            });
            instance._eventTarget.once(id.toString(), resolve);
            var opInfo = instance._operationQueue[0];
            _tryCallingRecursively(instance, opInfo);
          });
        };
      }

      var _class2$F;
      function ensurePlaying(domAudio) {
        return new Promise(function (resolve) {
          var promise = domAudio.play();
          if (promise === undefined) {
            return resolve();
          }
          promise.then(resolve)["catch"](function () {
            var onGesture = function onGesture() {
              domAudio.play().then(function () {
                canvas === null || canvas === void 0 ? void 0 : canvas.removeEventListener('touchend', onGesture, {
                  capture: true
                });
                canvas === null || canvas === void 0 ? void 0 : canvas.removeEventListener('mouseup', onGesture, {
                  capture: true
                });
              })["catch"](function (e) {});
              resolve();
            };
            var canvas = document.getElementById('GameCanvas');
            canvas === null || canvas === void 0 ? void 0 : canvas.addEventListener('touchend', onGesture, {
              capture: true
            });
            canvas === null || canvas === void 0 ? void 0 : canvas.addEventListener('mouseup', onGesture, {
              capture: true
            });
          });
          return null;
        });
      }
      var OneShotAudioDOM = function () {
        function OneShotAudioDOM(nativeAudio, volume) {
          this._domAudio = void 0;
          this._onPlayCb = void 0;
          this._onEndCb = void 0;
          this._domAudio = nativeAudio;
          nativeAudio.volume = volume;
        }
        var _proto = OneShotAudioDOM.prototype;
        _proto.play = function play() {
          var _this = this;
          ensurePlaying(this._domAudio).then(function () {
            var _this$onPlay;
            (_this$onPlay = _this.onPlay) === null || _this$onPlay === void 0 ? void 0 : _this$onPlay.call(_this);
          })["catch"](function (e) {});
        };
        _proto.stop = function stop() {
          this._domAudio.pause();
        };
        _createClass(OneShotAudioDOM, [{
          key: "onPlay",
          get: function get() {
            return this._onPlayCb;
          },
          set: function set(cb) {
            this._onPlayCb = cb;
          }
        }, {
          key: "onEnd",
          get: function get() {
            return this._onEndCb;
          },
          set: function set(cb) {
            if (this._onEndCb) {
              this._domAudio.removeEventListener('ended', this._onEndCb);
            }
            this._onEndCb = cb;
            if (cb) {
              this._domAudio.addEventListener('ended', cb);
            }
          }
        }]);
        return OneShotAudioDOM;
      }();
      var AudioPlayerDOM = (_class2$F = function () {
        function AudioPlayerDOM(nativeAudio) {
          var _this2 = this;
          this._domAudio = void 0;
          this._state = AudioState.INIT;
          this._onEnded = void 0;
          this._eventTarget = new EventTarget();
          this._operationQueue = [];
          this._domAudio = nativeAudio;
          game.on(Game.EVENT_PAUSE, this._onInterruptedBegin, this);
          game.on(Game.EVENT_RESUME, this._onInterruptedEnd, this);
          this._onEnded = function () {
            _this2.seek(0)["catch"](function (e) {});
            _this2._state = AudioState.INIT;
            _this2._eventTarget.emit(AudioEvent.ENDED);
          };
          this._domAudio.addEventListener('ended', this._onEnded);
        }
        var _proto2 = AudioPlayerDOM.prototype;
        _proto2.destroy = function destroy() {
          game.off(Game.EVENT_PAUSE, this._onInterruptedBegin, this);
          game.off(Game.EVENT_RESUME, this._onInterruptedEnd, this);
          this._domAudio.removeEventListener('ended', this._onEnded);
          this._domAudio = null;
        };
        AudioPlayerDOM.load = function load(url) {
          return new Promise(function (resolve) {
            AudioPlayerDOM.loadNative(url).then(function (domAudio) {
              resolve(new AudioPlayerDOM(domAudio));
            })["catch"](function (e) {});
          });
        };
        AudioPlayerDOM.loadNative = function loadNative(url) {
          return new Promise(function (resolve, reject) {
            var domAudio = document.createElement('audio');
            var loadedEvent = 'canplaythrough';
            if (systemInfo.os === OS.IOS) {
              loadedEvent = 'loadedmetadata';
            } else if (systemInfo.browserType === BrowserType.FIREFOX) {
              loadedEvent = 'canplay';
            }
            var timer = setTimeout(function () {
              if (domAudio.readyState === 0) {
                failure();
              } else {
                success();
              }
            }, 8000);
            var clearEvent = function clearEvent() {
              clearTimeout(timer);
              domAudio.removeEventListener(loadedEvent, success, false);
              domAudio.removeEventListener('error', failure, false);
            };
            var success = function success() {
              clearEvent();
              resolve(domAudio);
            };
            var failure = function failure() {
              clearEvent();
              var message = "load audio failure - " + url;
              reject(message);
            };
            domAudio.addEventListener(loadedEvent, success, false);
            domAudio.addEventListener('error', failure, false);
            domAudio.src = url;
          });
        };
        AudioPlayerDOM.loadOneShotAudio = function loadOneShotAudio(url, volume) {
          return new Promise(function (resolve, reject) {
            AudioPlayerDOM.loadNative(url).then(function (domAudio) {
              var oneShotAudio = new OneShotAudioDOM(domAudio, volume);
              resolve(oneShotAudio);
            })["catch"](reject);
          });
        };
        _proto2._onInterruptedBegin = function _onInterruptedBegin() {
          var _this3 = this;
          if (this._state === AudioState.PLAYING) {
            this.pause().then(function () {
              _this3._state = AudioState.INTERRUPTED;
              _this3._eventTarget.emit(AudioEvent.INTERRUPTION_BEGIN);
            })["catch"](function (e) {});
          }
        };
        _proto2._onInterruptedEnd = function _onInterruptedEnd() {
          var _this4 = this;
          if (this._state === AudioState.INTERRUPTED) {
            this.play().then(function () {
              _this4._eventTarget.emit(AudioEvent.INTERRUPTION_END);
            })["catch"](function (e) {});
          }
        };
        _proto2.getPCMData = function getPCMData(channelIndex) {
          return undefined;
        };
        _proto2.seek = function seek(time) {
          time = clamp$1(time, 0, this.duration);
          this._domAudio.currentTime = time;
          return Promise.resolve();
        };
        _proto2.play = function play() {
          var _this5 = this;
          return new Promise(function (resolve) {
            ensurePlaying(_this5._domAudio).then(function () {
              _this5._state = AudioState.PLAYING;
              resolve();
            })["catch"](function (e) {});
          });
        };
        _proto2.pause = function pause() {
          this._domAudio.pause();
          this._state = AudioState.PAUSED;
          return Promise.resolve();
        };
        _proto2.stop = function stop() {
          var _this6 = this;
          return new Promise(function (resolve) {
            _this6._domAudio.pause();
            _this6._domAudio.currentTime = 0;
            _this6._state = AudioState.STOPPED;
            resolve();
          });
        };
        _proto2.onInterruptionBegin = function onInterruptionBegin(cb) {
          this._eventTarget.on(AudioEvent.INTERRUPTION_BEGIN, cb);
        };
        _proto2.offInterruptionBegin = function offInterruptionBegin(cb) {
          this._eventTarget.off(AudioEvent.INTERRUPTION_BEGIN, cb);
        };
        _proto2.onInterruptionEnd = function onInterruptionEnd(cb) {
          this._eventTarget.on(AudioEvent.INTERRUPTION_END, cb);
        };
        _proto2.offInterruptionEnd = function offInterruptionEnd(cb) {
          this._eventTarget.off(AudioEvent.INTERRUPTION_END, cb);
        };
        _proto2.onEnded = function onEnded(cb) {
          this._eventTarget.on(AudioEvent.ENDED, cb);
        };
        _proto2.offEnded = function offEnded(cb) {
          this._eventTarget.off(AudioEvent.ENDED, cb);
        };
        _createClass(AudioPlayerDOM, [{
          key: "src",
          get: function get() {
            return this._domAudio ? this._domAudio.src : '';
          }
        }, {
          key: "type",
          get: function get() {
            return AudioType.DOM_AUDIO;
          }
        }, {
          key: "state",
          get: function get() {
            return this._state;
          }
        }, {
          key: "loop",
          get: function get() {
            return this._domAudio.loop;
          },
          set: function set(val) {
            this._domAudio.loop = val;
          }
        }, {
          key: "volume",
          get: function get() {
            return this._domAudio.volume;
          },
          set: function set(val) {
            val = clamp01(val);
            this._domAudio.volume = val;
          }
        }, {
          key: "duration",
          get: function get() {
            return this._domAudio.duration;
          }
        }, {
          key: "currentTime",
          get: function get() {
            return this._domAudio.currentTime;
          }
        }, {
          key: "sampleRate",
          get: function get() {
            return 0;
          }
        }]);
        return AudioPlayerDOM;
      }(), (_applyDecoratedDescriptor(_class2$F.prototype, "seek", [enqueueOperation], Object.getOwnPropertyDescriptor(_class2$F.prototype, "seek"), _class2$F.prototype), _applyDecoratedDescriptor(_class2$F.prototype, "play", [enqueueOperation], Object.getOwnPropertyDescriptor(_class2$F.prototype, "play"), _class2$F.prototype), _applyDecoratedDescriptor(_class2$F.prototype, "pause", [enqueueOperation], Object.getOwnPropertyDescriptor(_class2$F.prototype, "pause"), _class2$F.prototype), _applyDecoratedDescriptor(_class2$F.prototype, "stop", [enqueueOperation], Object.getOwnPropertyDescriptor(_class2$F.prototype, "stop"), _class2$F.prototype)), _class2$F);

      var AudioTimer = function () {
        function AudioTimer(nativeAudio) {
          this._nativeAudio = void 0;
          this._startTime = 0;
          this._startOffset = 0;
          this._isPaused = true;
          this._nativeAudio = nativeAudio;
        }
        var _proto = AudioTimer.prototype;
        _proto.destroy = function destroy() {
          this._nativeAudio = undefined;
        };
        _proto._now = function _now() {
          return performance.now() / 1000;
        };
        _proto._calculateCurrentTime = function _calculateCurrentTime() {
          var timePassed = this._now() - this._startTime;
          var currentTime = this._startOffset + timePassed;
          if (currentTime >= this.duration) {
            this._startTime = this._now();
            this._startOffset = 0;
          }
          return currentTime % this.duration;
        };
        _proto.start = function start() {
          this._isPaused = false;
          this._startTime = this._now();
        };
        _proto.pause = function pause() {
          if (this._isPaused) {
            return;
          }
          this._isPaused = true;
          this._startOffset = this._calculateCurrentTime();
        };
        _proto.stop = function stop() {
          this._isPaused = true;
          this._startOffset = 0;
        };
        _proto.seek = function seek(time) {
          this._startTime = this._now();
          this._startOffset = clamp$1(time, 0, this.duration);
        };
        _createClass(AudioTimer, [{
          key: "duration",
          get: function get() {
            return this._nativeAudio.duration;
          }
        }, {
          key: "currentTime",
          get: function get() {
            if (this._isPaused) {
              return this._startOffset;
            } else {
              return this._calculateCurrentTime();
            }
          }
        }]);
        return AudioTimer;
      }();

      var AudioBufferManager = function () {
        function AudioBufferManager() {
          this._audioBufferDataMap = {};
        }
        var _proto = AudioBufferManager.prototype;
        _proto.addCache = function addCache(url, audioBuffer) {
          var audioBufferData = this._audioBufferDataMap[url];
          if (audioBufferData) {
            console.warn("Audio buffer " + url + " has been cached");
            return;
          }
          this._audioBufferDataMap[url] = {
            usedCount: 1,
            audioBuffer: audioBuffer
          };
        };
        _proto.retainCache = function retainCache(url) {
          var audioBufferData = this._audioBufferDataMap[url];
          if (!audioBufferData) {
            console.warn("Audio buffer cache " + url + " has not been added.");
            return;
          }
          audioBufferData.usedCount++;
        };
        _proto.getCache = function getCache(url) {
          var audioBufferData = this._audioBufferDataMap[url];
          return audioBufferData === null || audioBufferData === void 0 ? void 0 : audioBufferData.audioBuffer;
        };
        _proto.tryReleasingCache = function tryReleasingCache(url) {
          var audioBufferData = this._audioBufferDataMap[url];
          if (!audioBufferData) {
            console.warn("Audio buffer cache " + url + " has not been added.");
            return;
          }
          if (--audioBufferData.usedCount <= 0) {
            delete this._audioBufferDataMap[url];
          }
        };
        return AudioBufferManager;
      }();
      var audioBufferManager = new AudioBufferManager();

      var _class3$k;
      var AudioContextClass = window.AudioContext || window.webkitAudioContext || window.mozAudioContext;
      var _contextRunningEvent = 'on-context-running';
      var AudioContextAgent = function () {
        function AudioContextAgent() {
          var _this = this;
          this._eventTarget = void 0;
          this._context = void 0;
          this._isRunning = false;
          this._context = new (window.AudioContext || window.webkitAudioContext || window.mozAudioContext)();
          this._eventTarget = new EventTarget();
          this._context.onstatechange = function () {
            if (_this._context.state === 'running') {
              _this._isRunning = true;
              _this._eventTarget.emit(_contextRunningEvent);
            } else {
              _this._isRunning = false;
            }
          };
        }
        var _proto = AudioContextAgent.prototype;
        _proto.onceRunning = function onceRunning(cb, target) {
          this._eventTarget.once(_contextRunningEvent, cb, target);
        };
        _proto.offRunning = function offRunning(cb, target) {
          this._eventTarget.off(_contextRunningEvent, cb, target);
        };
        _proto.decodeAudioData = function decodeAudioData(audioData) {
          var _this2 = this;
          return new Promise(function (resolve) {
            var promise = _this2._context.decodeAudioData(audioData, function (audioBuffer) {
              resolve(audioBuffer);
            }, function (err) {
              console.error('failed to load Web Audio', err);
            });
            promise === null || promise === void 0 ? void 0 : promise["catch"](function (e) {
              warn('decodeAudioData error', e);
            });
          });
        };
        _proto.runContext = function runContext() {
          var _this3 = this;
          return new Promise(function (resolve) {
            if (_this3.isRunning) {
              resolve();
              return;
            }
            var context = _this3._context;
            if (!context.resume) {
              resolve();
              return;
            }
            context.resume()["catch"](function (e) {
              warn('runContext error', e);
            });
            if (context.state === 'running') {
              resolve();
              return;
            }
            var canvas = document.getElementById('GameCanvas');
            var onGesture = function onGesture() {
              context.resume().then(function () {
                canvas === null || canvas === void 0 ? void 0 : canvas.removeEventListener('touchend', onGesture, {
                  capture: true
                });
                canvas === null || canvas === void 0 ? void 0 : canvas.removeEventListener('mouseup', onGesture, {
                  capture: true
                });
                resolve();
              })["catch"](function (e) {
                warn('onGesture resume error', e);
              });
            };
            canvas === null || canvas === void 0 ? void 0 : canvas.addEventListener('touchend', onGesture, {
              capture: true
            });
            canvas === null || canvas === void 0 ? void 0 : canvas.addEventListener('mouseup', onGesture, {
              capture: true
            });
          });
        };
        _proto.createBufferSource = function createBufferSource(audioBuffer, loop) {
          var sourceBufferNode = this._context.createBufferSource();
          if (audioBuffer !== undefined) {
            sourceBufferNode.buffer = audioBuffer;
          }
          if (loop !== undefined) {
            sourceBufferNode.loop = loop;
          }
          return sourceBufferNode;
        };
        _proto.createGain = function createGain(volume) {
          if (volume === void 0) {
            volume = 1;
          }
          var gainNode = this._context.createGain();
          this.setGainValue(gainNode, volume);
          return gainNode;
        };
        _proto.setGainValue = function setGainValue(gain, volume) {
          if (gain.gain.setTargetAtTime) {
            try {
              gain.gain.setTargetAtTime(volume, this._context.currentTime, 0);
            } catch (e) {
              gain.gain.setTargetAtTime(volume, this._context.currentTime, 0.01);
            }
          } else {
            gain.gain.value = volume;
          }
        };
        _proto.connectContext = function connectContext(audioNode) {
          if (!this._context) {
            return;
          }
          audioNode.connect(this._context.destination);
        };
        _createClass(AudioContextAgent, [{
          key: "isRunning",
          get: function get() {
            return this._isRunning;
          }
        }, {
          key: "currentTime",
          get: function get() {
            return this._context.currentTime;
          }
        }]);
        return AudioContextAgent;
      }();
      AudioContextAgent.support = !!AudioContextClass;
      var audioContextAgent;
      if (AudioContextAgent.support) {
        audioContextAgent = new AudioContextAgent();
      }
      var OneShotAudioWeb = function () {
        function OneShotAudioWeb(audioBuffer, volume, url) {
          this._duration = void 0;
          this._bufferSourceNode = void 0;
          this._onPlayCb = void 0;
          this._currentTimer = 0;
          this._url = void 0;
          this._onEndCb = void 0;
          this._duration = audioBuffer.duration;
          this._url = url;
          this._bufferSourceNode = audioContextAgent.createBufferSource(audioBuffer, false);
          var gainNode = audioContextAgent.createGain(volume);
          this._bufferSourceNode.connect(gainNode);
          audioContextAgent.connectContext(gainNode);
        }
        var _proto2 = OneShotAudioWeb.prototype;
        _proto2.play = function play() {
          var _this4 = this;
          this._bufferSourceNode.start();
          audioContextAgent.runContext().then(function () {
            var _this4$onPlay;
            (_this4$onPlay = _this4.onPlay) === null || _this4$onPlay === void 0 ? void 0 : _this4$onPlay.call(_this4);
            _this4._currentTimer = window.setTimeout(function () {
              var _this4$onEnd;
              audioBufferManager.tryReleasingCache(_this4._url);
              (_this4$onEnd = _this4.onEnd) === null || _this4$onEnd === void 0 ? void 0 : _this4$onEnd.call(_this4);
            }, _this4._duration * 1000);
          })["catch"](function (e) {
            warn('play error', e);
          });
        };
        _proto2.stop = function stop() {
          clearTimeout(this._currentTimer);
          audioBufferManager.tryReleasingCache(this._url);
          this._bufferSourceNode.stop();
          this._bufferSourceNode.disconnect();
          this._bufferSourceNode.buffer = null;
        };
        _createClass(OneShotAudioWeb, [{
          key: "onPlay",
          get: function get() {
            return this._onPlayCb;
          },
          set: function set(cb) {
            this._onPlayCb = cb;
          }
        }, {
          key: "onEnd",
          get: function get() {
            return this._onEndCb;
          },
          set: function set(cb) {
            this._onEndCb = cb;
          }
        }]);
        return OneShotAudioWeb;
      }();
      var AudioPlayerWeb = (_class3$k = function () {
        function AudioPlayerWeb(audioBuffer, url) {
          this._src = void 0;
          this._audioBuffer = void 0;
          this._sourceNode = void 0;
          this._gainNode = void 0;
          this._currentTimer = 0;
          this._volume = 1;
          this._loop = false;
          this._state = AudioState.INIT;
          this._audioTimer = void 0;
          this._runningCallback = void 0;
          this._eventTarget = new EventTarget();
          this._operationQueue = [];
          this._audioBuffer = audioBuffer;
          this._audioTimer = new AudioTimer(audioBuffer);
          this._gainNode = audioContextAgent.createGain();
          audioContextAgent.connectContext(this._gainNode);
          this._src = url;
          game.on(Game.EVENT_PAUSE, this._onInterruptedBegin, this);
          game.on(Game.EVENT_RESUME, this._onInterruptedEnd, this);
        }
        var _proto3 = AudioPlayerWeb.prototype;
        _proto3.destroy = function destroy() {
          this._audioTimer.destroy();
          if (this._audioBuffer) {
            this._audioBuffer = null;
          }
          audioBufferManager.tryReleasingCache(this._src);
          game.off(Game.EVENT_PAUSE, this._onInterruptedBegin, this);
          game.off(Game.EVENT_RESUME, this._onInterruptedEnd, this);
          this.offRunning();
        };
        AudioPlayerWeb.load = function load(url) {
          return new Promise(function (resolve) {
            AudioPlayerWeb.loadNative(url).then(function (audioBuffer) {
              resolve(new AudioPlayerWeb(audioBuffer, url));
            })["catch"](function (e) {
              warn('load error', url, e);
            });
          });
        };
        AudioPlayerWeb.loadNative = function loadNative(url) {
          return new Promise(function (resolve, reject) {
            var cachedAudioBuffer = audioBufferManager.getCache(url);
            if (cachedAudioBuffer) {
              audioBufferManager.retainCache(url);
              resolve(cachedAudioBuffer);
              return;
            }
            var xhr = new XMLHttpRequest();
            var errInfo = "load audio failed: " + url + ", status: ";
            xhr.open('GET', url, true);
            xhr.responseType = 'arraybuffer';
            xhr.onload = function () {
              if (xhr.status === 200 || xhr.status === 0) {
                audioContextAgent.decodeAudioData(xhr.response).then(function (decodedAudioBuffer) {
                  audioBufferManager.addCache(url, decodedAudioBuffer);
                  resolve(decodedAudioBuffer);
                })["catch"](function (e) {
                  warn('loadNative error', url, e);
                });
              } else {
                reject(new Error("" + errInfo + xhr.status + "(no response)"));
              }
            };
            xhr.onerror = function () {
              reject(new Error("" + errInfo + xhr.status + "(error)"));
            };
            xhr.ontimeout = function () {
              reject(new Error("" + errInfo + xhr.status + "(time out)"));
            };
            xhr.onabort = function () {
              reject(new Error("" + errInfo + xhr.status + "(abort)"));
            };
            xhr.send(null);
          });
        };
        AudioPlayerWeb.loadOneShotAudio = function loadOneShotAudio(url, volume) {
          return new Promise(function (resolve, reject) {
            AudioPlayerWeb.loadNative(url).then(function (audioBuffer) {
              var oneShotAudio = new OneShotAudioWeb(audioBuffer, volume, url);
              resolve(oneShotAudio);
            })["catch"](reject);
          });
        };
        _proto3.getPCMData = function getPCMData(channelIndex) {
          return new AudioPCMDataView(this._audioBuffer.getChannelData(channelIndex), 1);
        };
        _proto3._onInterruptedBegin = function _onInterruptedBegin() {
          var _this5 = this;
          if (this._state === AudioState.PLAYING) {
            this.pause().then(function () {
              _this5._state = AudioState.INTERRUPTED;
              _this5._eventTarget.emit(AudioEvent.INTERRUPTION_BEGIN);
            })["catch"](function (e) {
              warn('_onInterruptedBegin error', e);
            });
          }
        };
        _proto3._onInterruptedEnd = function _onInterruptedEnd() {
          var _this6 = this;
          if (this._state === AudioState.INTERRUPTED) {
            this.play().then(function () {
              _this6._eventTarget.emit(AudioEvent.INTERRUPTION_END);
            })["catch"](function (e) {
              warn('_onInterruptedEnd error', e);
            });
          }
        };
        _proto3.offRunning = function offRunning() {
          if (this._runningCallback) {
            audioContextAgent.offRunning(this._runningCallback);
            this._runningCallback = undefined;
          }
        };
        _proto3.seek = function seek(time) {
          var _this7 = this;
          return new Promise(function (resolve) {
            _this7.offRunning();
            _this7._audioTimer.seek(time);
            if (_this7._state === AudioState.PLAYING) {
              _this7._doPlay().then(resolve)["catch"](function (e) {
                warn('seek error', e);
              });
            } else {
              resolve();
            }
          });
        };
        _proto3.play = function play() {
          this.offRunning();
          return this._doPlay();
        };
        _proto3._doPlay = function _doPlay() {
          var _this8 = this;
          return new Promise(function (resolve) {
            if (audioContextAgent.isRunning) {
              _this8._startSourceNode();
              resolve();
            } else {
              _this8.offRunning();
              _this8._runningCallback = function () {
                _this8._startSourceNode();
                resolve();
              };
              audioContextAgent.onceRunning(_this8._runningCallback);
              audioContextAgent.runContext()["catch"](function (e) {
                warn('doPlay error', e);
              });
            }
          });
        };
        _proto3._startSourceNode = function _startSourceNode() {
          var _this9 = this;
          this._stopSourceNode();
          this._sourceNode = audioContextAgent.createBufferSource(this._audioBuffer, this.loop);
          this._sourceNode.connect(this._gainNode);
          this._sourceNode.loop = this._loop;
          this._sourceNode.start(0, this._audioTimer.currentTime);
          this._state = AudioState.PLAYING;
          this._audioTimer.start();
          var checkEnded = function checkEnded() {
            if (_this9.loop) {
              _this9._currentTimer = window.setTimeout(checkEnded, _this9._audioBuffer.duration * 1000);
            } else {
              _this9._audioTimer.stop();
              _this9._eventTarget.emit(AudioEvent.ENDED);
              _this9._state = AudioState.INIT;
            }
          };
          window.clearTimeout(this._currentTimer);
          this._currentTimer = window.setTimeout(checkEnded, (this._audioBuffer.duration - this._audioTimer.currentTime) * 1000);
        };
        _proto3._stopSourceNode = function _stopSourceNode() {
          try {
            if (this._sourceNode) {
              this._sourceNode.stop();
              this._sourceNode.disconnect();
              this._sourceNode.buffer = null;
              this._sourceNode = undefined;
            }
          } catch (e) {}
        };
        _proto3.pause = function pause() {
          this.offRunning();
          if (this._state !== AudioState.PLAYING || !this._sourceNode) {
            return Promise.resolve();
          }
          this._audioTimer.pause();
          this._state = AudioState.PAUSED;
          window.clearTimeout(this._currentTimer);
          this._stopSourceNode();
          return Promise.resolve();
        };
        _proto3.stop = function stop() {
          this.offRunning();
          if (!this._sourceNode) {
            this._audioTimer.stop();
            this._state = AudioState.STOPPED;
            return Promise.resolve();
          }
          this._audioTimer.stop();
          this._state = AudioState.STOPPED;
          window.clearTimeout(this._currentTimer);
          this._stopSourceNode();
          return Promise.resolve();
        };
        _proto3.onInterruptionBegin = function onInterruptionBegin(cb) {
          this._eventTarget.on(AudioEvent.INTERRUPTION_BEGIN, cb);
        };
        _proto3.offInterruptionBegin = function offInterruptionBegin(cb) {
          this._eventTarget.off(AudioEvent.INTERRUPTION_BEGIN, cb);
        };
        _proto3.onInterruptionEnd = function onInterruptionEnd(cb) {
          this._eventTarget.on(AudioEvent.INTERRUPTION_END, cb);
        };
        _proto3.offInterruptionEnd = function offInterruptionEnd(cb) {
          this._eventTarget.off(AudioEvent.INTERRUPTION_END, cb);
        };
        _proto3.onEnded = function onEnded(cb) {
          this._eventTarget.on(AudioEvent.ENDED, cb);
        };
        _proto3.offEnded = function offEnded(cb) {
          this._eventTarget.off(AudioEvent.ENDED, cb);
        };
        _createClass(AudioPlayerWeb, [{
          key: "sampleRate",
          get: function get() {
            return this._audioBuffer.sampleRate;
          }
        }, {
          key: "src",
          get: function get() {
            return this._src;
          }
        }, {
          key: "type",
          get: function get() {
            return AudioType.WEB_AUDIO;
          }
        }, {
          key: "state",
          get: function get() {
            return this._state;
          }
        }, {
          key: "loop",
          get: function get() {
            return this._loop;
          },
          set: function set(val) {
            this._loop = val;
            if (this._sourceNode) {
              this._sourceNode.loop = val;
            }
          }
        }, {
          key: "volume",
          get: function get() {
            return this._volume;
          },
          set: function set(val) {
            val = clamp01(val);
            this._volume = val;
            audioContextAgent.setGainValue(this._gainNode, val);
          }
        }, {
          key: "duration",
          get: function get() {
            return this._audioBuffer.duration;
          }
        }, {
          key: "currentTime",
          get: function get() {
            return this._audioTimer.currentTime;
          }
        }]);
        return AudioPlayerWeb;
      }(), (_applyDecoratedDescriptor(_class3$k.prototype, "seek", [enqueueOperation], Object.getOwnPropertyDescriptor(_class3$k.prototype, "seek"), _class3$k.prototype), _applyDecoratedDescriptor(_class3$k.prototype, "play", [enqueueOperation], Object.getOwnPropertyDescriptor(_class3$k.prototype, "play"), _class3$k.prototype), _applyDecoratedDescriptor(_class3$k.prototype, "pause", [enqueueOperation], Object.getOwnPropertyDescriptor(_class3$k.prototype, "pause"), _class3$k.prototype), _applyDecoratedDescriptor(_class3$k.prototype, "stop", [enqueueOperation], Object.getOwnPropertyDescriptor(_class3$k.prototype, "stop"), _class3$k.prototype)), _class3$k);

      var OneShotAudio = function () {
        function OneShotAudio(audio) {
          this._audio = void 0;
          this._audio = audio;
        }
        var _proto = OneShotAudio.prototype;
        _proto.play = function play() {
          this._audio.play();
        };
        _proto.stop = function stop() {
          this._audio.stop();
        };
        _createClass(OneShotAudio, [{
          key: "onPlay",
          get: function get() {
            return this._audio.onPlay;
          },
          set: function set(v) {
            this._audio.onPlay = v;
          }
        }, {
          key: "onEnd",
          get: function get() {
            return this._audio.onEnd;
          },
          set: function set(v) {
            this._audio.onEnd = v;
          }
        }]);
        return OneShotAudio;
      }();
      var AudioPlayer = function () {
        function AudioPlayer(player) {
          this._player = void 0;
          this._player = player;
        }
        AudioPlayer.load = function load(url, opts) {
          return new Promise(function (resolve) {
            if ((opts === null || opts === void 0 ? void 0 : opts.audioLoadMode) === AudioType.DOM_AUDIO || !AudioContextAgent.support) {
              if (!AudioContextAgent.support) {
                warnID(5201);
              }
              AudioPlayerDOM.load(url).then(function (domPlayer) {
                resolve(new AudioPlayer(domPlayer));
              })["catch"](function (e) {});
            } else {
              AudioPlayerWeb.load(url).then(function (webPlayer) {
                resolve(new AudioPlayer(webPlayer));
              })["catch"](function (e) {});
            }
          });
        };
        var _proto2 = AudioPlayer.prototype;
        _proto2.destroy = function destroy() {
          this._player.destroy();
        };
        AudioPlayer.loadNative = function loadNative(url, opts) {
          if ((opts === null || opts === void 0 ? void 0 : opts.audioLoadMode) === AudioType.DOM_AUDIO || !AudioContextAgent.support) {
            if (!AudioContextAgent.support) {
              warnID(5201);
            }
            return AudioPlayerDOM.loadNative(url);
          }
          return AudioPlayerWeb.loadNative(url);
        };
        AudioPlayer.loadOneShotAudio = function loadOneShotAudio(url, volume, opts) {
          return new Promise(function (resolve, reject) {
            if ((opts === null || opts === void 0 ? void 0 : opts.audioLoadMode) === AudioType.DOM_AUDIO || !AudioContextAgent.support) {
              if (!AudioContextAgent.support) {
                warnID(5201);
              }
              AudioPlayerDOM.loadOneShotAudio(url, volume).then(function (oneShotAudioDOM) {
                resolve(new OneShotAudio(oneShotAudioDOM));
              })["catch"](reject);
            } else {
              AudioPlayerWeb.loadOneShotAudio(url, volume).then(function (oneShotAudioWeb) {
                resolve(new OneShotAudio(oneShotAudioWeb));
              })["catch"](reject);
            }
          });
        };
        _proto2.getPCMData = function getPCMData(channelIndex) {
          return this._player.getPCMData(channelIndex);
        };
        _proto2.seek = function seek(time) {
          return this._player.seek(time);
        };
        _proto2.play = function play() {
          return this._player.play();
        };
        _proto2.pause = function pause() {
          return this._player.pause();
        };
        _proto2.stop = function stop() {
          return this._player.stop();
        };
        _proto2.onInterruptionBegin = function onInterruptionBegin(cb) {
          this._player.onInterruptionBegin(cb);
        };
        _proto2.offInterruptionBegin = function offInterruptionBegin(cb) {
          this._player.offInterruptionBegin(cb);
        };
        _proto2.onInterruptionEnd = function onInterruptionEnd(cb) {
          this._player.onInterruptionEnd(cb);
        };
        _proto2.offInterruptionEnd = function offInterruptionEnd(cb) {
          this._player.offInterruptionEnd(cb);
        };
        _proto2.onEnded = function onEnded(cb) {
          this._player.onEnded(cb);
        };
        _proto2.offEnded = function offEnded(cb) {
          this._player.offEnded(cb);
        };
        _createClass(AudioPlayer, [{
          key: "src",
          get: function get() {
            return this._player.src;
          }
        }, {
          key: "type",
          get: function get() {
            return this._player.type;
          }
        }, {
          key: "state",
          get: function get() {
            return this._player.state;
          }
        }, {
          key: "loop",
          get: function get() {
            return this._player.loop;
          },
          set: function set(val) {
            this._player.loop = val;
          }
        }, {
          key: "volume",
          get: function get() {
            return this._player.volume;
          },
          set: function set(val) {
            this._player.volume = val;
          }
        }, {
          key: "duration",
          get: function get() {
            return this._player.duration;
          }
        }, {
          key: "currentTime",
          get: function get() {
            return this._player.currentTime;
          }
        }, {
          key: "sampleRate",
          get: function get() {
            return this._player.sampleRate;
          }
        }]);
        return AudioPlayer;
      }();
      AudioPlayer.maxAudioChannel = 24;

      var _dec$H, _class$G, _class2$E, _initializer$D, _class3$j;
      var AudioClip = exports('av', (_dec$H = ccclass$n('cc.AudioClip'), _dec$H(_class$G = (_class2$E = (_class3$j = function (_Asset) {
        _inheritsLoose(AudioClip, _Asset);
        function AudioClip() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Asset.call.apply(_Asset, [this].concat(args)) || this;
          _this._duration = _initializer$D && _initializer$D();
          _this._loadMode = AudioType.UNKNOWN_AUDIO;
          _this._meta = null;
          _this._player = null;
          return _this;
        }
        var _proto = AudioClip.prototype;
        _proto.destroy = function destroy() {
          var _this$_player;
          var destroyResult = _Asset.prototype.destroy.call(this);
          (_this$_player = this._player) === null || _this$_player === void 0 ? void 0 : _this$_player.destroy();
          this._player = null;
          if (this._meta) {
            this._meta.player = null;
          }
          return destroyResult;
        };
        _proto.validate = function validate() {
          return !!this._meta;
        };
        _proto.getDuration = function getDuration() {
          if (this._duration) {
            return this._duration;
          }
          return this._meta ? this._meta.duration : 0;
        };
        _proto.getCurrentTime = function getCurrentTime() {
          return this._player ? this._player.currentTime : 0;
        };
        _proto.getVolume = function getVolume() {
          return this._player ? this._player.volume : 0;
        };
        _proto.getLoop = function getLoop() {
          return this._player ? this._player.loop : false;
        };
        _proto.setCurrentTime = function setCurrentTime(time) {
          var _this$_player2;
          (_this$_player2 = this._player) === null || _this$_player2 === void 0 ? void 0 : _this$_player2.seek(time)["catch"](function (e) {});
        };
        _proto.setVolume = function setVolume(volume) {
          if (this._player) {
            this._player.volume = volume;
          }
        };
        _proto.setLoop = function setLoop(loop) {
          if (this._player) {
            this._player.loop = loop;
          }
        };
        _proto.play = function play() {
          var _this$_player3;
          (_this$_player3 = this._player) === null || _this$_player3 === void 0 ? void 0 : _this$_player3.play()["catch"](function (e) {});
        };
        _proto.pause = function pause() {
          var _this$_player4;
          (_this$_player4 = this._player) === null || _this$_player4 === void 0 ? void 0 : _this$_player4.pause()["catch"](function (e) {});
        };
        _proto.stop = function stop() {
          var _this$_player5;
          (_this$_player5 = this._player) === null || _this$_player5 === void 0 ? void 0 : _this$_player5.stop()["catch"](function (e) {});
        };
        _proto.playOneShot = function playOneShot(volume) {
          if (volume === void 0) {
            volume = 1;
          }
          if (this._nativeAsset) {
            AudioPlayer.loadOneShotAudio(this._nativeAsset.url, volume).then(function (oneShotAudio) {
              oneShotAudio.play();
            })["catch"](function (e) {});
          }
        };
        _createClass(AudioClip, [{
          key: "duration",
          set: function set(v) {
            this._duration = v;
          }
        }, {
          key: "_nativeAsset",
          get: function get() {
            return this._meta;
          },
          set: function set(meta) {
            this._meta = meta;
            if (meta) {
              this._loadMode = meta.type;
              this._player = meta.player;
            } else {
              this._meta = null;
              this._loadMode = AudioType.UNKNOWN_AUDIO;
              this._duration = 0;
            }
          }
        }, {
          key: "_nativeDep",
          get: function get() {
            return {
              uuid: this._uuid,
              audioLoadMode: this.loadMode,
              ext: this._native,
              __isNative__: true
            };
          }
        }, {
          key: "loadMode",
          get: function get() {
            return this._loadMode;
          }
        }, {
          key: "state",
          get: function get() {
            return this._player ? this._player.state : AudioState.INIT;
          }
        }]);
        return AudioClip;
      }(Asset), _class3$j.AudioType = AudioType, _class3$j), (_initializer$D = applyDecoratedInitializer(_class2$E.prototype, "_duration", [serializable$j], function () {
        return 0;
      }), _applyDecoratedDescriptor(_class2$E.prototype, "_nativeDep", [override], Object.getOwnPropertyDescriptor(_class2$E.prototype, "_nativeDep"), _class2$E.prototype)), _class2$E)) || _class$G));
      legacyCC.AudioClip = AudioClip;

      function loadAudioPlayer(url, options, onComplete) {
        AudioPlayer.load(url, {
          audioLoadMode: options.audioLoadMode
        }).then(function (player) {
          var audioMeta = {
            player: player,
            url: url,
            duration: player.duration,
            type: player.type
          };
          onComplete(null, audioMeta);
        })["catch"](function (err) {
          onComplete(err);
        });
      }
      function createAudioClip(id, data, options, onComplete) {
        var out = new AudioClip();
        out._nativeUrl = id;
        out._nativeAsset = data;
        out.duration = data.duration;
        onComplete(null, out);
      }
      downloader$1.register({
        '.mp3': loadAudioPlayer,
        '.ogg': loadAudioPlayer,
        '.wav': loadAudioPlayer,
        '.m4a': loadAudioPlayer
      });
      factory.register({
        '.mp3': createAudioClip,
        '.ogg': createAudioClip,
        '.wav': createAudioClip,
        '.m4a': createAudioClip
      });

      var AudioManager = function () {
        function AudioManager() {
          this._oneShotAudioInfoList = [];
          this._audioPlayerInfoList = [];
        }
        var _proto = AudioManager.prototype;
        _proto._findIndex = function _findIndex(audioInfoList, audio) {
          return audioInfoList.findIndex(function (item) {
            return item.audio === audio;
          });
        };
        _proto._tryAddPlaying = function _tryAddPlaying(audioInfoList, audio) {
          var idx = this._findIndex(audioInfoList, audio);
          if (idx > -1) {
            audioInfoList[idx].playTime = performance.now();
            return false;
          }
          audioInfoList.push({
            audio: audio,
            playTime: performance.now()
          });
          return true;
        };
        _proto.addPlaying = function addPlaying(audio) {
          if (audio instanceof AudioPlayer) {
            this._tryAddPlaying(this._audioPlayerInfoList, audio);
          } else {
            this._tryAddPlaying(this._oneShotAudioInfoList, audio);
          }
        };
        _proto._tryRemovePlaying = function _tryRemovePlaying(audioInfoList, audio) {
          var idx = this._findIndex(audioInfoList, audio);
          if (idx === -1) {
            return false;
          }
          fastRemoveAt$2(audioInfoList, idx);
          return true;
        };
        _proto.removePlaying = function removePlaying(audio) {
          if (audio instanceof AudioPlayer) {
            this._tryRemovePlaying(this._audioPlayerInfoList, audio);
          } else {
            this._tryRemovePlaying(this._oneShotAudioInfoList, audio);
          }
        };
        _proto.discardOnePlayingIfNeeded = function discardOnePlayingIfNeeded() {
          if (this._audioPlayerInfoList.length + this._oneShotAudioInfoList.length < AudioPlayer.maxAudioChannel) {
            return;
          }
          var audioInfoToDiscard;
          if (this._oneShotAudioInfoList.length > 0) {
            this._oneShotAudioInfoList.forEach(function (audioInfo) {
              if (!audioInfoToDiscard || audioInfo.playTime < audioInfoToDiscard.playTime) {
                audioInfoToDiscard = audioInfo;
              }
            });
          } else {
            this._audioPlayerInfoList.forEach(function (audioInfo) {
              if (!audioInfoToDiscard || audioInfo.playTime < audioInfoToDiscard.playTime) {
                audioInfoToDiscard = audioInfo;
              }
            });
          }
          if (audioInfoToDiscard) {
            audioInfoToDiscard.audio.stop();
            this.removePlaying(audioInfoToDiscard.audio);
          }
        };
        _proto.pause = function pause() {
          this._oneShotAudioInfoList.forEach(function (info) {
            info.audio.stop();
          });
          this._audioPlayerInfoList.forEach(function (info) {
            info.audio.pause()["catch"](function (e) {});
          });
        };
        _proto.resume = function resume() {
          this._audioPlayerInfoList.forEach(function (info) {
            info.audio.play()["catch"](function (e) {});
          });
        };
        return AudioManager;
      }();
      var audioManager = new AudioManager();

      var _dec$G, _dec2$D, _dec3$s, _class$F, _class2$D, _initializer$C, _initializer2$z, _initializer3$p, _initializer4$j, _class3$i;
      var _LOADED_EVENT = 'audiosource-loaded';
      var AudioSourceEventType;
      (function (AudioSourceEventType) {
        AudioSourceEventType["STARTED"] = "started";
        AudioSourceEventType["ENDED"] = "ended";
      })(AudioSourceEventType || (AudioSourceEventType = {}));
      var AudioOperationType;
      (function (AudioOperationType) {
        AudioOperationType["PLAY"] = "play";
        AudioOperationType["STOP"] = "stop";
        AudioOperationType["PAUSE"] = "pause";
        AudioOperationType["SEEK"] = "seek";
      })(AudioOperationType || (AudioOperationType = {}));
      var AudioSource = exports('au', (_dec$G = ccclass$n('cc.AudioSource'), _dec2$D = type$7(AudioClip), _dec3$s = type$7(AudioClip), _dec$G(_class$F = (_class2$D = (_class3$i = function (_Component) {
        _inheritsLoose(AudioSource, _Component);
        function AudioSource() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Component.call.apply(_Component, [this].concat(args)) || this;
          _this._clip = _initializer$C && _initializer$C();
          _this._player = null;
          _this._hasRegisterListener = false;
          _this._loop = _initializer2$z && _initializer2$z();
          _this._playOnAwake = _initializer3$p && _initializer3$p();
          _this._volume = _initializer4$j && _initializer4$j();
          _this._cachedCurrentTime = -1;
          _this._operationsBeforeLoading = [];
          _this._isLoaded = false;
          _this._lastSetClip = null;
          return _this;
        }
        var _proto = AudioSource.prototype;
        _proto._resetPlayer = function _resetPlayer() {
          if (this._player) {
            audioManager.removePlaying(this._player);
            this._unregisterListener();
            this._player.destroy();
            this._player = null;
          }
        };
        _proto._syncPlayer = function _syncPlayer() {
          var _this2 = this;
          var clip = this._clip;
          if (this._lastSetClip === clip) {
            return;
          }
          if (!clip) {
            this._lastSetClip = null;
            this._resetPlayer();
            return;
          }
          if (!clip._nativeAsset) {
            console.error('Invalid audio clip');
            return;
          }
          this._isLoaded = false;
          this._lastSetClip = clip;
          this._operationsBeforeLoading.length = 0;
          AudioPlayer.load(clip._nativeAsset.url, {
            audioLoadMode: clip.loadMode
          }).then(function (player) {
            var _this2$node;
            if (_this2._lastSetClip !== clip) {
              player.destroy();
              return;
            }
            _this2._isLoaded = true;
            _this2._resetPlayer();
            _this2._player = player;
            _this2._syncStates();
            (_this2$node = _this2.node) === null || _this2$node === void 0 ? void 0 : _this2$node.emit(_LOADED_EVENT);
          })["catch"](function (e) {});
        };
        _proto._registerListener = function _registerListener() {
          var _this3 = this;
          if (!this._hasRegisterListener && this._player) {
            var player = this._player;
            player.onEnded(function () {
              var _this3$node;
              audioManager.removePlaying(player);
              (_this3$node = _this3.node) === null || _this3$node === void 0 ? void 0 : _this3$node.emit(AudioSourceEventType.ENDED, _this3);
            });
            player.onInterruptionBegin(function () {
              audioManager.removePlaying(player);
            });
            player.onInterruptionEnd(function () {
              if (_this3._player === player) {
                audioManager.addPlaying(player);
              }
            });
            this._hasRegisterListener = true;
          }
        };
        _proto._unregisterListener = function _unregisterListener() {
          if (this._player && this._hasRegisterListener) {
            this._player.offEnded();
            this._player.offInterruptionBegin();
            this._player.offInterruptionEnd();
            this._hasRegisterListener = false;
          }
        };
        _proto.onLoad = function onLoad() {
          this._syncPlayer();
        };
        _proto.onEnable = function onEnable() {
          if (this._playOnAwake && !this.playing) {
            this.play();
          }
        };
        _proto.onDisable = function onDisable() {
          var rootNode = this._getRootNode();
          if (rootNode !== null && rootNode !== void 0 && rootNode._persistNode) {
            return;
          }
          this.pause();
        };
        _proto.onDestroy = function onDestroy() {
          this.stop();
          this.clip = null;
        };
        _proto.getPCMData = function getPCMData(channelIndex) {
          var _this4 = this;
          return new Promise(function (resolve) {
            if (channelIndex !== 0 && channelIndex !== 1) {
              console.warn('Only support channel index 0 or 1 to get buffer');
              resolve(undefined);
              return;
            }
            if (_this4._player) {
              resolve(_this4._player.getPCMData(channelIndex));
            } else {
              var _this4$node;
              (_this4$node = _this4.node) === null || _this4$node === void 0 ? void 0 : _this4$node.once(_LOADED_EVENT, function () {
                var _this4$_player;
                resolve((_this4$_player = _this4._player) === null || _this4$_player === void 0 ? void 0 : _this4$_player.getPCMData(channelIndex));
              });
            }
          });
        };
        _proto.getSampleRate = function getSampleRate() {
          var _this5 = this;
          return new Promise(function (resolve) {
            if (_this5._player) {
              resolve(_this5._player.sampleRate);
            } else {
              var _this5$node;
              (_this5$node = _this5.node) === null || _this5$node === void 0 ? void 0 : _this5$node.once(_LOADED_EVENT, function () {
                resolve(_this5._player.sampleRate);
              });
            }
          });
        };
        _proto._getRootNode = function _getRootNode() {
          var _currentNode, _currentNode$parent;
          var currentNode = this.node;
          var currentGrandparentNode = (_currentNode = currentNode) === null || _currentNode === void 0 ? void 0 : (_currentNode$parent = _currentNode.parent) === null || _currentNode$parent === void 0 ? void 0 : _currentNode$parent.parent;
          while (currentGrandparentNode) {
            var _currentNode2, _currentNode3, _currentNode3$parent;
            currentNode = (_currentNode2 = currentNode) === null || _currentNode2 === void 0 ? void 0 : _currentNode2.parent;
            currentGrandparentNode = (_currentNode3 = currentNode) === null || _currentNode3 === void 0 ? void 0 : (_currentNode3$parent = _currentNode3.parent) === null || _currentNode3$parent === void 0 ? void 0 : _currentNode3$parent.parent;
          }
          return currentNode;
        };
        _proto.play = function play() {
          var _this6 = this;
          if (!this._isLoaded && this.clip) {
            this._operationsBeforeLoading.push({
              op: AudioOperationType.PLAY,
              params: null
            });
            return;
          }
          this._registerListener();
          audioManager.discardOnePlayingIfNeeded();
          if (this.state === AudioState.PLAYING) {
            var _this$_player;
            (_this$_player = this._player) === null || _this$_player === void 0 ? void 0 : _this$_player.stop()["catch"](function (e) {});
          }
          var player = this._player;
          if (player) {
            player.play().then(function () {
              var _this6$node;
              (_this6$node = _this6.node) === null || _this6$node === void 0 ? void 0 : _this6$node.emit(AudioSourceEventType.STARTED, _this6);
            })["catch"](function (e) {
              audioManager.removePlaying(player);
            });
            audioManager.addPlaying(player);
          }
        };
        _proto.pause = function pause() {
          var _this$_player2;
          if (!this._isLoaded && this.clip) {
            this._operationsBeforeLoading.push({
              op: AudioOperationType.PAUSE,
              params: null
            });
            return;
          }
          (_this$_player2 = this._player) === null || _this$_player2 === void 0 ? void 0 : _this$_player2.pause()["catch"](function (e) {});
        };
        _proto.stop = function stop() {
          if (!this._isLoaded && this.clip) {
            this._operationsBeforeLoading.push({
              op: AudioOperationType.STOP,
              params: null
            });
            return;
          }
          if (this._player) {
            this._player.stop()["catch"](function (e) {});
            audioManager.removePlaying(this._player);
          }
        };
        _proto.playOneShot = function playOneShot(clip, volumeScale) {
          if (volumeScale === void 0) {
            volumeScale = 1;
          }
          if (!clip._nativeAsset) {
            console.error('Invalid audio clip');
            return;
          }
          var player;
          AudioPlayer.loadOneShotAudio(clip._nativeAsset.url, this._volume * volumeScale, {
            audioLoadMode: clip.loadMode
          }).then(function (oneShotAudio) {
            player = oneShotAudio;
            audioManager.discardOnePlayingIfNeeded();
            oneShotAudio.onEnd = function () {
              audioManager.removePlaying(oneShotAudio);
            };
            oneShotAudio.play();
            audioManager.addPlaying(oneShotAudio);
          })["catch"](function (e) {
            if (player) {
              audioManager.removePlaying(player);
            }
          });
        };
        _proto._syncStates = function _syncStates() {
          var _this7 = this;
          if (this._player) {
            this._player.loop = this._loop;
            this._player.volume = this._volume;
            this._operationsBeforeLoading.forEach(function (opInfo) {
              if (opInfo.op === AudioOperationType.SEEK) {
                _this7._cachedCurrentTime = opInfo.params && opInfo.params[0];
                if (_this7._player) {
                  _this7._player.seek(_this7._cachedCurrentTime)["catch"](function (e) {});
                }
              } else {
                var _this7$opInfo$op;
                (_this7$opInfo$op = _this7[opInfo.op]) === null || _this7$opInfo$op === void 0 ? void 0 : _this7$opInfo$op.call(_this7);
              }
            });
            this._operationsBeforeLoading.length = 0;
          }
        };
        _createClass(AudioSource, [{
          key: "clip",
          get: function get() {
            return this._clip;
          },
          set: function set(val) {
            if (val === this._clip) {
              return;
            }
            this._clip = val;
            this._syncPlayer();
          }
        }, {
          key: "loop",
          get: function get() {
            return this._loop;
          },
          set: function set(val) {
            this._loop = val;
            if (this._player) {
              this._player.loop = val;
            }
          }
        }, {
          key: "playOnAwake",
          get: function get() {
            return this._playOnAwake;
          },
          set: function set(val) {
            this._playOnAwake = val;
          }
        }, {
          key: "volume",
          get: function get() {
            return this._volume;
          },
          set: function set(val) {
            if (Number.isNaN(val)) {
              console.warn('illegal audio volume!');
              return;
            }
            val = clamp$1(val, 0, 1);
            if (this._player) {
              this._player.volume = val;
              this._volume = this._player.volume;
            } else {
              this._volume = val;
            }
          }
        }, {
          key: "currentTime",
          get: function get() {
            return this._player ? this._player.currentTime : this._cachedCurrentTime < 0 ? 0 : this._cachedCurrentTime;
          },
          set: function set(num) {
            var _this$_player3;
            if (Number.isNaN(num)) {
              console.warn('illegal audio time!');
              return;
            }
            num = clamp$1(num, 0, this.duration);
            if (!this._isLoaded && this.clip) {
              this._operationsBeforeLoading.push({
                op: AudioOperationType.SEEK,
                params: [num]
              });
              return;
            }
            this._cachedCurrentTime = num;
            (_this$_player3 = this._player) === null || _this$_player3 === void 0 ? void 0 : _this$_player3.seek(this._cachedCurrentTime)["catch"](function (e) {});
          }
        }, {
          key: "duration",
          get: function get() {
            var _this$_clip$getDurati, _this$_clip;
            return (_this$_clip$getDurati = (_this$_clip = this._clip) === null || _this$_clip === void 0 ? void 0 : _this$_clip.getDuration()) !== null && _this$_clip$getDurati !== void 0 ? _this$_clip$getDurati : this._player ? this._player.duration : 0;
          }
        }, {
          key: "state",
          get: function get() {
            return this._player ? this._player.state : AudioState.INIT;
          }
        }, {
          key: "playing",
          get: function get() {
            return this.state === AudioSource.AudioState.PLAYING;
          }
        }], [{
          key: "maxAudioChannel",
          get: function get() {
            return AudioPlayer.maxAudioChannel;
          }
        }]);
        return AudioSource;
      }(Component), _class3$i.AudioState = AudioState, _class3$i.EventType = AudioSourceEventType, _class3$i), (_initializer$C = applyDecoratedInitializer(_class2$D.prototype, "_clip", [_dec2$D], function () {
        return null;
      }), _initializer2$z = applyDecoratedInitializer(_class2$D.prototype, "_loop", [serializable$j], function () {
        return false;
      }), _initializer3$p = applyDecoratedInitializer(_class2$D.prototype, "_playOnAwake", [serializable$j], function () {
        return true;
      }), _initializer4$j = applyDecoratedInitializer(_class2$D.prototype, "_volume", [serializable$j], function () {
        return 1;
      }), _applyDecoratedDescriptor(_class2$D.prototype, "clip", [_dec3$s], Object.getOwnPropertyDescriptor(_class2$D.prototype, "clip"), _class2$D.prototype)), _class2$D)) || _class$F));

      legacyCC.AudioSourceComponent = AudioSource;
      setClassAlias(AudioSource, 'cc.AudioSourceComponent');

      legacyCC.log = log;
      legacyCC.warn = warn;
      legacyCC.error = error;
      legacyCC.assert = assert;
      legacyCC._throw = _throw;
      legacyCC.logID = logID;
      legacyCC.warnID = warnID;
      legacyCC.errorID = errorID;
      legacyCC.assertID = assertID;
      legacyCC.debug = debug$1;
      legacyCC.path = {
        join: join,
        extname: extname,
        mainFileName: mainFileName,
        basename: basename,
        dirname: dirname,
        changeExtname: changeExtname,
        changeBasename: changeBasename,
        _normalize: _normalize,
        stripSep: stripSep,
        get sep() {
          return getSeperator();
        }
      };

      function isUICamera(camera) {
        var scene = camera.scene;
        var batches = scene.batches;
        for (var i = 0; batches && i < batches.length; i++) {
          var batch = batches[i];
          if (camera.visibility & batch.visFlags) {
            return true;
          }
        }
        return false;
      }

      var CameraInfo = function CameraInfo(camera, id, windowID, width, height) {
        this.camera = void 0;
        this.id = 0xFFFFFFFF;
        this.windowID = 0xFFFFFFFF;
        this.width = 0;
        this.height = 0;
        this.camera = camera;
        this.id = id;
        this.windowID = windowID;
        this.width = width;
        this.height = height;
      };
      var cameraInfos = new Map();
      var windowInfos = new Map();
      function prepareRenderWindow(camera) {
        var windowID = windowInfos.get(camera.window);
        if (windowID === undefined) {
          windowID = windowInfos.size;
          windowInfos.set(camera.window, windowID);
        }
        return windowID;
      }
      function prepareResource(ppl, camera, initResourceFunc, updateResourceFunc) {
        var info = cameraInfos.get(camera);
        if (info !== undefined) {
          camera.window.width;
          camera.window.height;
          prepareRenderWindow(camera);
          updateResourceFunc(ppl, info);
          return info;
        }
        var windowID = prepareRenderWindow(camera);
        info = new CameraInfo(camera, cameraInfos.size, windowID, camera.window.width ? camera.window.width : 1, camera.window.height ? camera.window.height : 1);
        initResourceFunc(ppl, info);
        cameraInfos.set(camera, info);
        return info;
      }
      function buildShadowRes(ppl, name, width, height) {
        var fboW = width;
        var fboH = height;
        var shadowMapName = name;
        var device = ppl.device;
        if (!ppl.containsResource(shadowMapName)) {
          var format = supportsR32FloatTexture(device) ? Format.R32F : Format.RGBA8;
          ppl.addRenderTarget(shadowMapName, format, fboW, fboH, ResourceResidency.MANAGED);
          ppl.addDepthStencil(shadowMapName + "Depth", Format.DEPTH_STENCIL, fboW, fboH, ResourceResidency.MANAGED);
        }
        ppl.updateRenderTarget(shadowMapName, fboW, fboH);
        ppl.updateDepthStencil(shadowMapName + "Depth", fboW, fboH);
      }
      var shadowInfo = new ShadowInfo();
      function setupShadowRes(ppl, cameraInfo) {
        var camera = cameraInfo.camera;
        validPunctualLightsCulling(ppl, camera);
        var pipeline = ppl;
        var shadow = pipeline.pipelineSceneData.shadows;
        var validPunctualLights = ppl.pipelineSceneData.validPunctualLights;
        var shadows = ppl.pipelineSceneData.shadows;
        shadowInfo.reset();
        if (!shadow.enabled || shadow.type !== ShadowType.ShadowMap) {
          return shadowInfo;
        }
        shadowInfo.shadowEnabled = true;
        var _validLights = shadowInfo.validLights;
        var n = 0;
        var m = 0;
        for (; n < shadow.maxReceived && m < validPunctualLights.length;) {
          var light = validPunctualLights[m];
          if (light.type === LightType.SPOT) {
            var spotLight = light;
            if (spotLight.shadowEnabled) {
              _validLights.push(light);
              n++;
            }
          }
          m++;
        }
        var _ref = camera.scene,
          mainLight = _ref.mainLight;
        var mapWidth = shadows.size.x;
        var mapHeight = shadows.size.y;
        if (mainLight && mainLight.shadowEnabled) {
          shadowInfo.mainLightShadowNames[0] = "MainLightShadow" + cameraInfo.id;
          if (mainLight.shadowFixedArea) {
            buildShadowRes(ppl, shadowInfo.mainLightShadowNames[0], mapWidth, mapHeight);
          } else {
            var csmLevel = pipeline.pipelineSceneData.csmSupported ? mainLight.csmLevel : 1;
            shadowInfo.mainLightShadowNames[0] = "MainLightShadow" + cameraInfo.id;
            for (var i = 0; i < csmLevel; i++) {
              buildShadowRes(ppl, shadowInfo.mainLightShadowNames[0], mapWidth, mapHeight);
            }
          }
        }
        for (var l = 0; l < _validLights.length; l++) {
          _validLights[l];
          var passName = "SpotLightShadow" + l.toString() + cameraInfo.id;
          shadowInfo.spotLightShadowNames[l] = passName;
          buildShadowRes(ppl, shadowInfo.spotLightShadowNames[l], mapWidth, mapHeight);
        }
        return shadowInfo;
      }
      var updateShadowRes = setupShadowRes;
      var shadowPass;
      function buildShadowPass(passName, ppl, camera, light, level, width, height) {
        var fboW = width;
        var fboH = height;
        var area = getRenderArea(camera, width, height, light, level);
        width = area.width;
        height = area.height;
        var shadowMapName = passName;
        if (!level) {
          shadowPass = ppl.addRenderPass(width, height, 'default');
          shadowPass.name = passName;
          shadowPass.setViewport(new Viewport(0, 0, fboW, fboH));
          shadowPass.addRenderTarget(shadowMapName, LoadOp.CLEAR, StoreOp.STORE, new Color(1, 1, 1, camera.clearColor.w));
          shadowPass.addDepthStencil(shadowMapName + "Depth", LoadOp.CLEAR, StoreOp.DISCARD, camera.clearDepth, camera.clearStencil, ClearFlagBit.DEPTH_STENCIL);
        }
        var queue = shadowPass.addQueue(QueueHint.RENDER_OPAQUE, 'shadow-caster');
        queue.addSceneOfCamera(camera, new LightInfo(light, level), SceneFlags.SHADOW_CASTER);
        queue.setViewport(new Viewport(area.x, area.y, area.width, area.height));
      }
      function setupShadowPass(ppl, cameraInfo) {
        if (!shadowInfo.shadowEnabled) return;
        var camera = cameraInfo.camera;
        var shadows = ppl.pipelineSceneData.shadows;
        var mapWidth = shadows.size.x;
        var mapHeight = shadows.size.y;
        var _ref2 = camera.scene,
          mainLight = _ref2.mainLight;
        if (mainLight && mainLight.shadowEnabled) {
          shadowInfo.mainLightShadowNames[0] = "MainLightShadow" + cameraInfo.id;
          if (mainLight.shadowFixedArea) {
            buildShadowPass(shadowInfo.mainLightShadowNames[0], ppl, camera, mainLight, 0, mapWidth, mapHeight);
          } else {
            var csmLevel = ppl.pipelineSceneData.csmSupported ? mainLight.csmLevel : 1;
            shadowInfo.mainLightShadowNames[0] = "MainLightShadow" + cameraInfo.id;
            for (var i = 0; i < csmLevel; i++) {
              buildShadowPass(shadowInfo.mainLightShadowNames[0], ppl, camera, mainLight, i, mapWidth, mapHeight);
            }
          }
        }
        for (var l = 0; l < shadowInfo.validLights.length; l++) {
          var light = shadowInfo.validLights[l];
          var passName = "SpotLightShadow" + l.toString() + cameraInfo.id;
          shadowInfo.spotLightShadowNames[l] = passName;
          buildShadowPass(passName, ppl, camera, light, 0, mapWidth, mapHeight);
        }
      }
      function setupForwardRes(ppl, cameraInfo, isOffScreen) {
        if (isOffScreen === void 0) {
          isOffScreen = false;
        }
        var camera = cameraInfo.camera;
        var area = getRenderArea(camera, camera.window.width, camera.window.height);
        var width = area.width;
        var height = area.height;
        setupShadowRes(ppl, cameraInfo);
        if (!isOffScreen) {
          ppl.addRenderWindow("ForwardColor" + cameraInfo.id, Format.BGRA8, width, height, cameraInfo.camera.window);
        } else {
          ppl.addRenderTarget("ForwardColor" + cameraInfo.id, getRTFormatBeforeToneMapping(ppl), width, height, ResourceResidency.PERSISTENT);
        }
        ppl.addDepthStencil("ForwardDepthStencil" + cameraInfo.id, Format.DEPTH_STENCIL, width, height);
      }
      function updateForwardRes(ppl, cameraInfo, isOffScreen) {
        if (isOffScreen === void 0) {
          isOffScreen = false;
        }
        var camera = cameraInfo.camera;
        var area = getRenderArea(camera, camera.window.width, camera.window.height);
        var width = area.width;
        var height = area.height;
        updateShadowRes(ppl, cameraInfo);
        if (!isOffScreen) {
          ppl.updateRenderWindow("ForwardColor" + cameraInfo.id, cameraInfo.camera.window);
        } else {
          ppl.updateRenderTarget("ForwardColor" + cameraInfo.id, width, height);
        }
        ppl.updateDepthStencil("ForwardDepthStencil" + cameraInfo.id, width, height);
      }
      function setupDeferredForward(ppl, cameraInfo, inputColor) {
        var area = getRenderArea(cameraInfo.camera, cameraInfo.camera.window.width, cameraInfo.camera.window.height);
        var width = area.width;
        var height = area.height;
        var forwardPass = ppl.addRenderPass(width, height, 'default');
        var camera = cameraInfo.camera;
        forwardPass.addRenderTarget(inputColor, LoadOp.LOAD, StoreOp.STORE);
        forwardPass.addDepthStencil(gBufferInfo.ds, LoadOp.LOAD, StoreOp.DISCARD);
        for (var _iterator = _createForOfIteratorHelperLoose(shadowInfo.mainLightShadowNames), _step; !(_step = _iterator()).done;) {
          var dirShadowName = _step.value;
          if (ppl.containsResource(dirShadowName)) {
            forwardPass.addTexture(dirShadowName, 'cc_shadowMap');
          }
        }
        for (var _iterator2 = _createForOfIteratorHelperLoose(shadowInfo.spotLightShadowNames), _step2; !(_step2 = _iterator2()).done;) {
          var spotShadowName = _step2.value;
          if (ppl.containsResource(spotShadowName)) {
            forwardPass.addTexture(spotShadowName, 'cc_spotShadowMap');
          }
        }
        forwardPass.addQueue(QueueHint.RENDER_OPAQUE, 'deferred-forward').addSceneOfCamera(camera, new LightInfo(), SceneFlags.OPAQUE_OBJECT | SceneFlags.PLANAR_SHADOW | SceneFlags.CUTOUT_OBJECT | SceneFlags.DEFAULT_LIGHTING | SceneFlags.DRAW_INSTANCING);
        forwardPass.addQueue(QueueHint.RENDER_TRANSPARENT, 'deferred-forward').addSceneOfCamera(camera, new LightInfo(), SceneFlags.TRANSPARENT_OBJECT | SceneFlags.GEOMETRY);
      }
      function setupForwardPass(ppl, cameraInfo, isOffScreen, enabledAlpha) {
        if (isOffScreen === void 0) {
          isOffScreen = false;
        }
        if (enabledAlpha === void 0) {
          enabledAlpha = true;
        }
        setupShadowPass(ppl, cameraInfo);
        var cameraID = cameraInfo.id;
        var area = getRenderArea(cameraInfo.camera, cameraInfo.camera.window.width, cameraInfo.camera.window.height);
        var width = area.width;
        var height = area.height;
        var forwardPass = ppl.addRenderPass(width, height, 'default');
        forwardPass.name = "ForwardPass" + cameraID;
        forwardPass.setViewport(new Viewport(area.x, area.y, width, height));
        for (var _iterator3 = _createForOfIteratorHelperLoose(shadowInfo.mainLightShadowNames), _step3; !(_step3 = _iterator3()).done;) {
          var dirShadowName = _step3.value;
          if (ppl.containsResource(dirShadowName)) {
            forwardPass.addTexture(dirShadowName, 'cc_shadowMap');
          }
        }
        for (var _iterator4 = _createForOfIteratorHelperLoose(shadowInfo.spotLightShadowNames), _step4; !(_step4 = _iterator4()).done;) {
          var spotShadowName = _step4.value;
          if (ppl.containsResource(spotShadowName)) {
            forwardPass.addTexture(spotShadowName, 'cc_spotShadowMap');
          }
        }
        var camera = cameraInfo.camera;
        forwardPass.addRenderTarget("ForwardColor" + cameraInfo.id, isOffScreen ? LoadOp.CLEAR : getLoadOpOfClearFlag(camera.clearFlag, AttachmentType.RENDER_TARGET), StoreOp.STORE, new Color(camera.clearColor.x, camera.clearColor.y, camera.clearColor.z, camera.clearColor.w));
        forwardPass.addDepthStencil("ForwardDepthStencil" + cameraInfo.id, isOffScreen ? LoadOp.CLEAR : getLoadOpOfClearFlag(camera.clearFlag, AttachmentType.DEPTH_STENCIL), isOffScreen ? StoreOp.DISCARD : StoreOp.STORE, camera.clearDepth, camera.clearStencil, camera.clearFlag);
        forwardPass.addQueue(QueueHint.RENDER_OPAQUE).addSceneOfCamera(camera, new LightInfo(), SceneFlags.OPAQUE_OBJECT | SceneFlags.PLANAR_SHADOW | SceneFlags.CUTOUT_OBJECT | SceneFlags.DEFAULT_LIGHTING | SceneFlags.DRAW_INSTANCING);
        var sceneFlags = SceneFlags.TRANSPARENT_OBJECT | SceneFlags.GEOMETRY;
        if (!isOffScreen) {
          sceneFlags |= SceneFlags.UI;
          forwardPass.showStatistics = true;
        }
        if (enabledAlpha) {
          forwardPass.addQueue(QueueHint.RENDER_TRANSPARENT).addSceneOfCamera(camera, new LightInfo(), sceneFlags);
        }
        return {
          rtName: "ForwardColor" + cameraInfo.id,
          dsName: "ForwardDepthStencil" + cameraInfo.id
        };
      }
      var gBufferInfo = new GBufferInfo();
      function setupGBufferRes(ppl, info) {
        var camera = info.camera;
        var area = getRenderArea(camera, camera.window.width, camera.window.height);
        var width = area.width;
        var height = area.height;
        var gBufferPassRTName = "gBufferPassColorCamera" + info.id;
        var gBufferPassNormal = "gBufferPassNormal" + info.id;
        var gBufferPassEmissive = "gBufferPassEmissive" + info.id;
        var gBufferPassDSName = "gBufferPassDSCamera" + info.id;
        var colFormat = Format.RGBA16F;
        ppl.addRenderTarget(gBufferPassRTName, colFormat, width, height, ResourceResidency.MANAGED);
        ppl.addRenderTarget(gBufferPassEmissive, colFormat, width, height, ResourceResidency.MANAGED);
        ppl.addRenderTarget(gBufferPassNormal, colFormat, width, height, ResourceResidency.MANAGED);
        ppl.addDepthStencil(gBufferPassDSName, Format.DEPTH_STENCIL, width, height, ResourceResidency.MANAGED);
        gBufferInfo.color = gBufferPassRTName;
        gBufferInfo.normal = gBufferPassNormal;
        gBufferInfo.emissive = gBufferPassEmissive;
        gBufferInfo.ds = gBufferPassDSName;
      }
      function updateGBufferRes(ppl, info) {
        var camera = info.camera;
        var area = getRenderArea(camera, camera.window.width, camera.window.height);
        var width = area.width;
        var height = area.height;
        var gBufferPassRTName = "gBufferPassColorCamera" + info.id;
        var gBufferPassNormal = "gBufferPassNormal" + info.id;
        var gBufferPassEmissive = "gBufferPassEmissive" + info.id;
        var gBufferPassDSName = "gBufferPassDSCamera" + info.id;
        ppl.updateRenderTarget(gBufferPassRTName, width, height);
        ppl.updateRenderTarget(gBufferPassEmissive, width, height);
        ppl.updateRenderTarget(gBufferPassNormal, width, height);
        ppl.updateDepthStencil(gBufferPassDSName, width, height);
      }
      new Color(0, 0, 0, 0);
      function setupGBufferPass(ppl, info) {
        var camera = info.camera;
        var area = getRenderArea(camera, camera.window.width, camera.window.height);
        var width = area.width;
        var height = area.height;
        var gBufferPassRTName = gBufferInfo.color;
        var gBufferPassNormal = gBufferInfo.normal;
        var gBufferPassEmissive = gBufferInfo.emissive;
        var gBufferPassDSName = gBufferInfo.ds;
        var gBufferPass = ppl.addRenderPass(width, height, 'gbuffer');
        gBufferPass.name = "CameraGBufferPass" + info.id;
        gBufferPass.setViewport(new Viewport(area.x, area.y, width, height));
        var rtColor = new Color(0, 0, 0, 0);
        if (camera.clearFlag & ClearFlagBit.COLOR) {
          if (ppl.pipelineSceneData.isHDR) {
            SRGBToLinear(rtColor, camera.clearColor);
          } else {
            rtColor.x = camera.clearColor.x;
            rtColor.y = camera.clearColor.y;
            rtColor.z = camera.clearColor.z;
          }
        }
        gBufferPass.addRenderTarget(gBufferPassRTName, LoadOp.CLEAR, StoreOp.STORE, rtColor);
        gBufferPass.addRenderTarget(gBufferPassEmissive, LoadOp.CLEAR, StoreOp.STORE, new Color(0, 0, 0, 0));
        gBufferPass.addRenderTarget(gBufferPassNormal, LoadOp.CLEAR, StoreOp.STORE, new Color(0, 0, 0, 0));
        gBufferPass.addDepthStencil(gBufferPassDSName, LoadOp.CLEAR, StoreOp.STORE, camera.clearDepth, camera.clearStencil, camera.clearFlag);
        gBufferPass.addQueue(QueueHint.RENDER_OPAQUE, 'gbuffer').addSceneOfCamera(camera, new LightInfo(), SceneFlags.OPAQUE_OBJECT | SceneFlags.CUTOUT_OBJECT);
        return gBufferPass;
      }
      function setupLightingRes(ppl, info) {
        setupShadowRes(ppl, info);
        var camera = info.camera;
        var area = getRenderArea(camera, camera.window.width, camera.window.height);
        var width = area.width;
        var height = area.height;
        var deferredLightingPassRTName = "deferredLightingPassRTName" + info.id;
        ppl.addRenderTarget(deferredLightingPassRTName, Format.RGBA8, width, height, ResourceResidency.MANAGED);
      }
      function updateLightingRes(ppl, info) {
        updateShadowRes(ppl, info);
        var camera = info.camera;
        var area = getRenderArea(camera, camera.window.width, camera.window.height);
        var width = area.width;
        var height = area.height;
        var deferredLightingPassRTName = "deferredLightingPassRTName" + info.id;
        ppl.updateRenderTarget(deferredLightingPassRTName, width, height);
      }
      var lightingInfo;
      function setupLightingPass(pipeline, info, useCluster) {
        setupShadowPass(pipeline, info);
        if (!lightingInfo) {
          lightingInfo = new LightingInfo(useCluster);
        }
        var ppl = pipeline;
        var camera = info.camera;
        var area = getRenderArea(camera, camera.window.width, camera.window.height);
        var width = area.width;
        var height = area.height;
        var cameraID = getCameraUniqueID(camera);
        var deferredLightingPassRTName = "deferredLightingPassRTName" + info.id;
        var lightingPass = ppl.addRenderPass(width, height, 'deferred-lighting');
        lightingPass.name = "CameraLightingPass" + info.id;
        lightingPass.setViewport(new Viewport(area.x, area.y, width, height));
        for (var _iterator5 = _createForOfIteratorHelperLoose(shadowInfo.mainLightShadowNames), _step5; !(_step5 = _iterator5()).done;) {
          var dirShadowName = _step5.value;
          if (ppl.containsResource(dirShadowName)) {
            lightingPass.addTexture(dirShadowName, 'cc_shadowMap');
          }
        }
        for (var _iterator6 = _createForOfIteratorHelperLoose(shadowInfo.spotLightShadowNames), _step6; !(_step6 = _iterator6()).done;) {
          var spotShadowName = _step6.value;
          if (ppl.containsResource(spotShadowName)) {
            lightingPass.addTexture(spotShadowName, 'cc_spotShadowMap');
          }
        }
        if (ppl.containsResource(gBufferInfo.color)) {
          lightingPass.addTexture(gBufferInfo.color, 'albedoMap');
          lightingPass.addTexture(gBufferInfo.normal, 'normalMap');
          lightingPass.addTexture(gBufferInfo.emissive, 'emissiveMap');
          lightingPass.addTexture(gBufferInfo.ds, 'depthStencil');
        }
        var clusterLightBufferName = "clusterLightBuffer" + cameraID;
        var clusterLightIndicesBufferName = "clusterLightIndicesBuffer" + cameraID;
        var clusterLightGridBufferName = "clusterLightGridBuffer" + cameraID;
        if (ppl.containsResource(clusterLightBufferName)) {
          lightingPass.addStorageBuffer(clusterLightBufferName, AccessType.READ, 'b_ccLightsBuffer');
          lightingPass.addStorageBuffer(clusterLightIndicesBufferName, AccessType.READ, 'b_clusterLightIndicesBuffer');
          lightingPass.addStorageBuffer(clusterLightGridBufferName, AccessType.READ, 'b_clusterLightGridBuffer');
        }
        var lightingClearColor = new Color(0, 0, 0, 0);
        if (camera.clearFlag & ClearFlagBit.COLOR) {
          lightingClearColor.x = camera.clearColor.x;
          lightingClearColor.y = camera.clearColor.y;
          lightingClearColor.z = camera.clearColor.z;
        }
        lightingClearColor.w = 0;
        lightingPass.addRenderTarget(deferredLightingPassRTName, LoadOp.CLEAR, StoreOp.STORE, lightingClearColor);
        lightingPass.addQueue(QueueHint.RENDER_TRANSPARENT).addCameraQuad(camera, lightingInfo.deferredLightingMaterial, 0, SceneFlags.VOLUMETRIC_LIGHTING);
        return {
          rtName: deferredLightingPassRTName
        };
      }
      function setupPostprocessRes(ppl, info) {
        var cameraID = info.id;
        var camera = info.camera;
        var area = getRenderArea(camera, camera.window.width, camera.window.height);
        var width = area.width;
        var height = area.height;
        var postprocessPassRTName = "postprocessPassRTName" + cameraID;
        var postprocessPassDS = "postprocessPassDS" + cameraID;
        ppl.addRenderWindow(postprocessPassRTName, Format.BGRA8, width, height, camera.window);
        ppl.addDepthStencil(postprocessPassDS, Format.DEPTH_STENCIL, width, height, ResourceResidency.MANAGED);
      }
      function updatePostprocessRes(ppl, info) {
        var cameraID = info.id;
        var camera = info.camera;
        var area = getRenderArea(camera, camera.window.width, camera.window.height);
        var width = area.width;
        var height = area.height;
        var postprocessPassRTName = "postprocessPassRTName" + cameraID;
        var postprocessPassDS = "postprocessPassDS" + cameraID;
        ppl.updateRenderWindow(postprocessPassRTName, camera.window);
        ppl.updateDepthStencil(postprocessPassDS, width, height);
      }
      var postInfo;
      function setupPostprocessPass(ppl, info, inputTex) {
        if (!postInfo) {
          postInfo = new PostInfo();
        }
        var cameraID = info.id;
        var camera = info.camera;
        var area = getRenderArea(camera, camera.window.width, camera.window.height);
        var width = area.width;
        var height = area.height;
        var postprocessPassRTName = "postprocessPassRTName" + cameraID;
        var postprocessPassDS = "postprocessPassDS" + cameraID;
        var postprocessPass = ppl.addRenderPass(width, height, 'post-process');
        postprocessPass.name = "CameraPostprocessPass" + cameraID;
        postprocessPass.setViewport(new Viewport(area.x, area.y, area.width, area.height));
        if (ppl.containsResource(inputTex)) {
          postprocessPass.addTexture(inputTex, 'outputResultMap');
        }
        var postClearColor = new Color(0, 0, 0, camera.clearColor.w);
        if (camera.clearFlag & ClearFlagBit.COLOR) {
          postClearColor.x = camera.clearColor.x;
          postClearColor.y = camera.clearColor.y;
          postClearColor.z = camera.clearColor.z;
        }
        postprocessPass.addRenderTarget(postprocessPassRTName, getLoadOpOfClearFlag(camera.clearFlag, AttachmentType.RENDER_TARGET), StoreOp.STORE, postClearColor);
        postprocessPass.addDepthStencil(postprocessPassDS, getLoadOpOfClearFlag(camera.clearFlag, AttachmentType.DEPTH_STENCIL), StoreOp.STORE, camera.clearDepth, camera.clearStencil, camera.clearFlag);
        postprocessPass.addQueue(QueueHint.NONE).addCameraQuad(camera, postInfo.postMaterial, 0, SceneFlags.NONE);
        if (getProfilerCamera() === camera) {
          postprocessPass.showStatistics = true;
        }
        return {
          rtName: postprocessPassRTName,
          dsName: postprocessPassDS
        };
      }
      function setupUIRes(ppl, info) {
        var camera = info.camera;
        var area = getRenderArea(camera, camera.window.width, camera.window.height);
        var width = area.width;
        var height = area.height;
        var dsUIAndProfilerPassRTName = "dsUIAndProfilerPassColor" + info.id;
        var dsUIAndProfilerPassDSName = "dsUIAndProfilerPassDS" + info.id;
        ppl.addRenderWindow(dsUIAndProfilerPassRTName, Format.BGRA8, width, height, camera.window);
        ppl.addDepthStencil(dsUIAndProfilerPassDSName, Format.DEPTH_STENCIL, width, height, ResourceResidency.MANAGED);
      }
      function updateUIRes(ppl, info) {
        var camera = info.camera;
        var area = getRenderArea(camera, camera.window.width, camera.window.height);
        var width = area.width;
        var height = area.height;
        var dsUIAndProfilerPassRTName = "dsUIAndProfilerPassColor" + info.id;
        var dsUIAndProfilerPassDSName = "dsUIAndProfilerPassDS" + info.id;
        ppl.updateRenderWindow(dsUIAndProfilerPassRTName, camera.window);
        ppl.updateDepthStencil(dsUIAndProfilerPassDSName, width, height);
      }
      function setupUIPass(ppl, info) {
        var camera = info.camera;
        var area = getRenderArea(camera, camera.window.width, camera.window.height);
        var width = area.width;
        var height = area.height;
        var dsUIAndProfilerPassRTName = "dsUIAndProfilerPassColor" + info.id;
        var dsUIAndProfilerPassDSName = "dsUIAndProfilerPassDS" + info.id;
        var uiAndProfilerPass = ppl.addRenderPass(width, height, 'default');
        uiAndProfilerPass.name = "CameraUIAndProfilerPass" + info.id;
        uiAndProfilerPass.setViewport(new Viewport(area.x, area.y, width, height));
        uiAndProfilerPass.addRenderTarget(dsUIAndProfilerPassRTName, getLoadOpOfClearFlag(camera.clearFlag, AttachmentType.RENDER_TARGET), StoreOp.STORE, new Color(camera.clearColor.x, camera.clearColor.y, camera.clearColor.z, camera.clearColor.w));
        uiAndProfilerPass.addDepthStencil(dsUIAndProfilerPassDSName, getLoadOpOfClearFlag(camera.clearFlag, AttachmentType.DEPTH_STENCIL), StoreOp.STORE, camera.clearDepth, camera.clearStencil, camera.clearFlag);
        var sceneFlags = SceneFlags.UI;
        uiAndProfilerPass.addQueue(QueueHint.RENDER_TRANSPARENT).addSceneOfCamera(camera, new LightInfo(), sceneFlags);
        if (getProfilerCamera() === camera) {
          uiAndProfilerPass.showStatistics = true;
        }
      }

      var ForwardPipelineBuilder = exports('ds', function () {
        function ForwardPipelineBuilder() {}
        var _proto = ForwardPipelineBuilder.prototype;
        _proto.setup = function setup(cameras, ppl) {
          for (var i = 0; i < cameras.length; i++) {
            var camera = cameras[i];
            if (camera.scene === null) {
              continue;
            }
            ppl.update(camera);
            var info = prepareResource(ppl, camera, this.initResource, this.updateResource);
            setupForwardPass(ppl, info);
          }
        };
        _proto.initResource = function initResource(ppl, cameraInfo) {
          setupForwardRes(ppl, cameraInfo);
        };
        _proto.updateResource = function updateResource(ppl, cameraInfo) {
          updateForwardRes(ppl, cameraInfo);
        };
        return ForwardPipelineBuilder;
      }());
      var DeferredPipelineBuilder = exports('dt', function () {
        function DeferredPipelineBuilder() {}
        var _proto2 = DeferredPipelineBuilder.prototype;
        _proto2.setup = function setup(cameras, ppl) {
          for (var i = 0; i < cameras.length; ++i) {
            var camera = cameras[i];
            if (!camera.scene) {
              continue;
            }
            ppl.update(camera);
            var forceDisableCluster = false;
            var useCluster = !forceDisableCluster && ppl.device.hasFeature(Feature.COMPUTE_SHADER);
            var isGameView = camera.cameraUsage === CameraUsage.GAME || camera.cameraUsage === CameraUsage.GAME_VIEW;
            var info = prepareResource(ppl, camera, this.initResource, this.updateResource);
            if (!isGameView) {
              setupForwardPass(ppl, info);
              continue;
            }
            if (!isUICamera(camera)) {
              if (useCluster) {
                buildClusterPasses(camera, ppl);
              }
              setupGBufferPass(ppl, info);
              var lightInfo = setupLightingPass(ppl, info, useCluster);
              setupDeferredForward(ppl, info, lightInfo.rtName);
              setupPostprocessPass(ppl, info, lightInfo.rtName);
              continue;
            }
            setupUIPass(ppl, info);
          }
        };
        _proto2.initResource = function initResource(ppl, cameraInfo) {
          if (!isUICamera(cameraInfo.camera)) {
            setupGBufferRes(ppl, cameraInfo);
            setupLightingRes(ppl, cameraInfo);
            setupPostprocessRes(ppl, cameraInfo);
          } else {
            setupUIRes(ppl, cameraInfo);
          }
        };
        _proto2.updateResource = function updateResource(ppl, cameraInfo) {
          if (!isUICamera(cameraInfo.camera)) {
            updateGBufferRes(ppl, cameraInfo);
            updateLightingRes(ppl, cameraInfo);
            updatePostprocessRes(ppl, cameraInfo);
          } else {
            updateUIRes(ppl, cameraInfo);
          }
        };
        return DeferredPipelineBuilder;
      }());

      var NodePool = exports('em', function () {
        function NodePool(poolHandlerComp) {
          this.poolHandlerComp = void 0;
          this._pool = void 0;
          this.poolHandlerComp = poolHandlerComp;
          this._pool = [];
        }
        var _proto = NodePool.prototype;
        _proto.size = function size() {
          return this._pool.length;
        };
        _proto.clear = function clear() {
          var count = this._pool.length;
          for (var i = 0; i < count; ++i) {
            this._pool[i].destroy();
          }
          this._pool.length = 0;
        };
        _proto.put = function put(obj) {
          if (obj && this._pool.indexOf(obj) === -1) {
            obj.removeFromParent();
            var handler = this.poolHandlerComp ? obj.getComponent(this.poolHandlerComp) : null;
            if (handler && handler.unuse) {
              handler.unuse();
            }
            this._pool.push(obj);
          }
        };
        _proto.get = function get() {
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          var last = this._pool.length - 1;
          if (last < 0) {
            return null;
          } else {
            var obj = this._pool[last];
            this._pool.length = last;
            var handler = this.poolHandlerComp ? obj.getComponent(this.poolHandlerComp) : null;
            if (handler && handler.reuse) {
              handler.reuse(arguments);
            }
            return obj;
          }
        };
        return NodePool;
      }());
      legacyCC.NodePool = NodePool;

      var _globalThis$jsb, _globalJsb$copyTextTo;
      var globalJsb = (_globalThis$jsb = globalThis.jsb) !== null && _globalThis$jsb !== void 0 ? _globalThis$jsb : {};
      var _native = exports('eE', {
        DownloaderHints: globalJsb.DownloaderHints,
        Downloader: globalJsb.Downloader,
        zipUtils: globalJsb.zipUtils,
        fileUtils: globalJsb.fileUtils,
        DebugRenderer: globalJsb.DebugRenderer,
        copyTextToClipboard: (_globalJsb$copyTextTo = globalJsb.copyTextToClipboard) === null || _globalJsb$copyTextTo === void 0 ? void 0 : _globalJsb$copyTextTo.bind(globalJsb),
        garbageCollect: globalJsb.garbageCollect,
        reflection: globalJsb.reflection,
        bridge: globalJsb.bridge,
        jsbBridgeWrapper: globalJsb.jsbBridgeWrapper,
        AssetsManager: globalJsb.AssetsManager,
        EventAssetsManager: globalJsb.EventAssetsManager,
        Manifest: globalJsb.Manifest,
        saveImageData: globalJsb.saveImageData,
        process: globalJsb.process
      });

      legacyCC.renderer = renderer;

      var WebGLDescriptorSet = function (_DescriptorSet) {
        _inheritsLoose(WebGLDescriptorSet, _DescriptorSet);
        function WebGLDescriptorSet() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _DescriptorSet.call.apply(_DescriptorSet, [this].concat(args)) || this;
          _this._gpuDescriptorSet = null;
          return _this;
        }
        var _proto = WebGLDescriptorSet.prototype;
        _proto.initialize = function initialize(info) {
          this._layout = info.layout;
          var _gpuDescriptorSetLayo = info.layout.gpuDescriptorSetLayout,
            bindings = _gpuDescriptorSetLayo.bindings,
            descriptorIndices = _gpuDescriptorSetLayo.descriptorIndices,
            descriptorCount = _gpuDescriptorSetLayo.descriptorCount;
          this._buffers = Array(descriptorCount).fill(null);
          this._textures = Array(descriptorCount).fill(null);
          this._samplers = Array(descriptorCount).fill(null);
          var gpuDescriptors = [];
          this._gpuDescriptorSet = {
            gpuDescriptors: gpuDescriptors,
            descriptorIndices: descriptorIndices
          };
          for (var i = 0; i < bindings.length; ++i) {
            var binding = bindings[i];
            for (var j = 0; j < binding.count; j++) {
              gpuDescriptors.push({
                type: binding.descriptorType,
                gpuBuffer: null,
                gpuTexture: null,
                gpuSampler: null
              });
            }
          }
        };
        _proto.destroy = function destroy() {
          this._layout = null;
          this._gpuDescriptorSet = null;
        };
        _proto.update = function update() {
          if (this._isDirty && this._gpuDescriptorSet) {
            var descriptors = this._gpuDescriptorSet.gpuDescriptors;
            for (var i = 0; i < descriptors.length; ++i) {
              if (descriptors[i].type & DESCRIPTOR_BUFFER_TYPE) {
                var buffer = this._buffers[i];
                if (buffer) {
                  descriptors[i].gpuBuffer = buffer.gpuBuffer || buffer.gpuBufferView;
                }
              } else if (descriptors[i].type & DESCRIPTOR_SAMPLER_TYPE) {
                if (this._textures[i]) {
                  descriptors[i].gpuTexture = this._textures[i].gpuTexture;
                }
                if (this._samplers[i]) {
                  descriptors[i].gpuSampler = this._samplers[i].gpuSampler;
                }
              }
            }
            this._isDirty = false;
          }
        };
        _createClass(WebGLDescriptorSet, [{
          key: "gpuDescriptorSet",
          get: function get() {
            return this._gpuDescriptorSet;
          }
        }]);
        return WebGLDescriptorSet;
      }(DescriptorSet);

      var WebGLEXT;
      (function (WebGLEXT) {
        WebGLEXT[WebGLEXT["RGBA16F_EXT"] = 34842] = "RGBA16F_EXT";
        WebGLEXT[WebGLEXT["RGB16F_EXT"] = 34843] = "RGB16F_EXT";
        WebGLEXT[WebGLEXT["RGBA32F_EXT"] = 34836] = "RGBA32F_EXT";
        WebGLEXT[WebGLEXT["FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE_EXT"] = 33297] = "FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE_EXT";
        WebGLEXT[WebGLEXT["UNSIGNED_NORMALIZED_EXT"] = 35863] = "UNSIGNED_NORMALIZED_EXT";
        WebGLEXT[WebGLEXT["UNSIGNED_INT_24_8_WEBGL"] = 34042] = "UNSIGNED_INT_24_8_WEBGL";
        WebGLEXT[WebGLEXT["HALF_FLOAT_OES"] = 36193] = "HALF_FLOAT_OES";
        WebGLEXT[WebGLEXT["SRGB_EXT"] = 35904] = "SRGB_EXT";
        WebGLEXT[WebGLEXT["SRGB_ALPHA_EXT"] = 35906] = "SRGB_ALPHA_EXT";
        WebGLEXT[WebGLEXT["SRGB8_ALPHA8_EXT"] = 35907] = "SRGB8_ALPHA8_EXT";
        WebGLEXT[WebGLEXT["COMPRESSED_RGB_S3TC_DXT1_EXT"] = 33776] = "COMPRESSED_RGB_S3TC_DXT1_EXT";
        WebGLEXT[WebGLEXT["COMPRESSED_RGBA_S3TC_DXT1_EXT"] = 33777] = "COMPRESSED_RGBA_S3TC_DXT1_EXT";
        WebGLEXT[WebGLEXT["COMPRESSED_RGBA_S3TC_DXT3_EXT"] = 33778] = "COMPRESSED_RGBA_S3TC_DXT3_EXT";
        WebGLEXT[WebGLEXT["COMPRESSED_RGBA_S3TC_DXT5_EXT"] = 33779] = "COMPRESSED_RGBA_S3TC_DXT5_EXT";
        WebGLEXT[WebGLEXT["COMPRESSED_SRGB_S3TC_DXT1_EXT"] = 35916] = "COMPRESSED_SRGB_S3TC_DXT1_EXT";
        WebGLEXT[WebGLEXT["COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT"] = 35917] = "COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT";
        WebGLEXT[WebGLEXT["COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT"] = 35918] = "COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT";
        WebGLEXT[WebGLEXT["COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT"] = 35919] = "COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT";
        WebGLEXT[WebGLEXT["COMPRESSED_RGB_PVRTC_4BPPV1_IMG"] = 35840] = "COMPRESSED_RGB_PVRTC_4BPPV1_IMG";
        WebGLEXT[WebGLEXT["COMPRESSED_RGB_PVRTC_2BPPV1_IMG"] = 35841] = "COMPRESSED_RGB_PVRTC_2BPPV1_IMG";
        WebGLEXT[WebGLEXT["COMPRESSED_RGBA_PVRTC_4BPPV1_IMG"] = 35842] = "COMPRESSED_RGBA_PVRTC_4BPPV1_IMG";
        WebGLEXT[WebGLEXT["COMPRESSED_RGBA_PVRTC_2BPPV1_IMG"] = 35843] = "COMPRESSED_RGBA_PVRTC_2BPPV1_IMG";
        WebGLEXT[WebGLEXT["COMPRESSED_RGB_ETC1_WEBGL"] = 36196] = "COMPRESSED_RGB_ETC1_WEBGL";
        WebGLEXT[WebGLEXT["COMPRESSED_R11_EAC"] = 37488] = "COMPRESSED_R11_EAC";
        WebGLEXT[WebGLEXT["COMPRESSED_SIGNED_R11_EAC"] = 37489] = "COMPRESSED_SIGNED_R11_EAC";
        WebGLEXT[WebGLEXT["COMPRESSED_RG11_EAC"] = 37490] = "COMPRESSED_RG11_EAC";
        WebGLEXT[WebGLEXT["COMPRESSED_SIGNED_RG11_EAC"] = 37491] = "COMPRESSED_SIGNED_RG11_EAC";
        WebGLEXT[WebGLEXT["COMPRESSED_RGB8_ETC2"] = 37492] = "COMPRESSED_RGB8_ETC2";
        WebGLEXT[WebGLEXT["COMPRESSED_SRGB8_ETC2"] = 37493] = "COMPRESSED_SRGB8_ETC2";
        WebGLEXT[WebGLEXT["COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2"] = 37494] = "COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2";
        WebGLEXT[WebGLEXT["COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2"] = 37495] = "COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2";
        WebGLEXT[WebGLEXT["COMPRESSED_RGBA8_ETC2_EAC"] = 37496] = "COMPRESSED_RGBA8_ETC2_EAC";
        WebGLEXT[WebGLEXT["COMPRESSED_SRGB8_ALPHA8_ETC2_EAC"] = 37497] = "COMPRESSED_SRGB8_ALPHA8_ETC2_EAC";
        WebGLEXT[WebGLEXT["COMPRESSED_RGBA_ASTC_4x4_KHR"] = 37808] = "COMPRESSED_RGBA_ASTC_4x4_KHR";
        WebGLEXT[WebGLEXT["COMPRESSED_RGBA_ASTC_5x4_KHR"] = 37809] = "COMPRESSED_RGBA_ASTC_5x4_KHR";
        WebGLEXT[WebGLEXT["COMPRESSED_RGBA_ASTC_5x5_KHR"] = 37810] = "COMPRESSED_RGBA_ASTC_5x5_KHR";
        WebGLEXT[WebGLEXT["COMPRESSED_RGBA_ASTC_6x5_KHR"] = 37811] = "COMPRESSED_RGBA_ASTC_6x5_KHR";
        WebGLEXT[WebGLEXT["COMPRESSED_RGBA_ASTC_6x6_KHR"] = 37812] = "COMPRESSED_RGBA_ASTC_6x6_KHR";
        WebGLEXT[WebGLEXT["COMPRESSED_RGBA_ASTC_8x5_KHR"] = 37813] = "COMPRESSED_RGBA_ASTC_8x5_KHR";
        WebGLEXT[WebGLEXT["COMPRESSED_RGBA_ASTC_8x6_KHR"] = 37814] = "COMPRESSED_RGBA_ASTC_8x6_KHR";
        WebGLEXT[WebGLEXT["COMPRESSED_RGBA_ASTC_8x8_KHR"] = 37815] = "COMPRESSED_RGBA_ASTC_8x8_KHR";
        WebGLEXT[WebGLEXT["COMPRESSED_RGBA_ASTC_10x5_KHR"] = 37816] = "COMPRESSED_RGBA_ASTC_10x5_KHR";
        WebGLEXT[WebGLEXT["COMPRESSED_RGBA_ASTC_10x6_KHR"] = 37817] = "COMPRESSED_RGBA_ASTC_10x6_KHR";
        WebGLEXT[WebGLEXT["COMPRESSED_RGBA_ASTC_10x8_KHR"] = 37818] = "COMPRESSED_RGBA_ASTC_10x8_KHR";
        WebGLEXT[WebGLEXT["COMPRESSED_RGBA_ASTC_10x10_KHR"] = 37819] = "COMPRESSED_RGBA_ASTC_10x10_KHR";
        WebGLEXT[WebGLEXT["COMPRESSED_RGBA_ASTC_12x10_KHR"] = 37820] = "COMPRESSED_RGBA_ASTC_12x10_KHR";
        WebGLEXT[WebGLEXT["COMPRESSED_RGBA_ASTC_12x12_KHR"] = 37821] = "COMPRESSED_RGBA_ASTC_12x12_KHR";
        WebGLEXT[WebGLEXT["COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR"] = 37840] = "COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR";
        WebGLEXT[WebGLEXT["COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR"] = 37841] = "COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR";
        WebGLEXT[WebGLEXT["COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR"] = 37842] = "COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR";
        WebGLEXT[WebGLEXT["COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR"] = 37843] = "COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR";
        WebGLEXT[WebGLEXT["COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR"] = 37844] = "COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR";
        WebGLEXT[WebGLEXT["COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR"] = 37845] = "COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR";
        WebGLEXT[WebGLEXT["COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR"] = 37846] = "COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR";
        WebGLEXT[WebGLEXT["COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR"] = 37847] = "COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR";
        WebGLEXT[WebGLEXT["COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR"] = 37848] = "COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR";
        WebGLEXT[WebGLEXT["COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR"] = 37849] = "COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR";
        WebGLEXT[WebGLEXT["COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR"] = 37850] = "COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR";
        WebGLEXT[WebGLEXT["COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR"] = 37851] = "COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR";
        WebGLEXT[WebGLEXT["COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR"] = 37852] = "COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR";
        WebGLEXT[WebGLEXT["COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR"] = 37853] = "COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR";
      })(WebGLEXT || (WebGLEXT = {}));
      var WebGLDeviceManager = function () {
        function WebGLDeviceManager() {}
        WebGLDeviceManager.setInstance = function setInstance(instance) {
          WebGLDeviceManager._instance = instance;
        };
        _createClass(WebGLDeviceManager, null, [{
          key: "instance",
          get: function get() {
            return WebGLDeviceManager._instance;
          }
        }]);
        return WebGLDeviceManager;
      }();
      WebGLDeviceManager._instance = null;

      function GFXFormatToWebGLType$1(format, gl) {
        switch (format) {
          case Format.R8:
            return gl.UNSIGNED_BYTE;
          case Format.R8SN:
            return gl.BYTE;
          case Format.R8UI:
            return gl.UNSIGNED_BYTE;
          case Format.R8I:
            return gl.BYTE;
          case Format.R16F:
            return WebGLEXT.HALF_FLOAT_OES;
          case Format.R16UI:
            return gl.UNSIGNED_SHORT;
          case Format.R16I:
            return gl.SHORT;
          case Format.R32F:
            return gl.FLOAT;
          case Format.R32UI:
            return gl.UNSIGNED_INT;
          case Format.R32I:
            return gl.INT;
          case Format.RG8:
            return gl.UNSIGNED_BYTE;
          case Format.RG8SN:
            return gl.BYTE;
          case Format.RG8UI:
            return gl.UNSIGNED_BYTE;
          case Format.RG8I:
            return gl.BYTE;
          case Format.RG16F:
            return WebGLEXT.HALF_FLOAT_OES;
          case Format.RG16UI:
            return gl.UNSIGNED_SHORT;
          case Format.RG16I:
            return gl.SHORT;
          case Format.RG32F:
            return gl.FLOAT;
          case Format.RG32UI:
            return gl.UNSIGNED_INT;
          case Format.RG32I:
            return gl.INT;
          case Format.RGB8:
            return gl.UNSIGNED_BYTE;
          case Format.SRGB8:
            return gl.UNSIGNED_BYTE;
          case Format.RGB8SN:
            return gl.BYTE;
          case Format.RGB8UI:
            return gl.UNSIGNED_BYTE;
          case Format.RGB8I:
            return gl.BYTE;
          case Format.RGB16F:
            return WebGLEXT.HALF_FLOAT_OES;
          case Format.RGB16UI:
            return gl.UNSIGNED_SHORT;
          case Format.RGB16I:
            return gl.SHORT;
          case Format.RGB32F:
            return gl.FLOAT;
          case Format.RGB32UI:
            return gl.UNSIGNED_INT;
          case Format.RGB32I:
            return gl.INT;
          case Format.BGRA8:
            return gl.UNSIGNED_BYTE;
          case Format.RGBA8:
            return gl.UNSIGNED_BYTE;
          case Format.SRGB8_A8:
            return gl.UNSIGNED_BYTE;
          case Format.RGBA8SN:
            return gl.BYTE;
          case Format.RGBA8UI:
            return gl.UNSIGNED_BYTE;
          case Format.RGBA8I:
            return gl.BYTE;
          case Format.RGBA16F:
            return WebGLEXT.HALF_FLOAT_OES;
          case Format.RGBA16UI:
            return gl.UNSIGNED_SHORT;
          case Format.RGBA16I:
            return gl.SHORT;
          case Format.RGBA32F:
            return gl.FLOAT;
          case Format.RGBA32UI:
            return gl.UNSIGNED_INT;
          case Format.RGBA32I:
            return gl.INT;
          case Format.R5G6B5:
            return gl.UNSIGNED_SHORT_5_6_5;
          case Format.R11G11B10F:
            return gl.FLOAT;
          case Format.RGB5A1:
            return gl.UNSIGNED_SHORT_5_5_5_1;
          case Format.RGBA4:
            return gl.UNSIGNED_SHORT_4_4_4_4;
          case Format.RGB10A2:
            return gl.UNSIGNED_BYTE;
          case Format.RGB10A2UI:
            return gl.UNSIGNED_INT;
          case Format.RGB9E5:
            return gl.UNSIGNED_BYTE;
          case Format.DEPTH:
            return gl.UNSIGNED_INT;
          case Format.DEPTH_STENCIL:
            return WebGLEXT.UNSIGNED_INT_24_8_WEBGL;
          case Format.BC1:
            return gl.UNSIGNED_BYTE;
          case Format.BC1_SRGB:
            return gl.UNSIGNED_BYTE;
          case Format.BC2:
            return gl.UNSIGNED_BYTE;
          case Format.BC2_SRGB:
            return gl.UNSIGNED_BYTE;
          case Format.BC3:
            return gl.UNSIGNED_BYTE;
          case Format.BC3_SRGB:
            return gl.UNSIGNED_BYTE;
          case Format.BC4:
            return gl.UNSIGNED_BYTE;
          case Format.BC4_SNORM:
            return gl.BYTE;
          case Format.BC5:
            return gl.UNSIGNED_BYTE;
          case Format.BC5_SNORM:
            return gl.BYTE;
          case Format.BC6H_SF16:
            return gl.FLOAT;
          case Format.BC6H_UF16:
            return gl.FLOAT;
          case Format.BC7:
            return gl.UNSIGNED_BYTE;
          case Format.BC7_SRGB:
            return gl.UNSIGNED_BYTE;
          case Format.ETC_RGB8:
            return gl.UNSIGNED_BYTE;
          case Format.ETC2_RGB8:
            return gl.UNSIGNED_BYTE;
          case Format.ETC2_SRGB8:
            return gl.UNSIGNED_BYTE;
          case Format.ETC2_RGB8_A1:
            return gl.UNSIGNED_BYTE;
          case Format.ETC2_SRGB8_A1:
            return gl.UNSIGNED_BYTE;
          case Format.EAC_R11:
            return gl.UNSIGNED_BYTE;
          case Format.EAC_R11SN:
            return gl.BYTE;
          case Format.EAC_RG11:
            return gl.UNSIGNED_BYTE;
          case Format.EAC_RG11SN:
            return gl.BYTE;
          case Format.PVRTC_RGB2:
            return gl.UNSIGNED_BYTE;
          case Format.PVRTC_RGBA2:
            return gl.UNSIGNED_BYTE;
          case Format.PVRTC_RGB4:
            return gl.UNSIGNED_BYTE;
          case Format.PVRTC_RGBA4:
            return gl.UNSIGNED_BYTE;
          case Format.PVRTC2_2BPP:
            return gl.UNSIGNED_BYTE;
          case Format.PVRTC2_4BPP:
            return gl.UNSIGNED_BYTE;
          case Format.ASTC_RGBA_4X4:
          case Format.ASTC_RGBA_5X4:
          case Format.ASTC_RGBA_5X5:
          case Format.ASTC_RGBA_6X5:
          case Format.ASTC_RGBA_6X6:
          case Format.ASTC_RGBA_8X5:
          case Format.ASTC_RGBA_8X6:
          case Format.ASTC_RGBA_8X8:
          case Format.ASTC_RGBA_10X5:
          case Format.ASTC_RGBA_10X6:
          case Format.ASTC_RGBA_10X8:
          case Format.ASTC_RGBA_10X10:
          case Format.ASTC_RGBA_12X10:
          case Format.ASTC_RGBA_12X12:
          case Format.ASTC_SRGBA_4X4:
          case Format.ASTC_SRGBA_5X4:
          case Format.ASTC_SRGBA_5X5:
          case Format.ASTC_SRGBA_6X5:
          case Format.ASTC_SRGBA_6X6:
          case Format.ASTC_SRGBA_8X5:
          case Format.ASTC_SRGBA_8X6:
          case Format.ASTC_SRGBA_8X8:
          case Format.ASTC_SRGBA_10X5:
          case Format.ASTC_SRGBA_10X6:
          case Format.ASTC_SRGBA_10X8:
          case Format.ASTC_SRGBA_10X10:
          case Format.ASTC_SRGBA_12X10:
          case Format.ASTC_SRGBA_12X12:
            return gl.UNSIGNED_BYTE;
          default:
            {
              return gl.UNSIGNED_BYTE;
            }
        }
      }
      function GFXFormatToWebGLInternalFormat$1(format, gl) {
        switch (format) {
          case Format.R5G6B5:
            return gl.RGB565;
          case Format.RGB5A1:
            return gl.RGB5_A1;
          case Format.RGBA4:
            return gl.RGBA4;
          case Format.RGBA16F:
            return WebGLEXT.RGBA16F_EXT;
          case Format.RGBA32F:
            return WebGLEXT.RGBA32F_EXT;
          case Format.SRGB8_A8:
            return WebGLEXT.SRGB8_ALPHA8_EXT;
          case Format.DEPTH:
            return gl.DEPTH_COMPONENT16;
          case Format.DEPTH_STENCIL:
            return gl.DEPTH_STENCIL;
          default:
            {
              error('Unsupported Format, convert to WebGL internal format failed.');
              return gl.RGBA;
            }
        }
      }
      function GFXFormatToWebGLFormat$1(format, gl) {
        switch (format) {
          case Format.A8:
            return gl.ALPHA;
          case Format.L8:
            return gl.LUMINANCE;
          case Format.LA8:
            return gl.LUMINANCE_ALPHA;
          case Format.RGB8:
            return gl.RGB;
          case Format.RGB16F:
            return gl.RGB;
          case Format.RGB32F:
            return gl.RGB;
          case Format.BGRA8:
            return gl.RGBA;
          case Format.RGBA8:
            return gl.RGBA;
          case Format.SRGB8_A8:
            return gl.RGBA;
          case Format.RGBA16F:
            return gl.RGBA;
          case Format.RGBA32F:
            return gl.RGBA;
          case Format.R5G6B5:
            return gl.RGB;
          case Format.RGB5A1:
            return gl.RGBA;
          case Format.RGBA4:
            return gl.RGBA;
          case Format.DEPTH:
            return gl.DEPTH_COMPONENT;
          case Format.DEPTH_STENCIL:
            return gl.DEPTH_STENCIL;
          case Format.BC1:
            return WebGLEXT.COMPRESSED_RGB_S3TC_DXT1_EXT;
          case Format.BC1_ALPHA:
            return WebGLEXT.COMPRESSED_RGBA_S3TC_DXT1_EXT;
          case Format.BC1_SRGB:
            return WebGLEXT.COMPRESSED_SRGB_S3TC_DXT1_EXT;
          case Format.BC1_SRGB_ALPHA:
            return WebGLEXT.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;
          case Format.BC2:
            return WebGLEXT.COMPRESSED_RGBA_S3TC_DXT3_EXT;
          case Format.BC2_SRGB:
            return WebGLEXT.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;
          case Format.BC3:
            return WebGLEXT.COMPRESSED_RGBA_S3TC_DXT5_EXT;
          case Format.BC3_SRGB:
            return WebGLEXT.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT;
          case Format.ETC_RGB8:
            return WebGLEXT.COMPRESSED_RGB_ETC1_WEBGL;
          case Format.ETC2_RGB8:
            return WebGLEXT.COMPRESSED_RGB8_ETC2;
          case Format.ETC2_SRGB8:
            return WebGLEXT.COMPRESSED_SRGB8_ETC2;
          case Format.ETC2_RGB8_A1:
            return WebGLEXT.COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2;
          case Format.ETC2_SRGB8_A1:
            return WebGLEXT.COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2;
          case Format.ETC2_RGBA8:
            return WebGLEXT.COMPRESSED_RGBA8_ETC2_EAC;
          case Format.ETC2_SRGB8_A8:
            return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC;
          case Format.EAC_R11:
            return WebGLEXT.COMPRESSED_R11_EAC;
          case Format.EAC_R11SN:
            return WebGLEXT.COMPRESSED_SIGNED_R11_EAC;
          case Format.EAC_RG11:
            return WebGLEXT.COMPRESSED_RG11_EAC;
          case Format.EAC_RG11SN:
            return WebGLEXT.COMPRESSED_SIGNED_RG11_EAC;
          case Format.PVRTC_RGB2:
            return WebGLEXT.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
          case Format.PVRTC_RGBA2:
            return WebGLEXT.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
          case Format.PVRTC_RGB4:
            return WebGLEXT.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
          case Format.PVRTC_RGBA4:
            return WebGLEXT.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
          case Format.ASTC_RGBA_4X4:
            return WebGLEXT.COMPRESSED_RGBA_ASTC_4x4_KHR;
          case Format.ASTC_RGBA_5X4:
            return WebGLEXT.COMPRESSED_RGBA_ASTC_5x4_KHR;
          case Format.ASTC_RGBA_5X5:
            return WebGLEXT.COMPRESSED_RGBA_ASTC_5x5_KHR;
          case Format.ASTC_RGBA_6X5:
            return WebGLEXT.COMPRESSED_RGBA_ASTC_6x5_KHR;
          case Format.ASTC_RGBA_6X6:
            return WebGLEXT.COMPRESSED_RGBA_ASTC_6x6_KHR;
          case Format.ASTC_RGBA_8X5:
            return WebGLEXT.COMPRESSED_RGBA_ASTC_8x5_KHR;
          case Format.ASTC_RGBA_8X6:
            return WebGLEXT.COMPRESSED_RGBA_ASTC_8x6_KHR;
          case Format.ASTC_RGBA_8X8:
            return WebGLEXT.COMPRESSED_RGBA_ASTC_8x8_KHR;
          case Format.ASTC_RGBA_10X5:
            return WebGLEXT.COMPRESSED_RGBA_ASTC_10x5_KHR;
          case Format.ASTC_RGBA_10X6:
            return WebGLEXT.COMPRESSED_RGBA_ASTC_10x6_KHR;
          case Format.ASTC_RGBA_10X8:
            return WebGLEXT.COMPRESSED_RGBA_ASTC_10x8_KHR;
          case Format.ASTC_RGBA_10X10:
            return WebGLEXT.COMPRESSED_RGBA_ASTC_10x10_KHR;
          case Format.ASTC_RGBA_12X10:
            return WebGLEXT.COMPRESSED_RGBA_ASTC_12x10_KHR;
          case Format.ASTC_RGBA_12X12:
            return WebGLEXT.COMPRESSED_RGBA_ASTC_12x12_KHR;
          case Format.ASTC_SRGBA_4X4:
            return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR;
          case Format.ASTC_SRGBA_5X4:
            return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR;
          case Format.ASTC_SRGBA_5X5:
            return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR;
          case Format.ASTC_SRGBA_6X5:
            return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR;
          case Format.ASTC_SRGBA_6X6:
            return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR;
          case Format.ASTC_SRGBA_8X5:
            return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR;
          case Format.ASTC_SRGBA_8X6:
            return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR;
          case Format.ASTC_SRGBA_8X8:
            return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR;
          case Format.ASTC_SRGBA_10X5:
            return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR;
          case Format.ASTC_SRGBA_10X6:
            return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR;
          case Format.ASTC_SRGBA_10X8:
            return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR;
          case Format.ASTC_SRGBA_10X10:
            return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR;
          case Format.ASTC_SRGBA_12X10:
            return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR;
          case Format.ASTC_SRGBA_12X12:
            return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR;
          default:
            {
              error('Unsupported Format, convert to WebGL format failed.');
              return gl.RGBA;
            }
        }
      }
      function GFXTypeToWebGLType$1(type, gl) {
        switch (type) {
          case Type$1.BOOL:
            return gl.BOOL;
          case Type$1.BOOL2:
            return gl.BOOL_VEC2;
          case Type$1.BOOL3:
            return gl.BOOL_VEC3;
          case Type$1.BOOL4:
            return gl.BOOL_VEC4;
          case Type$1.INT:
            return gl.INT;
          case Type$1.INT2:
            return gl.INT_VEC2;
          case Type$1.INT3:
            return gl.INT_VEC3;
          case Type$1.INT4:
            return gl.INT_VEC4;
          case Type$1.UINT:
            return gl.UNSIGNED_INT;
          case Type$1.FLOAT:
            return gl.FLOAT;
          case Type$1.FLOAT2:
            return gl.FLOAT_VEC2;
          case Type$1.FLOAT3:
            return gl.FLOAT_VEC3;
          case Type$1.FLOAT4:
            return gl.FLOAT_VEC4;
          case Type$1.MAT2:
            return gl.FLOAT_MAT2;
          case Type$1.MAT3:
            return gl.FLOAT_MAT3;
          case Type$1.MAT4:
            return gl.FLOAT_MAT4;
          case Type$1.SAMPLER2D:
            return gl.SAMPLER_2D;
          case Type$1.SAMPLER_CUBE:
            return gl.SAMPLER_CUBE;
          default:
            {
              error('Unsupported GLType, convert to GL type failed.');
              return Type$1.UNKNOWN;
            }
        }
      }
      function GFXTypeToTypedArrayCtor(type) {
        switch (type) {
          case Type$1.BOOL:
          case Type$1.BOOL2:
          case Type$1.BOOL3:
          case Type$1.BOOL4:
          case Type$1.INT:
          case Type$1.INT2:
          case Type$1.INT3:
          case Type$1.INT4:
          case Type$1.UINT:
            return Int32Array;
          case Type$1.FLOAT:
          case Type$1.FLOAT2:
          case Type$1.FLOAT3:
          case Type$1.FLOAT4:
          case Type$1.MAT2:
          case Type$1.MAT3:
          case Type$1.MAT4:
            return Float32Array;
          default:
            {
              error('Unsupported GLType, convert to TypedArrayConstructor failed.');
              return Float32Array;
            }
        }
      }
      function WebGLTypeToGFXType$1(glType, gl) {
        switch (glType) {
          case gl.BOOL:
            return Type$1.BOOL;
          case gl.BOOL_VEC2:
            return Type$1.BOOL2;
          case gl.BOOL_VEC3:
            return Type$1.BOOL3;
          case gl.BOOL_VEC4:
            return Type$1.BOOL4;
          case gl.INT:
            return Type$1.INT;
          case gl.INT_VEC2:
            return Type$1.INT2;
          case gl.INT_VEC3:
            return Type$1.INT3;
          case gl.INT_VEC4:
            return Type$1.INT4;
          case gl.UNSIGNED_INT:
            return Type$1.UINT;
          case gl.FLOAT:
            return Type$1.FLOAT;
          case gl.FLOAT_VEC2:
            return Type$1.FLOAT2;
          case gl.FLOAT_VEC3:
            return Type$1.FLOAT3;
          case gl.FLOAT_VEC4:
            return Type$1.FLOAT4;
          case gl.FLOAT_MAT2:
            return Type$1.MAT2;
          case gl.FLOAT_MAT3:
            return Type$1.MAT3;
          case gl.FLOAT_MAT4:
            return Type$1.MAT4;
          case gl.SAMPLER_2D:
            return Type$1.SAMPLER2D;
          case gl.SAMPLER_CUBE:
            return Type$1.SAMPLER_CUBE;
          default:
            {
              error('Unsupported GLType, convert to Type failed.');
              return Type$1.UNKNOWN;
            }
        }
      }
      function WebGLGetTypeSize$1(glType, gl) {
        switch (glType) {
          case gl.BOOL:
            return 4;
          case gl.BOOL_VEC2:
            return 8;
          case gl.BOOL_VEC3:
            return 12;
          case gl.BOOL_VEC4:
            return 16;
          case gl.INT:
            return 4;
          case gl.INT_VEC2:
            return 8;
          case gl.INT_VEC3:
            return 12;
          case gl.INT_VEC4:
            return 16;
          case gl.UNSIGNED_INT:
            return 4;
          case gl.FLOAT:
            return 4;
          case gl.FLOAT_VEC2:
            return 8;
          case gl.FLOAT_VEC3:
            return 12;
          case gl.FLOAT_VEC4:
            return 16;
          case gl.FLOAT_MAT2:
            return 16;
          case gl.FLOAT_MAT3:
            return 36;
          case gl.FLOAT_MAT4:
            return 64;
          case gl.SAMPLER_2D:
            return 4;
          case gl.SAMPLER_CUBE:
            return 4;
          default:
            {
              error('Unsupported GLType, get type failed.');
              return 0;
            }
        }
      }
      function WebGLGetComponentCount$1(glType, gl) {
        switch (glType) {
          case gl.FLOAT_MAT2:
            return 2;
          case gl.FLOAT_MAT3:
            return 3;
          case gl.FLOAT_MAT4:
            return 4;
          default:
            {
              return 1;
            }
        }
      }
      var WebGLCmpFuncs$1 = [0x0200, 0x0201, 0x0202, 0x0203, 0x0204, 0x0205, 0x0206, 0x0207];
      var WebGLStencilOps$1 = [0x0000, 0x1E00, 0x1E01, 0x1E02, 0x1E03, 0x150A, 0x8507, 0x8508];
      var WebGLBlendOps$1 = [0x8006, 0x800A, 0x800B, 0x8007, 0x8008];
      var WebGLBlendFactors$1 = [0x0000, 0x0001, 0x0302, 0x0304, 0x0303, 0x0305, 0x0300, 0x0306, 0x0301, 0x0307, 0x0308, 0x8001, 0x8002, 0x8003, 0x8004];
      var WebGLCmd;
      (function (WebGLCmd) {
        WebGLCmd[WebGLCmd["BEGIN_RENDER_PASS"] = 0] = "BEGIN_RENDER_PASS";
        WebGLCmd[WebGLCmd["END_RENDER_PASS"] = 1] = "END_RENDER_PASS";
        WebGLCmd[WebGLCmd["BIND_STATES"] = 2] = "BIND_STATES";
        WebGLCmd[WebGLCmd["DRAW"] = 3] = "DRAW";
        WebGLCmd[WebGLCmd["UPDATE_BUFFER"] = 4] = "UPDATE_BUFFER";
        WebGLCmd[WebGLCmd["COPY_BUFFER_TO_TEXTURE"] = 5] = "COPY_BUFFER_TO_TEXTURE";
        WebGLCmd[WebGLCmd["BLIT_TEXTURE"] = 6] = "BLIT_TEXTURE";
        WebGLCmd[WebGLCmd["COUNT"] = 7] = "COUNT";
      })(WebGLCmd || (WebGLCmd = {}));
      var WebGLCmdObject = function WebGLCmdObject(type) {
        this.cmdType = void 0;
        this.refCount = 0;
        this.cmdType = type;
      };
      var WebGLCmdBeginRenderPass = function (_WebGLCmdObject) {
        _inheritsLoose(WebGLCmdBeginRenderPass, _WebGLCmdObject);
        function WebGLCmdBeginRenderPass() {
          var _this;
          _this = _WebGLCmdObject.call(this, WebGLCmd.BEGIN_RENDER_PASS) || this;
          _this.gpuRenderPass = null;
          _this.gpuFramebuffer = null;
          _this.renderArea = new Rect();
          _this.clearFlag = ClearFlagBit.NONE;
          _this.clearColors = [];
          _this.clearDepth = 1.0;
          _this.clearStencil = 0;
          return _this;
        }
        var _proto = WebGLCmdBeginRenderPass.prototype;
        _proto.clear = function clear() {
          this.gpuFramebuffer = null;
          this.clearColors.length = 0;
        };
        return WebGLCmdBeginRenderPass;
      }(WebGLCmdObject);
      var WebGLCmdBindStates = function (_WebGLCmdObject2) {
        _inheritsLoose(WebGLCmdBindStates, _WebGLCmdObject2);
        function WebGLCmdBindStates() {
          var _this2;
          _this2 = _WebGLCmdObject2.call(this, WebGLCmd.BIND_STATES) || this;
          _this2.gpuPipelineState = null;
          _this2.gpuInputAssembler = null;
          _this2.gpuDescriptorSets = [];
          _this2.dynamicOffsets = [];
          _this2.dynamicStates = new DynamicStates();
          return _this2;
        }
        var _proto2 = WebGLCmdBindStates.prototype;
        _proto2.clear = function clear() {
          this.gpuPipelineState = null;
          this.gpuDescriptorSets.length = 0;
          this.gpuInputAssembler = null;
          this.dynamicOffsets.length = 0;
        };
        return WebGLCmdBindStates;
      }(WebGLCmdObject);
      var WebGLCmdDraw = function (_WebGLCmdObject3) {
        _inheritsLoose(WebGLCmdDraw, _WebGLCmdObject3);
        function WebGLCmdDraw() {
          var _this3;
          _this3 = _WebGLCmdObject3.call(this, WebGLCmd.DRAW) || this;
          _this3.drawInfo = new DrawInfo();
          return _this3;
        }
        var _proto3 = WebGLCmdDraw.prototype;
        _proto3.clear = function clear() {};
        return WebGLCmdDraw;
      }(WebGLCmdObject);
      var WebGLCmdUpdateBuffer = function (_WebGLCmdObject4) {
        _inheritsLoose(WebGLCmdUpdateBuffer, _WebGLCmdObject4);
        function WebGLCmdUpdateBuffer() {
          var _this4;
          _this4 = _WebGLCmdObject4.call(this, WebGLCmd.UPDATE_BUFFER) || this;
          _this4.gpuBuffer = null;
          _this4.buffer = null;
          _this4.offset = 0;
          _this4.size = 0;
          return _this4;
        }
        var _proto4 = WebGLCmdUpdateBuffer.prototype;
        _proto4.clear = function clear() {
          this.gpuBuffer = null;
          this.buffer = null;
        };
        return WebGLCmdUpdateBuffer;
      }(WebGLCmdObject);
      var WebGLCmdCopyBufferToTexture = function (_WebGLCmdObject5) {
        _inheritsLoose(WebGLCmdCopyBufferToTexture, _WebGLCmdObject5);
        function WebGLCmdCopyBufferToTexture() {
          var _this5;
          _this5 = _WebGLCmdObject5.call(this, WebGLCmd.COPY_BUFFER_TO_TEXTURE) || this;
          _this5.gpuTexture = null;
          _this5.buffers = [];
          _this5.regions = [];
          return _this5;
        }
        var _proto5 = WebGLCmdCopyBufferToTexture.prototype;
        _proto5.clear = function clear() {
          this.gpuTexture = null;
          this.buffers.length = 0;
          this.regions.length = 0;
        };
        return WebGLCmdCopyBufferToTexture;
      }(WebGLCmdObject);
      var WebGLCmdBlitTexture = function (_WebGLCmdObject6) {
        _inheritsLoose(WebGLCmdBlitTexture, _WebGLCmdObject6);
        function WebGLCmdBlitTexture() {
          var _this6;
          _this6 = _WebGLCmdObject6.call(this, WebGLCmd.BLIT_TEXTURE) || this;
          _this6.srcTexture = null;
          _this6.dstTexture = null;
          _this6.regions = [];
          _this6.filter = Filter$1.LINEAR;
          return _this6;
        }
        var _proto6 = WebGLCmdBlitTexture.prototype;
        _proto6.clear = function clear() {
          this.srcTexture = null;
          this.dstTexture = null;
          this.regions.length = 0;
        };
        return WebGLCmdBlitTexture;
      }(WebGLCmdObject);
      var WebGLCmdPackage = function () {
        function WebGLCmdPackage() {
          this.cmds = new CachedArray(1);
          this.beginRenderPassCmds = new CachedArray(1);
          this.bindStatesCmds = new CachedArray(1);
          this.drawCmds = new CachedArray(1);
          this.updateBufferCmds = new CachedArray(1);
          this.copyBufferToTextureCmds = new CachedArray(1);
          this.blitTextureCmds = new CachedArray(1);
        }
        var _proto7 = WebGLCmdPackage.prototype;
        _proto7.clearCmds = function clearCmds(allocator) {
          if (this.beginRenderPassCmds.length) {
            allocator.beginRenderPassCmdPool.freeCmds(this.beginRenderPassCmds);
            this.beginRenderPassCmds.clear();
          }
          if (this.bindStatesCmds.length) {
            allocator.bindStatesCmdPool.freeCmds(this.bindStatesCmds);
            this.bindStatesCmds.clear();
          }
          if (this.drawCmds.length) {
            allocator.drawCmdPool.freeCmds(this.drawCmds);
            this.drawCmds.clear();
          }
          if (this.updateBufferCmds.length) {
            allocator.updateBufferCmdPool.freeCmds(this.updateBufferCmds);
            this.updateBufferCmds.clear();
          }
          if (this.copyBufferToTextureCmds.length) {
            allocator.copyBufferToTextureCmdPool.freeCmds(this.copyBufferToTextureCmds);
            this.copyBufferToTextureCmds.clear();
          }
          if (this.blitTextureCmds.length) {
            allocator.blitTextureCmdPool.freeCmds(this.blitTextureCmds);
            this.blitTextureCmds.clear();
          }
          this.cmds.clear();
        };
        return WebGLCmdPackage;
      }();
      function WebGLCmdFuncCreateBuffer(device, gpuBuffer) {
        var gl = device.gl;
        var cache = device.stateCache;
        var glUsage = gpuBuffer.memUsage & MemoryUsageBit.HOST ? gl.DYNAMIC_DRAW : gl.STATIC_DRAW;
        if (gpuBuffer.usage & BufferUsageBit.VERTEX) {
          gpuBuffer.glTarget = gl.ARRAY_BUFFER;
          var glBuffer = gl.createBuffer();
          if (glBuffer) {
            gpuBuffer.glBuffer = glBuffer;
            if (gpuBuffer.size > 0) {
              if (device.extensions.useVAO) {
                if (cache.glVAO) {
                  device.extensions.OES_vertex_array_object.bindVertexArrayOES(null);
                  cache.glVAO = null;
                }
              }
              gfxStateCache$1.gpuInputAssembler = null;
              if (device.stateCache.glArrayBuffer !== gpuBuffer.glBuffer) {
                gl.bindBuffer(gl.ARRAY_BUFFER, gpuBuffer.glBuffer);
                device.stateCache.glArrayBuffer = gpuBuffer.glBuffer;
              }
              gl.bufferData(gl.ARRAY_BUFFER, gpuBuffer.size, glUsage);
              gl.bindBuffer(gl.ARRAY_BUFFER, null);
              device.stateCache.glArrayBuffer = null;
            }
          }
        } else if (gpuBuffer.usage & BufferUsageBit.INDEX) {
          gpuBuffer.glTarget = gl.ELEMENT_ARRAY_BUFFER;
          var _glBuffer = gl.createBuffer();
          if (_glBuffer) {
            gpuBuffer.glBuffer = _glBuffer;
            if (gpuBuffer.size > 0) {
              if (device.extensions.useVAO) {
                if (cache.glVAO) {
                  device.extensions.OES_vertex_array_object.bindVertexArrayOES(null);
                  cache.glVAO = null;
                }
              }
              gfxStateCache$1.gpuInputAssembler = null;
              if (device.stateCache.glElementArrayBuffer !== gpuBuffer.glBuffer) {
                gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, gpuBuffer.glBuffer);
                device.stateCache.glElementArrayBuffer = gpuBuffer.glBuffer;
              }
              gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, gpuBuffer.size, glUsage);
              gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, null);
              device.stateCache.glElementArrayBuffer = null;
            }
          }
        } else if (gpuBuffer.usage & BufferUsageBit.UNIFORM) {
          gpuBuffer.glTarget = gl.NONE;
          if (gpuBuffer.buffer) {
            gpuBuffer.vf32 = new Float32Array(gpuBuffer.buffer.buffer);
          }
        } else if (gpuBuffer.usage & BufferUsageBit.INDIRECT) {
          gpuBuffer.glTarget = gl.NONE;
        } else if (gpuBuffer.usage & BufferUsageBit.TRANSFER_DST) {
          gpuBuffer.glTarget = gl.NONE;
        } else if (gpuBuffer.usage & BufferUsageBit.TRANSFER_SRC) {
          gpuBuffer.glTarget = gl.NONE;
        } else {
          error('Unsupported BufferType, create buffer failed.');
          gpuBuffer.glTarget = gl.NONE;
        }
      }
      function WebGLCmdFuncDestroyBuffer(device, gpuBuffer) {
        var gl = device.gl;
        var cache = device.stateCache;
        if (gpuBuffer.glBuffer) {
          switch (gpuBuffer.glTarget) {
            case gl.ARRAY_BUFFER:
              if (device.extensions.useVAO) {
                if (cache.glVAO) {
                  device.extensions.OES_vertex_array_object.bindVertexArrayOES(null);
                  device.stateCache.glVAO = null;
                }
              }
              gfxStateCache$1.gpuInputAssembler = null;
              gl.bindBuffer(gl.ARRAY_BUFFER, null);
              device.stateCache.glArrayBuffer = null;
              break;
            case gl.ELEMENT_ARRAY_BUFFER:
              if (device.extensions.useVAO) {
                if (cache.glVAO) {
                  device.extensions.OES_vertex_array_object.bindVertexArrayOES(null);
                  device.stateCache.glVAO = null;
                }
              }
              gfxStateCache$1.gpuInputAssembler = null;
              gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, null);
              device.stateCache.glElementArrayBuffer = null;
              break;
          }
          gl.deleteBuffer(gpuBuffer.glBuffer);
          gpuBuffer.glBuffer = null;
        }
      }
      function WebGLCmdFuncResizeBuffer(device, gpuBuffer) {
        var gl = device.gl;
        var cache = device.stateCache;
        var glUsage = gpuBuffer.memUsage & MemoryUsageBit.HOST ? gl.DYNAMIC_DRAW : gl.STATIC_DRAW;
        if (gpuBuffer.usage & BufferUsageBit.VERTEX) {
          if (device.extensions.useVAO) {
            if (cache.glVAO) {
              device.extensions.OES_vertex_array_object.bindVertexArrayOES(null);
              cache.glVAO = null;
            }
          }
          gfxStateCache$1.gpuInputAssembler = null;
          if (device.stateCache.glArrayBuffer !== gpuBuffer.glBuffer) {
            gl.bindBuffer(gl.ARRAY_BUFFER, gpuBuffer.glBuffer);
          }
          if (gpuBuffer.buffer) {
            gl.bufferData(gl.ARRAY_BUFFER, gpuBuffer.buffer, glUsage);
          } else {
            gl.bufferData(gl.ARRAY_BUFFER, gpuBuffer.size, glUsage);
          }
          gl.bindBuffer(gl.ARRAY_BUFFER, null);
          device.stateCache.glArrayBuffer = null;
        } else if (gpuBuffer.usage & BufferUsageBit.INDEX) {
          if (device.extensions.useVAO) {
            if (cache.glVAO) {
              device.extensions.OES_vertex_array_object.bindVertexArrayOES(null);
              cache.glVAO = null;
            }
          }
          gfxStateCache$1.gpuInputAssembler = null;
          if (device.stateCache.glElementArrayBuffer !== gpuBuffer.glBuffer) {
            gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, gpuBuffer.glBuffer);
          }
          if (gpuBuffer.buffer) {
            gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, gpuBuffer.buffer, glUsage);
          } else {
            gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, gpuBuffer.size, glUsage);
          }
          gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, null);
          device.stateCache.glElementArrayBuffer = null;
        } else if (gpuBuffer.usage & BufferUsageBit.UNIFORM) {
          if (gpuBuffer.buffer) {
            gpuBuffer.vf32 = new Float32Array(gpuBuffer.buffer.buffer);
          }
        } else if (gpuBuffer.usage & BufferUsageBit.INDIRECT || gpuBuffer.usage & BufferUsageBit.TRANSFER_DST || gpuBuffer.usage & BufferUsageBit.TRANSFER_SRC) {
          gpuBuffer.glTarget = gl.NONE;
        } else {
          error('Unsupported BufferType, create buffer failed.');
          gpuBuffer.glTarget = gl.NONE;
        }
      }
      function WebGLCmdFuncUpdateBuffer(device, gpuBuffer, buffer, offset, size) {
        if (gpuBuffer.usage & BufferUsageBit.UNIFORM) {
          if (ArrayBuffer.isView(buffer)) {
            gpuBuffer.vf32.set(buffer, offset / Float32Array.BYTES_PER_ELEMENT);
          } else {
            gpuBuffer.vf32.set(new Float32Array(buffer), offset / Float32Array.BYTES_PER_ELEMENT);
          }
        } else if (gpuBuffer.usage & BufferUsageBit.INDIRECT) {
          gpuBuffer.indirects.clearDraws();
          var drawInfos = buffer.drawInfos;
          for (var i = 0; i < drawInfos.length; ++i) {
            gpuBuffer.indirects.setDrawInfo(offset + i, drawInfos[i]);
          }
        } else {
          var buff = buffer;
          var gl = device.gl;
          var cache = device.stateCache;
          switch (gpuBuffer.glTarget) {
            case gl.ARRAY_BUFFER:
              {
                if (device.extensions.useVAO) {
                  if (cache.glVAO) {
                    device.extensions.OES_vertex_array_object.bindVertexArrayOES(null);
                    cache.glVAO = null;
                  }
                }
                gfxStateCache$1.gpuInputAssembler = null;
                if (device.stateCache.glArrayBuffer !== gpuBuffer.glBuffer) {
                  gl.bindBuffer(gl.ARRAY_BUFFER, gpuBuffer.glBuffer);
                  device.stateCache.glArrayBuffer = gpuBuffer.glBuffer;
                }
                break;
              }
            case gl.ELEMENT_ARRAY_BUFFER:
              {
                if (device.extensions.useVAO) {
                  if (cache.glVAO) {
                    device.extensions.OES_vertex_array_object.bindVertexArrayOES(null);
                    cache.glVAO = null;
                  }
                }
                gfxStateCache$1.gpuInputAssembler = null;
                if (device.stateCache.glElementArrayBuffer !== gpuBuffer.glBuffer) {
                  gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, gpuBuffer.glBuffer);
                  device.stateCache.glElementArrayBuffer = gpuBuffer.glBuffer;
                }
                break;
              }
            default:
              {
                error('Unsupported BufferType, update buffer failed.');
                return;
              }
          }
          if (size === buff.byteLength) {
            gl.bufferSubData(gpuBuffer.glTarget, offset, buff);
          } else {
            gl.bufferSubData(gpuBuffer.glTarget, offset, buff.slice(0, size));
          }
        }
      }
      function WebGLCmdFuncCreateTexture(device, gpuTexture) {
        var gl = device.gl;
        gpuTexture.glFormat = gpuTexture.glInternalFmt = GFXFormatToWebGLFormat$1(gpuTexture.format, gl);
        gpuTexture.glType = GFXFormatToWebGLType$1(gpuTexture.format, gl);
        var w = gpuTexture.width;
        var h = gpuTexture.height;
        switch (gpuTexture.type) {
          case TextureType.TEX2D:
            {
              gpuTexture.glTarget = gl.TEXTURE_2D;
              var maxSize = Math.max(w, h);
              if (maxSize > device.capabilities.maxTextureSize) {
                errorID(9100, maxSize, device.capabilities.maxTextureSize);
              }
              if (!device.textureExclusive[gpuTexture.format] && !device.extensions.WEBGL_depth_texture && FormatInfos[gpuTexture.format].hasDepth) {
                gpuTexture.glInternalFmt = GFXFormatToWebGLInternalFormat$1(gpuTexture.format, gl);
                gpuTexture.glRenderbuffer = gl.createRenderbuffer();
                if (gpuTexture.size > 0) {
                  if (device.stateCache.glRenderbuffer !== gpuTexture.glRenderbuffer) {
                    gl.bindRenderbuffer(gl.RENDERBUFFER, gpuTexture.glRenderbuffer);
                    device.stateCache.glRenderbuffer = gpuTexture.glRenderbuffer;
                  }
                  gl.renderbufferStorage(gl.RENDERBUFFER, gpuTexture.glInternalFmt, w, h);
                }
              } else {
                gpuTexture.glTexture = gl.createTexture();
                if (gpuTexture.size > 0) {
                  var glTexUnit = device.stateCache.glTexUnits[device.stateCache.texUnit];
                  if (glTexUnit.glTexture !== gpuTexture.glTexture) {
                    gl.bindTexture(gl.TEXTURE_2D, gpuTexture.glTexture);
                    glTexUnit.glTexture = gpuTexture.glTexture;
                  }
                  if (FormatInfos[gpuTexture.format].isCompressed) {
                    for (var i = 0; i < gpuTexture.mipLevel; ++i) {
                      var imgSize = FormatSize(gpuTexture.format, w, h, 1);
                      var view = new Uint8Array(imgSize);
                      gl.compressedTexImage2D(gl.TEXTURE_2D, i, gpuTexture.glInternalFmt, w, h, 0, view);
                      w = Math.max(1, w >> 1);
                      h = Math.max(1, h >> 1);
                    }
                  } else {
                    for (var _i = 0; _i < gpuTexture.mipLevel; ++_i) {
                      gl.texImage2D(gl.TEXTURE_2D, _i, gpuTexture.glInternalFmt, w, h, 0, gpuTexture.glFormat, gpuTexture.glType, null);
                      w = Math.max(1, w >> 1);
                      h = Math.max(1, h >> 1);
                    }
                  }
                  if (gpuTexture.isPowerOf2) {
                    gpuTexture.glWrapS = gl.REPEAT;
                    gpuTexture.glWrapT = gl.REPEAT;
                  } else {
                    gpuTexture.glWrapS = gl.CLAMP_TO_EDGE;
                    gpuTexture.glWrapT = gl.CLAMP_TO_EDGE;
                  }
                  gpuTexture.glMinFilter = gl.LINEAR;
                  gpuTexture.glMagFilter = gl.LINEAR;
                  gl.texParameteri(gpuTexture.glTarget, gl.TEXTURE_WRAP_S, gpuTexture.glWrapS);
                  gl.texParameteri(gpuTexture.glTarget, gl.TEXTURE_WRAP_T, gpuTexture.glWrapT);
                  gl.texParameteri(gpuTexture.glTarget, gl.TEXTURE_MIN_FILTER, gpuTexture.glMinFilter);
                  gl.texParameteri(gpuTexture.glTarget, gl.TEXTURE_MAG_FILTER, gpuTexture.glMagFilter);
                }
              }
              break;
            }
          case TextureType.CUBE:
            {
              gpuTexture.glTarget = gl.TEXTURE_CUBE_MAP;
              var _maxSize = Math.max(w, h);
              if (_maxSize > device.capabilities.maxCubeMapTextureSize) {
                errorID(9100, _maxSize, device.capabilities.maxTextureSize);
              }
              gpuTexture.glTexture = gl.createTexture();
              if (gpuTexture.size > 0) {
                var _glTexUnit = device.stateCache.glTexUnits[device.stateCache.texUnit];
                if (_glTexUnit.glTexture !== gpuTexture.glTexture) {
                  gl.bindTexture(gl.TEXTURE_CUBE_MAP, gpuTexture.glTexture);
                  _glTexUnit.glTexture = gpuTexture.glTexture;
                }
                if (FormatInfos[gpuTexture.format].isCompressed) {
                  for (var f = 0; f < 6; ++f) {
                    w = gpuTexture.width;
                    h = gpuTexture.height;
                    for (var _i2 = 0; _i2 < gpuTexture.mipLevel; ++_i2) {
                      var _imgSize = FormatSize(gpuTexture.format, w, h, 1);
                      var _view = new Uint8Array(_imgSize);
                      gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + f, _i2, gpuTexture.glInternalFmt, w, h, 0, _view);
                      w = Math.max(1, w >> 1);
                      h = Math.max(1, h >> 1);
                    }
                  }
                } else {
                  for (var _f = 0; _f < 6; ++_f) {
                    w = gpuTexture.width;
                    h = gpuTexture.height;
                    for (var _i3 = 0; _i3 < gpuTexture.mipLevel; ++_i3) {
                      gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + _f, _i3, gpuTexture.glInternalFmt, w, h, 0, gpuTexture.glFormat, gpuTexture.glType, null);
                      w = Math.max(1, w >> 1);
                      h = Math.max(1, h >> 1);
                    }
                  }
                }
                if (gpuTexture.isPowerOf2) {
                  gpuTexture.glWrapS = gl.REPEAT;
                  gpuTexture.glWrapT = gl.REPEAT;
                } else {
                  gpuTexture.glWrapS = gl.CLAMP_TO_EDGE;
                  gpuTexture.glWrapT = gl.CLAMP_TO_EDGE;
                }
                gpuTexture.glMinFilter = gl.LINEAR;
                gpuTexture.glMagFilter = gl.LINEAR;
                gl.texParameteri(gpuTexture.glTarget, gl.TEXTURE_WRAP_S, gpuTexture.glWrapS);
                gl.texParameteri(gpuTexture.glTarget, gl.TEXTURE_WRAP_T, gpuTexture.glWrapT);
                gl.texParameteri(gpuTexture.glTarget, gl.TEXTURE_MIN_FILTER, gpuTexture.glMinFilter);
                gl.texParameteri(gpuTexture.glTarget, gl.TEXTURE_MAG_FILTER, gpuTexture.glMagFilter);
              }
              break;
            }
          default:
            {
              error('Unsupported TextureType, create texture failed.');
              gpuTexture.type = TextureType.TEX2D;
              gpuTexture.glTarget = gl.TEXTURE_2D;
            }
        }
      }
      function WebGLCmdFuncDestroyTexture(device, gpuTexture) {
        var gl = device.gl;
        if (gpuTexture.glTexture) {
          var glTexUnits = device.stateCache.glTexUnits;
          var texUnit = device.stateCache.texUnit;
          gl.deleteTexture(gpuTexture.glTexture);
          for (var i = 0; i < glTexUnits.length; i++) {
            if (glTexUnits[i].glTexture === gpuTexture.glTexture) {
              gl.activeTexture(gl.TEXTURE0 + i);
              texUnit = i;
              gl.bindTexture(gpuTexture.glTarget, null);
              glTexUnits[i].glTexture = null;
            }
          }
          device.stateCache.texUnit = texUnit;
          gpuTexture.glTexture = null;
        }
        if (gpuTexture.glRenderbuffer) {
          var glRenderbuffer = device.stateCache.glRenderbuffer;
          gl.deleteRenderbuffer(gpuTexture.glRenderbuffer);
          if (glRenderbuffer === gpuTexture.glRenderbuffer) {
            gl.bindRenderbuffer(gl.RENDERBUFFER, null);
            glRenderbuffer = null;
          }
          gpuTexture.glRenderbuffer = null;
        }
      }
      function WebGLCmdFuncResizeTexture(device, gpuTexture) {
        if (!gpuTexture.size) return;
        var gl = device.gl;
        var w = gpuTexture.width;
        var h = gpuTexture.height;
        switch (gpuTexture.type) {
          case TextureType.TEX2D:
            {
              gpuTexture.glTarget = gl.TEXTURE_2D;
              var maxSize = Math.max(w, h);
              if (maxSize > device.capabilities.maxTextureSize) {
                errorID(9100, maxSize, device.capabilities.maxTextureSize);
              }
              if (gpuTexture.glRenderbuffer) {
                if (device.stateCache.glRenderbuffer !== gpuTexture.glRenderbuffer) {
                  gl.bindRenderbuffer(gl.RENDERBUFFER, gpuTexture.glRenderbuffer);
                  device.stateCache.glRenderbuffer = gpuTexture.glRenderbuffer;
                }
                gl.renderbufferStorage(gl.RENDERBUFFER, gpuTexture.glInternalFmt, w, h);
              } else if (gpuTexture.glTexture) {
                var glTexUnit = device.stateCache.glTexUnits[device.stateCache.texUnit];
                if (glTexUnit.glTexture !== gpuTexture.glTexture) {
                  gl.bindTexture(gl.TEXTURE_2D, gpuTexture.glTexture);
                  glTexUnit.glTexture = gpuTexture.glTexture;
                }
                if (FormatInfos[gpuTexture.format].isCompressed) {
                  for (var i = 0; i < gpuTexture.mipLevel; ++i) {
                    var imgSize = FormatSize(gpuTexture.format, w, h, 1);
                    var view = new Uint8Array(imgSize);
                    gl.compressedTexImage2D(gl.TEXTURE_2D, i, gpuTexture.glInternalFmt, w, h, 0, view);
                    w = Math.max(1, w >> 1);
                    h = Math.max(1, h >> 1);
                  }
                } else {
                  for (var _i4 = 0; _i4 < gpuTexture.mipLevel; ++_i4) {
                    gl.texImage2D(gl.TEXTURE_2D, _i4, gpuTexture.glInternalFmt, w, h, 0, gpuTexture.glFormat, gpuTexture.glType, null);
                    w = Math.max(1, w >> 1);
                    h = Math.max(1, h >> 1);
                  }
                }
              }
              break;
            }
          case TextureType.CUBE:
            {
              gpuTexture.glTarget = gl.TEXTURE_CUBE_MAP;
              var _maxSize2 = Math.max(w, h);
              if (_maxSize2 > device.capabilities.maxCubeMapTextureSize) {
                errorID(9100, _maxSize2, device.capabilities.maxTextureSize);
              }
              var _glTexUnit2 = device.stateCache.glTexUnits[device.stateCache.texUnit];
              if (_glTexUnit2.glTexture !== gpuTexture.glTexture) {
                gl.bindTexture(gl.TEXTURE_CUBE_MAP, gpuTexture.glTexture);
                _glTexUnit2.glTexture = gpuTexture.glTexture;
              }
              if (FormatInfos[gpuTexture.format].isCompressed) {
                for (var f = 0; f < 6; ++f) {
                  w = gpuTexture.width;
                  h = gpuTexture.height;
                  for (var _i5 = 0; _i5 < gpuTexture.mipLevel; ++_i5) {
                    var _imgSize2 = FormatSize(gpuTexture.format, w, h, 1);
                    var _view2 = new Uint8Array(_imgSize2);
                    gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + f, _i5, gpuTexture.glInternalFmt, w, h, 0, _view2);
                    w = Math.max(1, w >> 1);
                    h = Math.max(1, h >> 1);
                  }
                }
              } else {
                for (var _f2 = 0; _f2 < 6; ++_f2) {
                  w = gpuTexture.width;
                  h = gpuTexture.height;
                  for (var _i6 = 0; _i6 < gpuTexture.mipLevel; ++_i6) {
                    gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + _f2, _i6, gpuTexture.glInternalFmt, w, h, 0, gpuTexture.glFormat, gpuTexture.glType, null);
                    w = Math.max(1, w >> 1);
                    h = Math.max(1, h >> 1);
                  }
                }
              }
              break;
            }
          default:
            {
              error('Unsupported TextureType, create texture failed.');
              gpuTexture.type = TextureType.TEX2D;
              gpuTexture.glTarget = gl.TEXTURE_2D;
            }
        }
      }
      function WebGLCmdFuncCreateFramebuffer(device, gpuFramebuffer) {
        for (var i = 0; i < gpuFramebuffer.gpuColorTextures.length; ++i) {
          var tex = gpuFramebuffer.gpuColorTextures[i];
          if (tex.isSwapchainTexture) {
            gpuFramebuffer.isOffscreen = false;
            return;
          }
        }
        var gl = device.gl;
        var attachments = [];
        var glFramebuffer = gl.createFramebuffer();
        if (glFramebuffer) {
          gpuFramebuffer.glFramebuffer = glFramebuffer;
          if (device.stateCache.glFramebuffer !== gpuFramebuffer.glFramebuffer) {
            gl.bindFramebuffer(gl.FRAMEBUFFER, gpuFramebuffer.glFramebuffer);
          }
          for (var _i7 = 0; _i7 < gpuFramebuffer.gpuColorTextures.length; ++_i7) {
            var gpuTexture = gpuFramebuffer.gpuColorTextures[_i7];
            if (gpuTexture) {
              if (gpuTexture.glTexture) {
                gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + _i7, gpuTexture.glTarget, gpuTexture.glTexture, 0);
              } else {
                gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + _i7, gl.RENDERBUFFER, gpuTexture.glRenderbuffer);
              }
              attachments.push(gl.COLOR_ATTACHMENT0 + _i7);
              gpuFramebuffer.width = Math.min(gpuFramebuffer.width, gpuTexture.width);
              gpuFramebuffer.height = Math.min(gpuFramebuffer.height, gpuTexture.height);
            }
          }
          var dst = gpuFramebuffer.gpuDepthStencilTexture;
          if (dst) {
            var glAttachment = FormatInfos[dst.format].hasStencil ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
            if (dst.glTexture) {
              gl.framebufferTexture2D(gl.FRAMEBUFFER, glAttachment, dst.glTarget, dst.glTexture, 0);
            } else {
              gl.framebufferRenderbuffer(gl.FRAMEBUFFER, glAttachment, gl.RENDERBUFFER, dst.glRenderbuffer);
            }
            gpuFramebuffer.width = Math.min(gpuFramebuffer.width, dst.width);
            gpuFramebuffer.height = Math.min(gpuFramebuffer.height, dst.height);
          }
          if (device.extensions.WEBGL_draw_buffers) {
            device.extensions.WEBGL_draw_buffers.drawBuffersWEBGL(attachments);
          }
          var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
          if (status !== gl.FRAMEBUFFER_COMPLETE) {
            switch (status) {
              case gl.FRAMEBUFFER_INCOMPLETE_ATTACHMENT:
                {
                  error('glCheckFramebufferStatus() - FRAMEBUFFER_INCOMPLETE_ATTACHMENT');
                  break;
                }
              case gl.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:
                {
                  error('glCheckFramebufferStatus() - FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT');
                  break;
                }
              case gl.FRAMEBUFFER_INCOMPLETE_DIMENSIONS:
                {
                  error('glCheckFramebufferStatus() - FRAMEBUFFER_INCOMPLETE_DIMENSIONS');
                  break;
                }
              case gl.FRAMEBUFFER_UNSUPPORTED:
                {
                  error('glCheckFramebufferStatus() - FRAMEBUFFER_UNSUPPORTED');
                  break;
                }
            }
          }
          if (device.stateCache.glFramebuffer !== gpuFramebuffer.glFramebuffer) {
            gl.bindFramebuffer(gl.FRAMEBUFFER, device.stateCache.glFramebuffer);
          }
        }
      }
      function WebGLCmdFuncDestroyFramebuffer(device, gpuFramebuffer) {
        if (gpuFramebuffer.glFramebuffer) {
          device.gl.deleteFramebuffer(gpuFramebuffer.glFramebuffer);
          if (device.stateCache.glFramebuffer === gpuFramebuffer.glFramebuffer) {
            device.gl.bindFramebuffer(device.gl.FRAMEBUFFER, null);
            device.stateCache.glFramebuffer = null;
          }
          gpuFramebuffer.glFramebuffer = null;
        }
      }
      function WebGLCmdFuncCreateShader(device, gpuShader) {
        var gl = device.gl;
        var _loop = function _loop() {
            var gpuStage = gpuShader.gpuStages[k];
            var glShaderType = 0;
            var shaderTypeStr = '';
            var lineNumber = 1;
            switch (gpuStage.type) {
              case ShaderStageFlagBit.VERTEX:
                {
                  shaderTypeStr = 'VertexShader';
                  glShaderType = gl.VERTEX_SHADER;
                  break;
                }
              case ShaderStageFlagBit.FRAGMENT:
                {
                  shaderTypeStr = 'FragmentShader';
                  glShaderType = gl.FRAGMENT_SHADER;
                  break;
                }
              default:
                {
                  error('Unsupported ShaderType.');
                  return {
                    v: void 0
                  };
                }
            }
            var glShader = gl.createShader(glShaderType);
            if (glShader) {
              gpuStage.glShader = glShader;
              gl.shaderSource(gpuStage.glShader, gpuStage.source);
              gl.compileShader(gpuStage.glShader);
              if (!gl.getShaderParameter(gpuStage.glShader, gl.COMPILE_STATUS)) {
                error(shaderTypeStr + " in '" + gpuShader.name + "' compilation failed.");
                error('Shader source dump:', gpuStage.source.replace(/^|\n/g, function () {
                  return "\n" + lineNumber++ + " ";
                }));
                error(gl.getShaderInfoLog(gpuStage.glShader));
                for (var l = 0; l < gpuShader.gpuStages.length; l++) {
                  var stage = gpuShader.gpuStages[k];
                  if (stage.glShader) {
                    gl.deleteShader(stage.glShader);
                    stage.glShader = null;
                  }
                }
                return {
                  v: void 0
                };
              }
            }
          },
          _ret;
        for (var k = 0; k < gpuShader.gpuStages.length; k++) {
          _ret = _loop();
          if (_ret) return _ret.v;
        }
        var glProgram = gl.createProgram();
        if (!glProgram) {
          return;
        }
        gpuShader.glProgram = glProgram;
        for (var _k = 0; _k < gpuShader.gpuStages.length; _k++) {
          var gpuStage = gpuShader.gpuStages[_k];
          gl.attachShader(gpuShader.glProgram, gpuStage.glShader);
        }
        gl.linkProgram(gpuShader.glProgram);
        if (device.extensions.destroyShadersImmediately) {
          for (var _k2 = 0; _k2 < gpuShader.gpuStages.length; _k2++) {
            var _gpuStage = gpuShader.gpuStages[_k2];
            if (_gpuStage.glShader) {
              gl.detachShader(gpuShader.glProgram, _gpuStage.glShader);
              gl.deleteShader(_gpuStage.glShader);
              _gpuStage.glShader = null;
            }
          }
        }
        if (gl.getProgramParameter(gpuShader.glProgram, gl.LINK_STATUS)) {
          debug("Shader '" + gpuShader.name + "' compilation succeeded.");
        } else {
          error("Failed to link shader '" + gpuShader.name + "'.");
          error(gl.getProgramInfoLog(gpuShader.glProgram));
          return;
        }
        var activeAttribCount = gl.getProgramParameter(gpuShader.glProgram, gl.ACTIVE_ATTRIBUTES);
        gpuShader.glInputs = new Array(activeAttribCount);
        for (var i = 0; i < activeAttribCount; ++i) {
          var attribInfo = gl.getActiveAttrib(gpuShader.glProgram, i);
          if (attribInfo) {
            var varName = void 0;
            var nameOffset = attribInfo.name.indexOf('[');
            if (nameOffset !== -1) {
              varName = attribInfo.name.substr(0, nameOffset);
            } else {
              varName = attribInfo.name;
            }
            var glLoc = gl.getAttribLocation(gpuShader.glProgram, varName);
            var type = WebGLTypeToGFXType$1(attribInfo.type, gl);
            var stride = WebGLGetTypeSize$1(attribInfo.type, gl);
            gpuShader.glInputs[i] = {
              binding: glLoc,
              name: varName,
              type: type,
              stride: stride,
              count: attribInfo.size,
              size: stride * attribInfo.size,
              glType: attribInfo.type,
              glLoc: glLoc
            };
          }
        }
        if (gpuShader.blocks.length > 0) {
          gpuShader.glBlocks = new Array(gpuShader.blocks.length);
          for (var _i8 = 0; _i8 < gpuShader.blocks.length; ++_i8) {
            var block = gpuShader.blocks[_i8];
            var glBlock = {
              set: block.set,
              binding: block.binding,
              name: block.name,
              size: 0,
              glUniforms: new Array(block.members.length),
              glActiveUniforms: []
            };
            gpuShader.glBlocks[_i8] = glBlock;
            for (var u = 0; u < block.members.length; ++u) {
              var uniform = block.members[u];
              var glType = GFXTypeToWebGLType$1(uniform.type, gl);
              var _stride = WebGLGetTypeSize$1(glType, gl);
              var size = _stride * uniform.count;
              glBlock.glUniforms[u] = {
                binding: -1,
                name: uniform.name,
                type: uniform.type,
                stride: _stride,
                count: uniform.count,
                size: size,
                offset: 0,
                glType: glType,
                glLoc: null,
                array: null
              };
            }
          }
        }
        for (var _i9 = 0; _i9 < gpuShader.subpassInputs.length; ++_i9) {
          var subpassInput = gpuShader.subpassInputs[_i9];
          gpuShader.samplerTextures.push(new UniformSamplerTexture(subpassInput.set, subpassInput.binding, subpassInput.name, Type$1.SAMPLER2D, subpassInput.count));
        }
        if (gpuShader.samplerTextures.length > 0) {
          gpuShader.glSamplerTextures = new Array(gpuShader.samplerTextures.length);
          for (var _i10 = 0; _i10 < gpuShader.samplerTextures.length; ++_i10) {
            var sampler = gpuShader.samplerTextures[_i10];
            gpuShader.glSamplerTextures[_i10] = {
              set: sampler.set,
              binding: sampler.binding,
              name: sampler.name,
              type: sampler.type,
              count: sampler.count,
              units: [],
              glUnits: null,
              glType: GFXTypeToWebGLType$1(sampler.type, gl),
              glLoc: null
            };
          }
        }
        var activeUniformCount = gl.getProgramParameter(gpuShader.glProgram, gl.ACTIVE_UNIFORMS);
        for (var _i11 = 0; _i11 < activeUniformCount; ++_i11) {
          var uniformInfo = gl.getActiveUniform(gpuShader.glProgram, _i11);
          if (uniformInfo) {
            var isSampler = uniformInfo.type === gl.SAMPLER_2D || uniformInfo.type === gl.SAMPLER_CUBE;
            if (!isSampler) {
              var _glLoc = gl.getUniformLocation(gpuShader.glProgram, uniformInfo.name);
              if (device.extensions.isLocationActive(_glLoc)) {
                var _varName = void 0;
                var _nameOffset = uniformInfo.name.indexOf('[');
                if (_nameOffset !== -1) {
                  _varName = uniformInfo.name.substr(0, _nameOffset);
                } else {
                  _varName = uniformInfo.name;
                }
                for (var j = 0; j < gpuShader.glBlocks.length; j++) {
                  var _glBlock = gpuShader.glBlocks[j];
                  for (var _k3 = 0; _k3 < _glBlock.glUniforms.length; _k3++) {
                    var glUniform = _glBlock.glUniforms[_k3];
                    if (glUniform.name === _varName) {
                      glUniform.glLoc = _glLoc;
                      glUniform.count = uniformInfo.size;
                      glUniform.size = glUniform.stride * glUniform.count;
                      glUniform.array = new (GFXTypeToTypedArrayCtor(glUniform.type))(glUniform.size / 4);
                      _glBlock.glActiveUniforms.push(glUniform);
                      break;
                    }
                  }
                }
              }
            }
          }
        }
        for (var _j = 0; _j < gpuShader.glBlocks.length; _j++) {
          var _glBlock2 = gpuShader.glBlocks[_j];
          for (var _k4 = 0; _k4 < _glBlock2.glUniforms.length; _k4++) {
            var _glUniform = _glBlock2.glUniforms[_k4];
            _glUniform.offset = _glBlock2.size / 4;
            _glBlock2.size += _glUniform.size;
          }
        }
        var glActiveSamplers = [];
        var glActiveSamplerLocations = [];
        var bindingMappings = device.bindingMappings;
        var texUnitCacheMap = device.stateCache.texUnitCacheMap;
        if (!(legacyCC.rendering && legacyCC.rendering.enableEffectImport)) {
          var flexibleSetBaseOffset = 0;
          for (var _i12 = 0; _i12 < gpuShader.blocks.length; ++_i12) {
            if (gpuShader.blocks[_i12].set === bindingMappings.flexibleSet) {
              flexibleSetBaseOffset++;
            }
          }
          var arrayOffset = 0;
          for (var _i13 = 0; _i13 < gpuShader.samplerTextures.length; ++_i13) {
            var _sampler = gpuShader.samplerTextures[_i13];
            var _glLoc2 = gl.getUniformLocation(gpuShader.glProgram, _sampler.name);
            if (device.extensions.isLocationActive(_glLoc2)) {
              glActiveSamplers.push(gpuShader.glSamplerTextures[_i13]);
              glActiveSamplerLocations.push(_glLoc2);
            }
            if (texUnitCacheMap[_sampler.name] === undefined) {
              var binding = _sampler.binding + bindingMappings.samplerTextureOffsets[_sampler.set] + arrayOffset;
              if (_sampler.set === bindingMappings.flexibleSet) {
                binding -= flexibleSetBaseOffset;
              }
              texUnitCacheMap[_sampler.name] = binding % device.capabilities.maxTextureUnits;
              arrayOffset += _sampler.count - 1;
            }
          }
        } else {
          for (var _i14 = 0; _i14 < gpuShader.samplerTextures.length; ++_i14) {
            var _sampler2 = gpuShader.samplerTextures[_i14];
            var _glLoc3 = gl.getUniformLocation(gpuShader.glProgram, _sampler2.name);
            if (device.extensions.isLocationActive(_glLoc3)) {
              glActiveSamplers.push(gpuShader.glSamplerTextures[_i14]);
              glActiveSamplerLocations.push(_glLoc3);
            }
            if (texUnitCacheMap[_sampler2.name] === undefined) {
              texUnitCacheMap[_sampler2.name] = _sampler2.flattened % device.capabilities.maxTextureUnits;
            }
          }
        }
        if (glActiveSamplers.length) {
          var usedTexUnits = [];
          for (var _i15 = 0; _i15 < glActiveSamplers.length; ++_i15) {
            var glSampler = glActiveSamplers[_i15];
            var cachedUnit = texUnitCacheMap[glSampler.name];
            if (cachedUnit !== undefined) {
              glSampler.glLoc = glActiveSamplerLocations[_i15];
              for (var t = 0; t < glSampler.count; ++t) {
                while (usedTexUnits[cachedUnit]) {
                  cachedUnit = (cachedUnit + 1) % device.capabilities.maxTextureUnits;
                }
                glSampler.units.push(cachedUnit);
                usedTexUnits[cachedUnit] = true;
              }
            }
          }
          var unitIdx = 0;
          for (var _i16 = 0; _i16 < glActiveSamplers.length; ++_i16) {
            var _glSampler = glActiveSamplers[_i16];
            if (!device.extensions.isLocationActive(_glSampler.glLoc)) {
              _glSampler.glLoc = glActiveSamplerLocations[_i16];
              for (var _t = 0; _t < _glSampler.count; ++_t) {
                while (usedTexUnits[unitIdx]) {
                  unitIdx = (unitIdx + 1) % device.capabilities.maxTextureUnits;
                }
                if (texUnitCacheMap[_glSampler.name] === undefined) {
                  texUnitCacheMap[_glSampler.name] = unitIdx;
                }
                _glSampler.units.push(unitIdx);
                usedTexUnits[unitIdx] = true;
              }
            }
          }
          if (device.stateCache.glProgram !== gpuShader.glProgram) {
            gl.useProgram(gpuShader.glProgram);
          }
          for (var _i17 = 0; _i17 < glActiveSamplers.length; _i17++) {
            var _glSampler2 = glActiveSamplers[_i17];
            _glSampler2.glUnits = new Int32Array(_glSampler2.units);
            gl.uniform1iv(_glSampler2.glLoc, _glSampler2.glUnits);
          }
          if (device.stateCache.glProgram !== gpuShader.glProgram) {
            gl.useProgram(device.stateCache.glProgram);
          }
        }
        for (var _i18 = 0; _i18 < gpuShader.glBlocks.length;) {
          if (gpuShader.glBlocks[_i18].glActiveUniforms.length) {
            _i18++;
          } else {
            gpuShader.glBlocks[_i18] = gpuShader.glBlocks[gpuShader.glBlocks.length - 1];
            gpuShader.glBlocks.length--;
          }
        }
        gpuShader.glSamplerTextures = glActiveSamplers;
      }
      function WebGLCmdFuncDestroyShader(device, gpuShader) {
        if (gpuShader.glProgram) {
          var gl = device.gl;
          if (!device.extensions.destroyShadersImmediately) {
            for (var k = 0; k < gpuShader.gpuStages.length; k++) {
              var gpuStage = gpuShader.gpuStages[k];
              if (gpuStage.glShader) {
                gl.detachShader(gpuShader.glProgram, gpuStage.glShader);
                gl.deleteShader(gpuStage.glShader);
                gpuStage.glShader = null;
              }
            }
          }
          gl.deleteProgram(gpuShader.glProgram);
          if (device.stateCache.glProgram === gpuShader.glProgram) {
            device.gl.useProgram(null);
            device.stateCache.glProgram = null;
          }
          gpuShader.glProgram = null;
        }
      }
      function WebGLCmdFuncCreateInputAssember(device, gpuInputAssembler) {
        var gl = device.gl;
        gpuInputAssembler.glAttribs = new Array(gpuInputAssembler.attributes.length);
        var offsets = [0, 0, 0, 0, 0, 0, 0, 0];
        for (var i = 0; i < gpuInputAssembler.attributes.length; ++i) {
          var attrib = gpuInputAssembler.attributes[i];
          var stream = attrib.stream !== undefined ? attrib.stream : 0;
          var gpuBuffer = gpuInputAssembler.gpuVertexBuffers[stream];
          var glType = GFXFormatToWebGLType$1(attrib.format, gl);
          var size = FormatInfos[attrib.format].size;
          gpuInputAssembler.glAttribs[i] = {
            name: attrib.name,
            glBuffer: gpuBuffer.glBuffer,
            glType: glType,
            size: size,
            count: FormatInfos[attrib.format].count,
            stride: gpuBuffer.stride,
            componentCount: WebGLGetComponentCount$1(glType, gl),
            isNormalized: attrib.isNormalized !== undefined ? attrib.isNormalized : false,
            isInstanced: attrib.isInstanced !== undefined ? attrib.isInstanced : false,
            offset: offsets[stream]
          };
          offsets[stream] += size;
        }
      }
      function WebGLCmdFuncDestroyInputAssembler(device, gpuInputAssembler) {
        var it = gpuInputAssembler.glVAOs.values();
        var res = it.next();
        var OES_vertex_array_object = device.extensions.OES_vertex_array_object;
        var glVAO = device.stateCache.glVAO;
        while (!res.done) {
          OES_vertex_array_object.deleteVertexArrayOES(res.value);
          if (glVAO === res.value) {
            OES_vertex_array_object.bindVertexArrayOES(null);
            glVAO = null;
          }
          res = it.next();
        }
        device.stateCache.glVAO = glVAO;
        gpuInputAssembler.glVAOs.clear();
      }
      var gfxStateCache$1 = {
        gpuPipelineState: null,
        gpuInputAssembler: null,
        glPrimitive: 0
      };
      var realRenderArea = new Rect();
      function WebGLCmdFuncBeginRenderPass(device, gpuRenderPass, gpuFramebuffer, renderArea, clearColors, clearDepth, clearStencil) {
        var gl = device.gl;
        var cache = device.stateCache;
        var clears = 0;
        if (gpuFramebuffer) {
          realRenderArea.x = renderArea.x << gpuFramebuffer.lodLevel;
          realRenderArea.y = renderArea.y << gpuFramebuffer.lodLevel;
          realRenderArea.width = renderArea.width << gpuFramebuffer.lodLevel;
          realRenderArea.height = renderArea.height << gpuFramebuffer.lodLevel;
        }
        if (gpuFramebuffer && gpuRenderPass) {
          if (cache.glFramebuffer !== gpuFramebuffer.glFramebuffer) {
            gl.bindFramebuffer(gl.FRAMEBUFFER, gpuFramebuffer.glFramebuffer);
            cache.glFramebuffer = gpuFramebuffer.glFramebuffer;
          }
          if (cache.viewport.left !== realRenderArea.x || cache.viewport.top !== realRenderArea.y || cache.viewport.width !== realRenderArea.width || cache.viewport.height !== realRenderArea.height) {
            gl.viewport(realRenderArea.x, realRenderArea.y, realRenderArea.width, realRenderArea.height);
            cache.viewport.left = realRenderArea.x;
            cache.viewport.top = realRenderArea.y;
            cache.viewport.width = realRenderArea.width;
            cache.viewport.height = realRenderArea.height;
          }
          if (cache.scissorRect.x !== realRenderArea.x || cache.scissorRect.y !== realRenderArea.y || cache.scissorRect.width !== realRenderArea.width || cache.scissorRect.height !== realRenderArea.height) {
            gl.scissor(realRenderArea.x, realRenderArea.y, realRenderArea.width, realRenderArea.height);
            cache.scissorRect.x = realRenderArea.x;
            cache.scissorRect.y = realRenderArea.y;
            cache.scissorRect.width = realRenderArea.width;
            cache.scissorRect.height = realRenderArea.height;
          }
          var clearCount = clearColors.length;
          if (!device.extensions.WEBGL_draw_buffers) {
            clearCount = 1;
          }
          for (var j = 0; j < clearCount; ++j) {
            var colorAttachment = gpuRenderPass.colorAttachments[j];
            if (colorAttachment.format !== Format.UNKNOWN) {
              switch (colorAttachment.loadOp) {
                case LoadOp.LOAD:
                  break;
                case LoadOp.CLEAR:
                  {
                    if (cache.bs.targets[0].blendColorMask !== ColorMask.ALL) {
                      gl.colorMask(true, true, true, true);
                    }
                    var clearColor = clearColors[0];
                    gl.clearColor(clearColor.x, clearColor.y, clearColor.z, clearColor.w);
                    clears |= gl.COLOR_BUFFER_BIT;
                    break;
                  }
                case LoadOp.DISCARD:
                  {
                    break;
                  }
              }
            }
          }
          if (gpuRenderPass.depthStencilAttachment) {
            if (gpuRenderPass.depthStencilAttachment.format !== Format.UNKNOWN) {
              switch (gpuRenderPass.depthStencilAttachment.depthLoadOp) {
                case LoadOp.LOAD:
                  break;
                case LoadOp.CLEAR:
                  {
                    if (!cache.dss.depthWrite) {
                      gl.depthMask(true);
                    }
                    gl.clearDepth(clearDepth);
                    clears |= gl.DEPTH_BUFFER_BIT;
                    break;
                  }
                case LoadOp.DISCARD:
                  {
                    break;
                  }
              }
              if (FormatInfos[gpuRenderPass.depthStencilAttachment.format].hasStencil) {
                switch (gpuRenderPass.depthStencilAttachment.stencilLoadOp) {
                  case LoadOp.LOAD:
                    break;
                  case LoadOp.CLEAR:
                    {
                      if (!cache.dss.stencilWriteMaskFront) {
                        gl.stencilMaskSeparate(gl.FRONT, 0xffff);
                      }
                      if (!cache.dss.stencilWriteMaskBack) {
                        gl.stencilMaskSeparate(gl.BACK, 0xffff);
                      }
                      gl.clearStencil(clearStencil);
                      clears |= gl.STENCIL_BUFFER_BIT;
                      break;
                    }
                  case LoadOp.DISCARD:
                    {
                      break;
                    }
                }
              }
            }
          }
          if (clears) {
            gl.clear(clears);
          }
          if (clears & gl.COLOR_BUFFER_BIT) {
            var colorMask = cache.bs.targets[0].blendColorMask;
            if (colorMask !== ColorMask.ALL) {
              var r = (colorMask & ColorMask.R) !== ColorMask.NONE;
              var g = (colorMask & ColorMask.G) !== ColorMask.NONE;
              var b = (colorMask & ColorMask.B) !== ColorMask.NONE;
              var a = (colorMask & ColorMask.A) !== ColorMask.NONE;
              gl.colorMask(r, g, b, a);
            }
          }
          if (clears & gl.DEPTH_BUFFER_BIT && !cache.dss.depthWrite) {
            gl.depthMask(false);
          }
          if (clears & gl.STENCIL_BUFFER_BIT) {
            if (!cache.dss.stencilWriteMaskFront) {
              gl.stencilMaskSeparate(gl.FRONT, 0);
            }
            if (!cache.dss.stencilWriteMaskBack) {
              gl.stencilMaskSeparate(gl.BACK, 0);
            }
          }
        }
      }
      function WebGLCmdFuncBindStates(device, gpuPipelineState, gpuInputAssembler, gpuDescriptorSets, dynamicOffsets, dynamicStates) {
        var gl = device.gl;
        var cache = device.stateCache;
        var gpuShader = gpuPipelineState && gpuPipelineState.gpuShader;
        var isShaderChanged = false;
        var glWrapS;
        var glWrapT;
        var glMinFilter;
        if (gpuPipelineState && gfxStateCache$1.gpuPipelineState !== gpuPipelineState) {
          gfxStateCache$1.gpuPipelineState = gpuPipelineState;
          gfxStateCache$1.glPrimitive = gpuPipelineState.glPrimitive;
          if (gpuPipelineState.gpuShader) {
            var glProgram = gpuPipelineState.gpuShader.glProgram;
            if (cache.glProgram !== glProgram) {
              gl.useProgram(glProgram);
              cache.glProgram = glProgram;
              isShaderChanged = true;
            }
          }
          var rs = gpuPipelineState.rs;
          if (rs) {
            if (cache.rs.cullMode !== rs.cullMode) {
              switch (rs.cullMode) {
                case CullMode.NONE:
                  {
                    gl.disable(gl.CULL_FACE);
                    break;
                  }
                case CullMode.FRONT:
                  {
                    gl.enable(gl.CULL_FACE);
                    gl.cullFace(gl.FRONT);
                    break;
                  }
                case CullMode.BACK:
                  {
                    gl.enable(gl.CULL_FACE);
                    gl.cullFace(gl.BACK);
                    break;
                  }
              }
              cache.rs.cullMode = rs.cullMode;
            }
            var isFrontFaceCCW = rs.isFrontFaceCCW;
            if (cache.rs.isFrontFaceCCW !== isFrontFaceCCW) {
              gl.frontFace(isFrontFaceCCW ? gl.CCW : gl.CW);
              cache.rs.isFrontFaceCCW = isFrontFaceCCW;
            }
            if (cache.rs.depthBias !== rs.depthBias || cache.rs.depthBiasSlop !== rs.depthBiasSlop) {
              gl.polygonOffset(rs.depthBias, rs.depthBiasSlop);
              cache.rs.depthBias = rs.depthBias;
              cache.rs.depthBiasSlop = rs.depthBiasSlop;
            }
            if (cache.rs.lineWidth !== rs.lineWidth) {
              gl.lineWidth(rs.lineWidth);
              cache.rs.lineWidth = rs.lineWidth;
            }
          }
          var dss = gpuPipelineState.dss;
          if (dss) {
            if (cache.dss.depthTest !== dss.depthTest) {
              if (dss.depthTest) {
                gl.enable(gl.DEPTH_TEST);
              } else {
                gl.disable(gl.DEPTH_TEST);
              }
              cache.dss.depthTest = dss.depthTest;
            }
            if (cache.dss.depthWrite !== dss.depthWrite) {
              gl.depthMask(dss.depthWrite);
              cache.dss.depthWrite = dss.depthWrite;
            }
            if (cache.dss.depthFunc !== dss.depthFunc) {
              gl.depthFunc(WebGLCmpFuncs$1[dss.depthFunc]);
              cache.dss.depthFunc = dss.depthFunc;
            }
            if (cache.dss.stencilTestFront !== dss.stencilTestFront || cache.dss.stencilTestBack !== dss.stencilTestBack) {
              if (dss.stencilTestFront || dss.stencilTestBack) {
                gl.enable(gl.STENCIL_TEST);
              } else {
                gl.disable(gl.STENCIL_TEST);
              }
              cache.dss.stencilTestFront = dss.stencilTestFront;
              cache.dss.stencilTestBack = dss.stencilTestBack;
            }
            if (cache.dss.stencilFuncFront !== dss.stencilFuncFront || cache.dss.stencilRefFront !== dss.stencilRefFront || cache.dss.stencilReadMaskFront !== dss.stencilReadMaskFront) {
              gl.stencilFuncSeparate(gl.FRONT, WebGLCmpFuncs$1[dss.stencilFuncFront], dss.stencilRefFront, dss.stencilReadMaskFront);
              cache.dss.stencilFuncFront = dss.stencilFuncFront;
              cache.dss.stencilRefFront = dss.stencilRefFront;
              cache.dss.stencilReadMaskFront = dss.stencilReadMaskFront;
            }
            if (cache.dss.stencilFailOpFront !== dss.stencilFailOpFront || cache.dss.stencilZFailOpFront !== dss.stencilZFailOpFront || cache.dss.stencilPassOpFront !== dss.stencilPassOpFront) {
              gl.stencilOpSeparate(gl.FRONT, WebGLStencilOps$1[dss.stencilFailOpFront], WebGLStencilOps$1[dss.stencilZFailOpFront], WebGLStencilOps$1[dss.stencilPassOpFront]);
              cache.dss.stencilFailOpFront = dss.stencilFailOpFront;
              cache.dss.stencilZFailOpFront = dss.stencilZFailOpFront;
              cache.dss.stencilPassOpFront = dss.stencilPassOpFront;
            }
            if (cache.dss.stencilWriteMaskFront !== dss.stencilWriteMaskFront) {
              gl.stencilMaskSeparate(gl.FRONT, dss.stencilWriteMaskFront);
              cache.dss.stencilWriteMaskFront = dss.stencilWriteMaskFront;
            }
            if (cache.dss.stencilFuncBack !== dss.stencilFuncBack || cache.dss.stencilRefBack !== dss.stencilRefBack || cache.dss.stencilReadMaskBack !== dss.stencilReadMaskBack) {
              gl.stencilFuncSeparate(gl.BACK, WebGLCmpFuncs$1[dss.stencilFuncBack], dss.stencilRefBack, dss.stencilReadMaskBack);
              cache.dss.stencilFuncBack = dss.stencilFuncBack;
              cache.dss.stencilRefBack = dss.stencilRefBack;
              cache.dss.stencilReadMaskBack = dss.stencilReadMaskBack;
            }
            if (cache.dss.stencilFailOpBack !== dss.stencilFailOpBack || cache.dss.stencilZFailOpBack !== dss.stencilZFailOpBack || cache.dss.stencilPassOpBack !== dss.stencilPassOpBack) {
              gl.stencilOpSeparate(gl.BACK, WebGLStencilOps$1[dss.stencilFailOpBack], WebGLStencilOps$1[dss.stencilZFailOpBack], WebGLStencilOps$1[dss.stencilPassOpBack]);
              cache.dss.stencilFailOpBack = dss.stencilFailOpBack;
              cache.dss.stencilZFailOpBack = dss.stencilZFailOpBack;
              cache.dss.stencilPassOpBack = dss.stencilPassOpBack;
            }
            if (cache.dss.stencilWriteMaskBack !== dss.stencilWriteMaskBack) {
              gl.stencilMaskSeparate(gl.BACK, dss.stencilWriteMaskBack);
              cache.dss.stencilWriteMaskBack = dss.stencilWriteMaskBack;
            }
          }
          var bs = gpuPipelineState.bs;
          if (bs) {
            if (cache.bs.isA2C !== bs.isA2C) {
              if (bs.isA2C) {
                gl.enable(gl.SAMPLE_ALPHA_TO_COVERAGE);
              } else {
                gl.disable(gl.SAMPLE_ALPHA_TO_COVERAGE);
              }
              cache.bs.isA2C = bs.isA2C;
            }
            if (cache.bs.blendColor.x !== bs.blendColor.x || cache.bs.blendColor.y !== bs.blendColor.y || cache.bs.blendColor.z !== bs.blendColor.z || cache.bs.blendColor.w !== bs.blendColor.w) {
              gl.blendColor(bs.blendColor.x, bs.blendColor.y, bs.blendColor.z, bs.blendColor.w);
              cache.bs.blendColor.x = bs.blendColor.x;
              cache.bs.blendColor.y = bs.blendColor.y;
              cache.bs.blendColor.z = bs.blendColor.z;
              cache.bs.blendColor.w = bs.blendColor.w;
            }
            var target0 = bs.targets[0];
            var target0Cache = cache.bs.targets[0];
            if (target0Cache.blend !== target0.blend) {
              if (target0.blend) {
                gl.enable(gl.BLEND);
              } else {
                gl.disable(gl.BLEND);
              }
              target0Cache.blend = target0.blend;
            }
            if (target0Cache.blendEq !== target0.blendEq || target0Cache.blendAlphaEq !== target0.blendAlphaEq) {
              gl.blendEquationSeparate(WebGLBlendOps$1[target0.blendEq], WebGLBlendOps$1[target0.blendAlphaEq]);
              target0Cache.blendEq = target0.blendEq;
              target0Cache.blendAlphaEq = target0.blendAlphaEq;
            }
            if (target0Cache.blendSrc !== target0.blendSrc || target0Cache.blendDst !== target0.blendDst || target0Cache.blendSrcAlpha !== target0.blendSrcAlpha || target0Cache.blendDstAlpha !== target0.blendDstAlpha) {
              gl.blendFuncSeparate(WebGLBlendFactors$1[target0.blendSrc], WebGLBlendFactors$1[target0.blendDst], WebGLBlendFactors$1[target0.blendSrcAlpha], WebGLBlendFactors$1[target0.blendDstAlpha]);
              target0Cache.blendSrc = target0.blendSrc;
              target0Cache.blendDst = target0.blendDst;
              target0Cache.blendSrcAlpha = target0.blendSrcAlpha;
              target0Cache.blendDstAlpha = target0.blendDstAlpha;
            }
            if (target0Cache.blendColorMask !== target0.blendColorMask) {
              gl.colorMask((target0.blendColorMask & ColorMask.R) !== ColorMask.NONE, (target0.blendColorMask & ColorMask.G) !== ColorMask.NONE, (target0.blendColorMask & ColorMask.B) !== ColorMask.NONE, (target0.blendColorMask & ColorMask.A) !== ColorMask.NONE);
              target0Cache.blendColorMask = target0.blendColorMask;
            }
          }
        }
        if (gpuPipelineState && gpuPipelineState.gpuPipelineLayout && gpuShader) {
          var blockLen = gpuShader.glBlocks.length;
          var dynamicOffsetIndices = gpuPipelineState.gpuPipelineLayout.dynamicOffsetIndices;
          for (var j = 0; j < blockLen; j++) {
            var glBlock = gpuShader.glBlocks[j];
            var gpuDescriptorSet = gpuDescriptorSets[glBlock.set];
            var descriptorIdx = gpuDescriptorSet && gpuDescriptorSet.descriptorIndices[glBlock.binding];
            var gpuDescriptor = descriptorIdx >= 0 && gpuDescriptorSet.gpuDescriptors[descriptorIdx];
            var vf32 = null;
            var offset = 0;
            if (gpuDescriptor && gpuDescriptor.gpuBuffer) {
              var gpuBuffer = gpuDescriptor.gpuBuffer;
              var dynamicOffsetIndexSet = dynamicOffsetIndices[glBlock.set];
              var dynamicOffsetIndex = dynamicOffsetIndexSet && dynamicOffsetIndexSet[glBlock.binding];
              if (dynamicOffsetIndex >= 0) {
                offset = dynamicOffsets[dynamicOffsetIndex];
              }
              if ('vf32' in gpuBuffer) {
                vf32 = gpuBuffer.vf32;
              } else {
                offset += gpuBuffer.offset;
                vf32 = gpuBuffer.gpuBuffer.vf32;
              }
              offset >>= 2;
            }
            if (!vf32) {
              continue;
            }
            var uniformLen = glBlock.glActiveUniforms.length;
            for (var l = 0; l < uniformLen; l++) {
              var glUniform = glBlock.glActiveUniforms[l];
              switch (glUniform.glType) {
                case gl.BOOL:
                case gl.INT:
                  {
                    for (var u = 0; u < glUniform.array.length; ++u) {
                      var idx = glUniform.offset + offset + u;
                      if (vf32[idx] !== glUniform.array[u]) {
                        for (var n = u, m = idx; n < glUniform.array.length; ++n, ++m) {
                          glUniform.array[n] = vf32[m];
                        }
                        gl.uniform1iv(glUniform.glLoc, glUniform.array);
                        break;
                      }
                    }
                    break;
                  }
                case gl.BOOL_VEC2:
                case gl.INT_VEC2:
                  {
                    for (var _u = 0; _u < glUniform.array.length; ++_u) {
                      var _idx = glUniform.offset + offset + _u;
                      if (vf32[_idx] !== glUniform.array[_u]) {
                        for (var _n = _u, _m = _idx; _n < glUniform.array.length; ++_n, ++_m) {
                          glUniform.array[_n] = vf32[_m];
                        }
                        gl.uniform2iv(glUniform.glLoc, glUniform.array);
                        break;
                      }
                    }
                    break;
                  }
                case gl.BOOL_VEC3:
                case gl.INT_VEC3:
                  {
                    for (var _u2 = 0; _u2 < glUniform.array.length; ++_u2) {
                      var _idx2 = glUniform.offset + offset + _u2;
                      if (vf32[_idx2] !== glUniform.array[_u2]) {
                        for (var _n2 = _u2, _m2 = _idx2; _n2 < glUniform.array.length; ++_n2, ++_m2) {
                          glUniform.array[_n2] = vf32[_m2];
                        }
                        gl.uniform3iv(glUniform.glLoc, glUniform.array);
                        break;
                      }
                    }
                    break;
                  }
                case gl.BOOL_VEC4:
                case gl.INT_VEC4:
                  {
                    for (var _u3 = 0; _u3 < glUniform.array.length; ++_u3) {
                      var _idx3 = glUniform.offset + offset + _u3;
                      if (vf32[_idx3] !== glUniform.array[_u3]) {
                        for (var _n3 = _u3, _m3 = _idx3; _n3 < glUniform.array.length; ++_n3, ++_m3) {
                          glUniform.array[_n3] = vf32[_m3];
                        }
                        gl.uniform4iv(glUniform.glLoc, glUniform.array);
                        break;
                      }
                    }
                    break;
                  }
                case gl.FLOAT:
                  {
                    for (var _u4 = 0; _u4 < glUniform.array.length; ++_u4) {
                      var _idx4 = glUniform.offset + offset + _u4;
                      if (vf32[_idx4] !== glUniform.array[_u4]) {
                        for (var _n4 = _u4, _m4 = _idx4; _n4 < glUniform.array.length; ++_n4, ++_m4) {
                          glUniform.array[_n4] = vf32[_m4];
                        }
                        gl.uniform1fv(glUniform.glLoc, glUniform.array);
                        break;
                      }
                    }
                    break;
                  }
                case gl.FLOAT_VEC2:
                  {
                    for (var _u5 = 0; _u5 < glUniform.array.length; ++_u5) {
                      var _idx5 = glUniform.offset + offset + _u5;
                      if (vf32[_idx5] !== glUniform.array[_u5]) {
                        for (var _n5 = _u5, _m5 = _idx5; _n5 < glUniform.array.length; ++_n5, ++_m5) {
                          glUniform.array[_n5] = vf32[_m5];
                        }
                        gl.uniform2fv(glUniform.glLoc, glUniform.array);
                        break;
                      }
                    }
                    break;
                  }
                case gl.FLOAT_VEC3:
                  {
                    for (var _u6 = 0; _u6 < glUniform.array.length; ++_u6) {
                      var _idx6 = glUniform.offset + offset + _u6;
                      if (vf32[_idx6] !== glUniform.array[_u6]) {
                        for (var _n6 = _u6, _m6 = _idx6; _n6 < glUniform.array.length; ++_n6, ++_m6) {
                          glUniform.array[_n6] = vf32[_m6];
                        }
                        gl.uniform3fv(glUniform.glLoc, glUniform.array);
                        break;
                      }
                    }
                    break;
                  }
                case gl.FLOAT_VEC4:
                  {
                    for (var _u7 = 0; _u7 < glUniform.array.length; ++_u7) {
                      var _idx7 = glUniform.offset + offset + _u7;
                      if (vf32[_idx7] !== glUniform.array[_u7]) {
                        for (var _n7 = _u7, _m7 = _idx7; _n7 < glUniform.array.length; ++_n7, ++_m7) {
                          glUniform.array[_n7] = vf32[_m7];
                        }
                        gl.uniform4fv(glUniform.glLoc, glUniform.array);
                        break;
                      }
                    }
                    break;
                  }
                case gl.FLOAT_MAT2:
                  {
                    for (var _u8 = 0; _u8 < glUniform.array.length; ++_u8) {
                      var _idx8 = glUniform.offset + offset + _u8;
                      if (vf32[_idx8] !== glUniform.array[_u8]) {
                        for (var _n8 = _u8, _m8 = _idx8; _n8 < glUniform.array.length; ++_n8, ++_m8) {
                          glUniform.array[_n8] = vf32[_m8];
                        }
                        gl.uniformMatrix2fv(glUniform.glLoc, false, glUniform.array);
                        break;
                      }
                    }
                    break;
                  }
                case gl.FLOAT_MAT3:
                  {
                    for (var _u9 = 0; _u9 < glUniform.array.length; ++_u9) {
                      var _idx9 = glUniform.offset + offset + _u9;
                      if (vf32[_idx9] !== glUniform.array[_u9]) {
                        for (var _n9 = _u9, _m9 = _idx9; _n9 < glUniform.array.length; ++_n9, ++_m9) {
                          glUniform.array[_n9] = vf32[_m9];
                        }
                        gl.uniformMatrix3fv(glUniform.glLoc, false, glUniform.array);
                        break;
                      }
                    }
                    break;
                  }
                case gl.FLOAT_MAT4:
                  {
                    for (var _u10 = 0; _u10 < glUniform.array.length; ++_u10) {
                      var _idx10 = glUniform.offset + offset + _u10;
                      if (vf32[_idx10] !== glUniform.array[_u10]) {
                        for (var _n10 = _u10, _m10 = _idx10; _n10 < glUniform.array.length; ++_n10, ++_m10) {
                          glUniform.array[_n10] = vf32[_m10];
                        }
                        gl.uniformMatrix4fv(glUniform.glLoc, false, glUniform.array);
                        break;
                      }
                    }
                    break;
                  }
              }
            }
            continue;
          }
          var samplerLen = gpuShader.glSamplerTextures.length;
          for (var i = 0; i < samplerLen; i++) {
            var glSampler = gpuShader.glSamplerTextures[i];
            var _gpuDescriptorSet = gpuDescriptorSets[glSampler.set];
            var descriptorIndex = _gpuDescriptorSet && _gpuDescriptorSet.descriptorIndices[glSampler.binding];
            var _gpuDescriptor = descriptorIndex >= 0 && _gpuDescriptorSet.gpuDescriptors[descriptorIndex];
            var texUnitLen = glSampler.units.length;
            for (var _l = 0; _l < texUnitLen; _l++) {
              var texUnit = glSampler.units[_l];
              if (!_gpuDescriptor || !_gpuDescriptor.gpuSampler) {
                continue;
              }
              if (_gpuDescriptor.gpuTexture && _gpuDescriptor.gpuTexture.size > 0) {
                var _gpuDescriptor2 = _gpuDescriptor,
                  gpuTexture = _gpuDescriptor2.gpuTexture;
                var glTexUnit = cache.glTexUnits[texUnit];
                if (glTexUnit.glTexture !== gpuTexture.glTexture) {
                  if (cache.texUnit !== texUnit) {
                    gl.activeTexture(gl.TEXTURE0 + texUnit);
                    cache.texUnit = texUnit;
                  }
                  if (gpuTexture.glTexture) {
                    gl.bindTexture(gpuTexture.glTarget, gpuTexture.glTexture);
                  } else {
                    gl.bindTexture(gpuTexture.glTarget, device.nullTex2D.gpuTexture.glTexture);
                  }
                  glTexUnit.glTexture = gpuTexture.glTexture;
                }
                var _gpuDescriptor3 = _gpuDescriptor,
                  gpuSampler = _gpuDescriptor3.gpuSampler;
                if (gpuTexture.isPowerOf2) {
                  glWrapS = gpuSampler.glWrapS;
                  glWrapT = gpuSampler.glWrapT;
                } else {
                  glWrapS = gl.CLAMP_TO_EDGE;
                  glWrapT = gl.CLAMP_TO_EDGE;
                }
                if (gpuTexture.isPowerOf2) {
                  if (gpuTexture.mipLevel <= 1 && (gpuSampler.glMinFilter === gl.LINEAR_MIPMAP_NEAREST || gpuSampler.glMinFilter === gl.LINEAR_MIPMAP_LINEAR)) {
                    glMinFilter = gl.LINEAR;
                  } else {
                    glMinFilter = gpuSampler.glMinFilter;
                  }
                } else if (gpuSampler.glMinFilter === gl.LINEAR || gpuSampler.glMinFilter === gl.LINEAR_MIPMAP_NEAREST || gpuSampler.glMinFilter === gl.LINEAR_MIPMAP_LINEAR) {
                  glMinFilter = gl.LINEAR;
                } else {
                  glMinFilter = gl.NEAREST;
                }
                if (gpuTexture.glWrapS !== glWrapS) {
                  if (cache.texUnit !== texUnit) {
                    gl.activeTexture(gl.TEXTURE0 + texUnit);
                    cache.texUnit = texUnit;
                  }
                  gl.texParameteri(gpuTexture.glTarget, gl.TEXTURE_WRAP_S, glWrapS);
                  gpuTexture.glWrapS = glWrapS;
                }
                if (gpuTexture.glWrapT !== glWrapT) {
                  if (cache.texUnit !== texUnit) {
                    gl.activeTexture(gl.TEXTURE0 + texUnit);
                    cache.texUnit = texUnit;
                  }
                  gl.texParameteri(gpuTexture.glTarget, gl.TEXTURE_WRAP_T, glWrapT);
                  gpuTexture.glWrapT = glWrapT;
                }
                if (gpuTexture.glMinFilter !== glMinFilter) {
                  if (cache.texUnit !== texUnit) {
                    gl.activeTexture(gl.TEXTURE0 + texUnit);
                    cache.texUnit = texUnit;
                  }
                  gl.texParameteri(gpuTexture.glTarget, gl.TEXTURE_MIN_FILTER, glMinFilter);
                  gpuTexture.glMinFilter = glMinFilter;
                }
                if (gpuTexture.glMagFilter !== gpuSampler.glMagFilter) {
                  if (cache.texUnit !== texUnit) {
                    gl.activeTexture(gl.TEXTURE0 + texUnit);
                    cache.texUnit = texUnit;
                  }
                  gl.texParameteri(gpuTexture.glTarget, gl.TEXTURE_MAG_FILTER, gpuSampler.glMagFilter);
                  gpuTexture.glMagFilter = gpuSampler.glMagFilter;
                }
              }
              _gpuDescriptor = _gpuDescriptorSet.gpuDescriptors[++descriptorIndex];
            }
          }
        }
        if (gpuInputAssembler && gpuShader && (isShaderChanged || gfxStateCache$1.gpuInputAssembler !== gpuInputAssembler)) {
          gfxStateCache$1.gpuInputAssembler = gpuInputAssembler;
          var ia = device.extensions.ANGLE_instanced_arrays;
          if (device.extensions.useVAO) {
            var vao = device.extensions.OES_vertex_array_object;
            var glVAO = gpuInputAssembler.glVAOs.get(gpuShader.glProgram);
            if (!glVAO) {
              glVAO = vao.createVertexArrayOES();
              gpuInputAssembler.glVAOs.set(gpuShader.glProgram, glVAO);
              vao.bindVertexArrayOES(glVAO);
              gl.bindBuffer(gl.ARRAY_BUFFER, null);
              gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, null);
              cache.glArrayBuffer = null;
              cache.glElementArrayBuffer = null;
              var glAttrib;
              var inputLen = gpuShader.glInputs.length;
              for (var _j2 = 0; _j2 < inputLen; _j2++) {
                var glInput = gpuShader.glInputs[_j2];
                glAttrib = null;
                var attribLen = gpuInputAssembler.glAttribs.length;
                for (var k = 0; k < attribLen; k++) {
                  var attrib = gpuInputAssembler.glAttribs[k];
                  if (attrib.name === glInput.name) {
                    glAttrib = attrib;
                    break;
                  }
                }
                if (glAttrib) {
                  if (cache.glArrayBuffer !== glAttrib.glBuffer) {
                    gl.bindBuffer(gl.ARRAY_BUFFER, glAttrib.glBuffer);
                    cache.glArrayBuffer = glAttrib.glBuffer;
                  }
                  for (var c = 0; c < glAttrib.componentCount; ++c) {
                    var glLoc = glInput.glLoc + c;
                    var attribOffset = glAttrib.offset + glAttrib.size * c;
                    gl.enableVertexAttribArray(glLoc);
                    cache.glCurrentAttribLocs[glLoc] = true;
                    gl.vertexAttribPointer(glLoc, glAttrib.count, glAttrib.glType, glAttrib.isNormalized, glAttrib.stride, attribOffset);
                    if (ia) {
                      ia.vertexAttribDivisorANGLE(glLoc, glAttrib.isInstanced ? 1 : 0);
                    }
                  }
                }
              }
              var _gpuBuffer = gpuInputAssembler.gpuIndexBuffer;
              if (_gpuBuffer) {
                gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, _gpuBuffer.glBuffer);
              }
              vao.bindVertexArrayOES(null);
              gl.bindBuffer(gl.ARRAY_BUFFER, null);
              gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, null);
              cache.glArrayBuffer = null;
              cache.glElementArrayBuffer = null;
            }
            if (cache.glVAO !== glVAO) {
              vao.bindVertexArrayOES(glVAO);
              cache.glVAO = glVAO;
            }
          } else {
            for (var a = 0; a < device.capabilities.maxVertexAttributes; ++a) {
              cache.glCurrentAttribLocs[a] = false;
            }
            var _inputLen = gpuShader.glInputs.length;
            for (var _j3 = 0; _j3 < _inputLen; _j3++) {
              var _glInput = gpuShader.glInputs[_j3];
              var _glAttrib = null;
              var _attribLen = gpuInputAssembler.glAttribs.length;
              for (var _k5 = 0; _k5 < _attribLen; _k5++) {
                var _attrib = gpuInputAssembler.glAttribs[_k5];
                if (_attrib.name === _glInput.name) {
                  _glAttrib = _attrib;
                  break;
                }
              }
              if (_glAttrib) {
                if (cache.glArrayBuffer !== _glAttrib.glBuffer) {
                  gl.bindBuffer(gl.ARRAY_BUFFER, _glAttrib.glBuffer);
                  cache.glArrayBuffer = _glAttrib.glBuffer;
                }
                for (var _c = 0; _c < _glAttrib.componentCount; ++_c) {
                  var _glLoc4 = _glInput.glLoc + _c;
                  var _attribOffset = _glAttrib.offset + _glAttrib.size * _c;
                  if (!cache.glEnabledAttribLocs[_glLoc4] && _glLoc4 >= 0) {
                    gl.enableVertexAttribArray(_glLoc4);
                    cache.glEnabledAttribLocs[_glLoc4] = true;
                  }
                  cache.glCurrentAttribLocs[_glLoc4] = true;
                  gl.vertexAttribPointer(_glLoc4, _glAttrib.count, _glAttrib.glType, _glAttrib.isNormalized, _glAttrib.stride, _attribOffset);
                  if (ia) {
                    ia.vertexAttribDivisorANGLE(_glLoc4, _glAttrib.isInstanced ? 1 : 0);
                  }
                }
              }
            }
            var _gpuBuffer2 = gpuInputAssembler.gpuIndexBuffer;
            if (_gpuBuffer2) {
              if (cache.glElementArrayBuffer !== _gpuBuffer2.glBuffer) {
                gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, _gpuBuffer2.glBuffer);
                cache.glElementArrayBuffer = _gpuBuffer2.glBuffer;
              }
            }
            for (var _a = 0; _a < device.capabilities.maxVertexAttributes; ++_a) {
              if (cache.glEnabledAttribLocs[_a] !== cache.glCurrentAttribLocs[_a]) {
                gl.disableVertexAttribArray(_a);
                cache.glEnabledAttribLocs[_a] = false;
              }
            }
          }
        }
        if (gpuPipelineState && gpuPipelineState.dynamicStates.length) {
          var dsLen = gpuPipelineState.dynamicStates.length;
          for (var _j4 = 0; _j4 < dsLen; _j4++) {
            var dynamicState = gpuPipelineState.dynamicStates[_j4];
            switch (dynamicState) {
              case DynamicStateFlagBit.LINE_WIDTH:
                {
                  if (cache.rs.lineWidth !== dynamicStates.lineWidth) {
                    gl.lineWidth(dynamicStates.lineWidth);
                    cache.rs.lineWidth = dynamicStates.lineWidth;
                  }
                  break;
                }
              case DynamicStateFlagBit.DEPTH_BIAS:
                {
                  if (cache.rs.depthBias !== dynamicStates.depthBiasConstant || cache.rs.depthBiasSlop !== dynamicStates.depthBiasSlope) {
                    gl.polygonOffset(dynamicStates.depthBiasConstant, dynamicStates.depthBiasSlope);
                    cache.rs.depthBias = dynamicStates.depthBiasConstant;
                    cache.rs.depthBiasSlop = dynamicStates.depthBiasSlope;
                  }
                  break;
                }
              case DynamicStateFlagBit.BLEND_CONSTANTS:
                {
                  var blendConstant = dynamicStates.blendConstant;
                  if (cache.bs.blendColor.x !== blendConstant.x || cache.bs.blendColor.y !== blendConstant.y || cache.bs.blendColor.z !== blendConstant.z || cache.bs.blendColor.w !== blendConstant.w) {
                    gl.blendColor(blendConstant.x, blendConstant.y, blendConstant.z, blendConstant.w);
                    cache.bs.blendColor.copy(blendConstant);
                  }
                  break;
                }
              case DynamicStateFlagBit.STENCIL_WRITE_MASK:
                {
                  var front = dynamicStates.stencilStatesFront;
                  var back = dynamicStates.stencilStatesBack;
                  if (cache.dss.stencilWriteMaskFront !== front.writeMask) {
                    gl.stencilMaskSeparate(gl.FRONT, front.writeMask);
                    cache.dss.stencilWriteMaskFront = front.writeMask;
                  }
                  if (cache.dss.stencilWriteMaskBack !== back.writeMask) {
                    gl.stencilMaskSeparate(gl.BACK, back.writeMask);
                    cache.dss.stencilWriteMaskBack = back.writeMask;
                  }
                  break;
                }
              case DynamicStateFlagBit.STENCIL_COMPARE_MASK:
                {
                  var _front = dynamicStates.stencilStatesFront;
                  var _back = dynamicStates.stencilStatesBack;
                  if (cache.dss.stencilRefFront !== _front.reference || cache.dss.stencilReadMaskFront !== _front.compareMask) {
                    gl.stencilFuncSeparate(gl.FRONT, WebGLCmpFuncs$1[cache.dss.stencilFuncFront], _front.reference, _front.compareMask);
                    cache.dss.stencilRefFront = _front.reference;
                    cache.dss.stencilReadMaskFront = _front.compareMask;
                  }
                  if (cache.dss.stencilRefBack !== _back.reference || cache.dss.stencilReadMaskBack !== _back.compareMask) {
                    gl.stencilFuncSeparate(gl.BACK, WebGLCmpFuncs$1[cache.dss.stencilFuncBack], _back.reference, _back.compareMask);
                    cache.dss.stencilRefBack = _back.reference;
                    cache.dss.stencilReadMaskBack = _back.compareMask;
                  }
                  break;
                }
            }
          }
        }
      }
      function WebGLCmdFuncDraw(device, drawInfo) {
        var gl = device.gl;
        var _device$extensions = device.extensions,
          ia = _device$extensions.ANGLE_instanced_arrays,
          md = _device$extensions.WEBGL_multi_draw;
        var gpuInputAssembler = gfxStateCache$1.gpuInputAssembler,
          glPrimitive = gfxStateCache$1.glPrimitive;
        if (gpuInputAssembler) {
          var indexBuffer = gpuInputAssembler.gpuIndexBuffer;
          if (gpuInputAssembler.gpuIndirectBuffer) {
            var indirects = gpuInputAssembler.gpuIndirectBuffer.indirects;
            if (indirects.drawByIndex) {
              for (var j = 0; j < indirects.drawCount; j++) {
                indirects.byteOffsets[j] = indirects.offsets[j] * indexBuffer.stride;
              }
              if (md) {
                if (indirects.instancedDraw) {
                  md.multiDrawElementsInstancedWEBGL(glPrimitive, indirects.counts, 0, gpuInputAssembler.glIndexType, indirects.byteOffsets, 0, indirects.instances, 0, indirects.drawCount);
                } else {
                  md.multiDrawElementsWEBGL(glPrimitive, indirects.counts, 0, gpuInputAssembler.glIndexType, indirects.byteOffsets, 0, indirects.drawCount);
                }
              } else {
                for (var _j5 = 0; _j5 < indirects.drawCount; _j5++) {
                  if (indirects.instances[_j5] && ia) {
                    ia.drawElementsInstancedANGLE(glPrimitive, indirects.counts[_j5], gpuInputAssembler.glIndexType, indirects.byteOffsets[_j5], indirects.instances[_j5]);
                  } else {
                    gl.drawElements(glPrimitive, indirects.counts[_j5], gpuInputAssembler.glIndexType, indirects.byteOffsets[_j5]);
                  }
                }
              }
            } else if (md) {
              if (indirects.instancedDraw) {
                md.multiDrawArraysInstancedWEBGL(glPrimitive, indirects.offsets, 0, indirects.counts, 0, indirects.instances, 0, indirects.drawCount);
              } else {
                md.multiDrawArraysWEBGL(glPrimitive, indirects.offsets, 0, indirects.counts, 0, indirects.drawCount);
              }
            } else {
              for (var _j6 = 0; _j6 < indirects.drawCount; _j6++) {
                if (indirects.instances[_j6] && ia) {
                  ia.drawArraysInstancedANGLE(glPrimitive, indirects.offsets[_j6], indirects.counts[_j6], indirects.instances[_j6]);
                } else {
                  gl.drawArrays(glPrimitive, indirects.offsets[_j6], indirects.counts[_j6]);
                }
              }
            }
          } else if (drawInfo.instanceCount && ia) {
            if (indexBuffer) {
              if (drawInfo.indexCount > 0) {
                var offset = drawInfo.firstIndex * indexBuffer.stride;
                ia.drawElementsInstancedANGLE(glPrimitive, drawInfo.indexCount, gpuInputAssembler.glIndexType, offset, drawInfo.instanceCount);
              }
            } else if (drawInfo.vertexCount > 0) {
              ia.drawArraysInstancedANGLE(glPrimitive, drawInfo.firstVertex, drawInfo.vertexCount, drawInfo.instanceCount);
            }
          } else if (indexBuffer) {
            if (drawInfo.indexCount > 0) {
              var _offset = drawInfo.firstIndex * indexBuffer.stride;
              gl.drawElements(glPrimitive, drawInfo.indexCount, gpuInputAssembler.glIndexType, _offset);
            }
          } else if (drawInfo.vertexCount > 0) {
            gl.drawArrays(glPrimitive, drawInfo.firstVertex, drawInfo.vertexCount);
          }
        }
      }
      var cmdIds$1 = new Array(WebGLCmd.COUNT);
      function WebGLCmdFuncExecuteCmds(device, cmdPackage) {
        cmdIds$1.fill(0);
        for (var i = 0; i < cmdPackage.cmds.length; ++i) {
          var cmd = cmdPackage.cmds.array[i];
          var cmdId = cmdIds$1[cmd]++;
          switch (cmd) {
            case WebGLCmd.BEGIN_RENDER_PASS:
              {
                var cmd0 = cmdPackage.beginRenderPassCmds.array[cmdId];
                WebGLCmdFuncBeginRenderPass(device, cmd0.gpuRenderPass, cmd0.gpuFramebuffer, cmd0.renderArea, cmd0.clearColors, cmd0.clearDepth, cmd0.clearStencil);
                break;
              }
            case WebGLCmd.BIND_STATES:
              {
                var cmd2 = cmdPackage.bindStatesCmds.array[cmdId];
                WebGLCmdFuncBindStates(device, cmd2.gpuPipelineState, cmd2.gpuInputAssembler, cmd2.gpuDescriptorSets, cmd2.dynamicOffsets, cmd2.dynamicStates);
                break;
              }
            case WebGLCmd.DRAW:
              {
                var cmd3 = cmdPackage.drawCmds.array[cmdId];
                WebGLCmdFuncDraw(device, cmd3.drawInfo);
                break;
              }
            case WebGLCmd.UPDATE_BUFFER:
              {
                var cmd4 = cmdPackage.updateBufferCmds.array[cmdId];
                WebGLCmdFuncUpdateBuffer(device, cmd4.gpuBuffer, cmd4.buffer, cmd4.offset, cmd4.size);
                break;
              }
            case WebGLCmd.COPY_BUFFER_TO_TEXTURE:
              {
                var cmd5 = cmdPackage.copyBufferToTextureCmds.array[cmdId];
                WebGLCmdFuncCopyBuffersToTexture(device, cmd5.buffers, cmd5.gpuTexture, cmd5.regions);
                break;
              }
            case WebGLCmd.BLIT_TEXTURE:
              {
                var cmd6 = cmdPackage.blitTextureCmds.array[cmdId];
                WebGLCmdFuncBlitTexture(device, cmd6.srcTexture, cmd6.dstTexture, cmd6.regions, cmd6.filter);
                break;
              }
          }
        }
      }
      function WebGLCmdFuncCopyTexImagesToTexture(device, texImages, gpuTexture, regions) {
        var gl = device.gl;
        var glTexUnit = device.stateCache.glTexUnits[device.stateCache.texUnit];
        if (glTexUnit.glTexture !== gpuTexture.glTexture) {
          gl.bindTexture(gpuTexture.glTarget, gpuTexture.glTexture);
          glTexUnit.glTexture = gpuTexture.glTexture;
        }
        var n = 0;
        var f = 0;
        switch (gpuTexture.glTarget) {
          case gl.TEXTURE_2D:
            {
              for (var i = 0; i < regions.length; i++) {
                var region = regions[i];
                gl.texSubImage2D(gl.TEXTURE_2D, region.texSubres.mipLevel, region.texOffset.x, region.texOffset.y, gpuTexture.glFormat, gpuTexture.glType, texImages[n++]);
              }
              break;
            }
          case gl.TEXTURE_CUBE_MAP:
            {
              for (var _i19 = 0; _i19 < regions.length; _i19++) {
                var _region = regions[_i19];
                var fcount = _region.texSubres.baseArrayLayer + _region.texSubres.layerCount;
                for (f = _region.texSubres.baseArrayLayer; f < fcount; ++f) {
                  gl.texSubImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + f, _region.texSubres.mipLevel, _region.texOffset.x, _region.texOffset.y, gpuTexture.glFormat, gpuTexture.glType, texImages[n++]);
                }
              }
              break;
            }
          default:
            {
              error('Unsupported GL texture type, copy buffer to texture failed.');
            }
        }
        if (gpuTexture.flags & TextureFlagBit.GEN_MIPMAP && gpuTexture.isPowerOf2) {
          gl.generateMipmap(gpuTexture.glTarget);
        }
      }
      var stagingBuffer$1 = new Uint8Array(1);
      function pixelBufferPick$1(buffer, format, offset, stride, extent) {
        var blockHeight = formatAlignment(format).height;
        var bufferSize = FormatSize(format, extent.width, extent.height, extent.depth);
        var rowStride = FormatSize(format, stride.width, 1, 1);
        var sliceStride = FormatSize(format, stride.width, stride.height, 1);
        var chunkSize = FormatSize(format, extent.width, 1, 1);
        var ArrayBufferCtor = getTypedArrayConstructor(FormatInfos[format]);
        if (stagingBuffer$1.byteLength < bufferSize) {
          stagingBuffer$1 = new Uint8Array(bufferSize);
        }
        var destOffset = 0;
        var bufferOffset = offset;
        for (var i = 0; i < extent.depth; i++) {
          bufferOffset = offset + sliceStride * i;
          for (var j = 0; j < extent.height; j += blockHeight) {
            stagingBuffer$1.subarray(destOffset, destOffset + chunkSize).set(new Uint8Array(buffer.buffer, buffer.byteOffset + bufferOffset, chunkSize));
            destOffset += chunkSize;
            bufferOffset += rowStride;
          }
        }
        var length = bufferSize / ArrayBufferCtor.BYTES_PER_ELEMENT;
        assertID(Number.isInteger(length), 9101);
        return new ArrayBufferCtor(stagingBuffer$1.buffer, 0, length);
      }
      function WebGLCmdFuncCopyBuffersToTexture(device, buffers, gpuTexture, regions) {
        var gl = device.gl;
        var glTexUnit = device.stateCache.glTexUnits[device.stateCache.texUnit];
        if (glTexUnit.glTexture !== gpuTexture.glTexture) {
          gl.bindTexture(gpuTexture.glTarget, gpuTexture.glTexture);
          glTexUnit.glTexture = gpuTexture.glTexture;
        }
        var n = 0;
        var f = 0;
        var fmtInfo = FormatInfos[gpuTexture.format];
        var ArrayBufferCtor = getTypedArrayConstructor(fmtInfo);
        var isCompressed = fmtInfo.isCompressed;
        var blockSize = formatAlignment(gpuTexture.format);
        var extent = new Extent();
        var offset = new Offset();
        var stride = new Extent();
        switch (gpuTexture.glTarget) {
          case gl.TEXTURE_2D:
            {
              for (var i = 0; i < regions.length; i++) {
                var region = regions[i];
                var mipLevel = region.texSubres.mipLevel;
                offset.x = region.texOffset.x === 0 ? 0 : alignTo(region.texOffset.x, blockSize.width);
                offset.y = region.texOffset.y === 0 ? 0 : alignTo(region.texOffset.y, blockSize.height);
                extent.width = region.texExtent.width < blockSize.width ? region.texExtent.width : alignTo(region.texExtent.width, blockSize.width);
                extent.height = region.texExtent.height < blockSize.height ? region.texExtent.width : alignTo(region.texExtent.height, blockSize.height);
                stride.width = region.buffStride > 0 ? region.buffStride : extent.width;
                stride.height = region.buffTexHeight > 0 ? region.buffTexHeight : extent.height;
                var destWidth = region.texExtent.width + offset.x === gpuTexture.width >> mipLevel ? region.texExtent.width : extent.width;
                var destHeight = region.texExtent.height + offset.y === gpuTexture.height >> mipLevel ? region.texExtent.height : extent.height;
                var pixels = void 0;
                var buffer = buffers[n++];
                if (stride.width === extent.width && stride.height === extent.height) {
                  var length = FormatSize(gpuTexture.format, destWidth, destHeight, 1) / ArrayBufferCtor.BYTES_PER_ELEMENT;
                  assertID(Number.isInteger(length), 9101);
                  pixels = new ArrayBufferCtor(buffer.buffer, buffer.byteOffset + region.buffOffset, length);
                } else {
                  pixels = pixelBufferPick$1(buffer, gpuTexture.format, region.buffOffset, stride, extent);
                }
                if (!isCompressed) {
                  gl.texSubImage2D(gl.TEXTURE_2D, mipLevel, offset.x, offset.y, destWidth, destHeight, gpuTexture.glFormat, gpuTexture.glType, pixels);
                } else if (gpuTexture.glInternalFmt !== WebGLEXT.COMPRESSED_RGB_ETC1_WEBGL && !device.extensions.noCompressedTexSubImage2D) {
                  gl.compressedTexSubImage2D(gl.TEXTURE_2D, mipLevel, offset.x, offset.y, destWidth, destHeight, gpuTexture.glFormat, pixels);
                } else {
                  gl.compressedTexImage2D(gl.TEXTURE_2D, mipLevel, gpuTexture.glInternalFmt, destWidth, destHeight, 0, pixels);
                }
              }
              break;
            }
          case gl.TEXTURE_CUBE_MAP:
            {
              for (var _i20 = 0; _i20 < regions.length; _i20++) {
                var _region2 = regions[_i20];
                var _mipLevel = _region2.texSubres.mipLevel;
                offset.x = _region2.texOffset.x === 0 ? 0 : alignTo(_region2.texOffset.x, blockSize.width);
                offset.y = _region2.texOffset.y === 0 ? 0 : alignTo(_region2.texOffset.y, blockSize.height);
                extent.width = _region2.texExtent.width < blockSize.width ? _region2.texExtent.width : alignTo(_region2.texExtent.width, blockSize.width);
                extent.height = _region2.texExtent.height < blockSize.height ? _region2.texExtent.width : alignTo(_region2.texExtent.height, blockSize.height);
                stride.width = _region2.buffStride > 0 ? _region2.buffStride : extent.width;
                stride.height = _region2.buffTexHeight > 0 ? _region2.buffTexHeight : extent.height;
                var _destWidth = _region2.texExtent.width + offset.x === gpuTexture.width >> _mipLevel ? _region2.texExtent.width : extent.width;
                var _destHeight = _region2.texExtent.height + offset.y === gpuTexture.height >> _mipLevel ? _region2.texExtent.height : extent.height;
                var fcount = _region2.texSubres.baseArrayLayer + _region2.texSubres.layerCount;
                for (f = _region2.texSubres.baseArrayLayer; f < fcount; ++f) {
                  var _pixels = void 0;
                  var _buffer = buffers[n++];
                  if (stride.width === extent.width && stride.height === extent.height) {
                    var _length = FormatSize(gpuTexture.format, _destWidth, _destHeight, 1) / ArrayBufferCtor.BYTES_PER_ELEMENT;
                    assertID(Number.isInteger(_length), 9101);
                    _pixels = new ArrayBufferCtor(_buffer.buffer, _buffer.byteOffset + _region2.buffOffset, _length);
                  } else {
                    _pixels = pixelBufferPick$1(_buffer, gpuTexture.format, _region2.buffOffset, stride, extent);
                  }
                  if (!isCompressed) {
                    gl.texSubImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + f, _mipLevel, offset.x, offset.y, _destWidth, _destHeight, gpuTexture.glFormat, gpuTexture.glType, _pixels);
                  } else if (gpuTexture.glInternalFmt !== WebGLEXT.COMPRESSED_RGB_ETC1_WEBGL && !device.extensions.noCompressedTexSubImage2D) {
                    gl.compressedTexSubImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + f, _mipLevel, offset.x, offset.y, _destWidth, _destHeight, gpuTexture.glFormat, _pixels);
                  } else {
                    gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + f, _mipLevel, gpuTexture.glInternalFmt, _destWidth, _destHeight, 0, _pixels);
                  }
                }
              }
              break;
            }
          default:
            {
              error('Unsupported GL texture type, copy buffer to texture failed.');
            }
        }
        if (gpuTexture.flags & TextureFlagBit.GEN_MIPMAP) {
          gl.generateMipmap(gpuTexture.glTarget);
        }
      }
      function WebGLCmdFuncCopyTextureToBuffers(device, gpuTexture, buffers, regions) {
        var gl = device.gl;
        var cache = device.stateCache;
        var framebuffer = gl.createFramebuffer();
        gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
        var x = 0;
        var y = 0;
        var w = 1;
        var h = 1;
        switch (gpuTexture.glTarget) {
          case gl.TEXTURE_2D:
            {
              for (var k = 0; k < regions.length; k++) {
                var region = regions[k];
                gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gpuTexture.glTarget, gpuTexture.glTexture, region.texSubres.mipLevel);
                x = region.texOffset.x;
                y = region.texOffset.y;
                w = region.texExtent.width;
                h = region.texExtent.height;
                gl.readPixels(x, y, w, h, gpuTexture.glFormat, gpuTexture.glType, buffers[k]);
              }
              break;
            }
          default:
            {
              error('Unsupported GL texture type, copy texture to buffers failed.');
            }
        }
        gl.bindFramebuffer(gl.FRAMEBUFFER, null);
        cache.glFramebuffer = null;
        gl.deleteFramebuffer(framebuffer);
      }
      function WebGLCmdFuncBlitTexture(device, srcTexture, dstTexture, regions, filter) {
        device.blitManager.draw(srcTexture, dstTexture, regions, filter);
      }

      var WebGLIndirectDrawInfos = function () {
        function WebGLIndirectDrawInfos() {
          this.counts = void 0;
          this.offsets = void 0;
          this.instances = void 0;
          this.drawCount = 0;
          this.drawByIndex = false;
          this.instancedDraw = false;
          this.byteOffsets = void 0;
          this._capacity = 4;
          this.counts = new Int32Array(this._capacity);
          this.offsets = new Int32Array(this._capacity);
          this.instances = new Int32Array(this._capacity);
          this.byteOffsets = new Int32Array(this._capacity);
        }
        var _proto = WebGLIndirectDrawInfos.prototype;
        _proto.clearDraws = function clearDraws() {
          this.drawCount = 0;
          this.drawByIndex = false;
          this.instancedDraw = false;
        };
        _proto.setDrawInfo = function setDrawInfo(idx, info) {
          this._ensureCapacity(idx);
          this.drawByIndex = info.indexCount > 0;
          this.instancedDraw = !!info.instanceCount;
          this.drawCount = Math.max(idx + 1, this.drawCount);
          if (this.drawByIndex) {
            this.counts[idx] = info.indexCount;
            this.offsets[idx] = info.firstIndex;
          } else {
            this.counts[idx] = info.vertexCount;
            this.offsets[idx] = info.firstVertex;
          }
          this.instances[idx] = Math.max(1, info.instanceCount);
        };
        _proto._ensureCapacity = function _ensureCapacity(target) {
          if (this._capacity > target) return;
          this._capacity = nextPow2(target);
          var counts = new Int32Array(this._capacity);
          var offsets = new Int32Array(this._capacity);
          var instances = new Int32Array(this._capacity);
          this.byteOffsets = new Int32Array(this._capacity);
          counts.set(this.counts);
          offsets.set(this.offsets);
          instances.set(this.instances);
          this.counts = counts;
          this.offsets = offsets;
          this.instances = instances;
        };
        return WebGLIndirectDrawInfos;
      }();
      var IWebGLBlitManager = function () {
        function IWebGLBlitManager() {
          this._gpuShader = null;
          this._gpuDescriptorSetLayout = null;
          this._gpuPipelineLayout = null;
          this._gpuPipelineState = null;
          this._gpuVertexBuffer = null;
          this._gpuInputAssembler = null;
          this._gpuPointSampler = null;
          this._gpuLinearSampler = null;
          this._gpuDescriptorSet = null;
          this._gpuUniformBuffer = null;
          this._drawInfo = null;
          this._glFramebuffer = null;
          this._uniformBuffer = null;
          var gl = WebGLDeviceManager.instance.gl;
          var device = WebGLDeviceManager.instance;
          var samplerOffset = device.bindingMappingInfo.maxBlockCounts[0];
          this._gpuShader = {
            name: 'Blit Pass',
            blocks: [new UniformBlock(0, 0, "BlitParams", [new Uniform("tilingOffsetSrc", Type$1.FLOAT4, 1), new Uniform("tilingOffsetDst", Type$1.FLOAT4, 1)], 1)],
            samplerTextures: [new UniformSamplerTexture(0, samplerOffset, 'textureSrc', Type$1.SAMPLER2D, 1)],
            subpassInputs: [],
            gpuStages: [{
              type: ShaderStageFlagBit.VERTEX,
              source: "\n                    precision mediump float;\n\n                    attribute vec2 a_position;\n                    attribute vec2 a_texCoord;\n            \n                    uniform vec4 tilingOffsetSrc;\n                    uniform vec4 tilingOffsetDst;\n            \n                    varying vec2 v_texCoord;\n            \n                    void main() {\n                        v_texCoord = a_texCoord * tilingOffsetSrc.xy + tilingOffsetSrc.zw;\n                        gl_Position = vec4((a_position + 1.0) * tilingOffsetDst.xy - 1.0 + tilingOffsetDst.zw * 2.0, 0, 1);\n                    }",
              glShader: null
            }, {
              type: ShaderStageFlagBit.FRAGMENT,
              source: "\n                    precision mediump float;\n                    uniform sampler2D textureSrc;\n\n                    varying vec2 v_texCoord;\n                    \n                    void main() {\n                        gl_FragColor = texture2D(textureSrc, v_texCoord);\n                    }",
              glShader: null
            }],
            glProgram: null,
            glInputs: [],
            glUniforms: [],
            glBlocks: [],
            glSamplerTextures: []
          };
          WebGLCmdFuncCreateShader(WebGLDeviceManager.instance, this._gpuShader);
          this._gpuDescriptorSetLayout = {
            bindings: [new DescriptorSetLayoutBinding(0, DescriptorType.UNIFORM_BUFFER, 1, ShaderStageFlagBit.VERTEX), new DescriptorSetLayoutBinding(samplerOffset, DescriptorType.SAMPLER_TEXTURE, 1, ShaderStageFlagBit.FRAGMENT)],
            dynamicBindings: [],
            descriptorIndices: [],
            descriptorCount: samplerOffset + 1
          };
          for (var i = 0; i < samplerOffset; i++) {
            this._gpuDescriptorSetLayout.descriptorIndices[i] = 0;
          }
          this._gpuDescriptorSetLayout.descriptorIndices.push(1);
          this._gpuPipelineLayout = {
            gpuSetLayouts: [this._gpuDescriptorSetLayout],
            dynamicOffsetCount: 0,
            dynamicOffsetOffsets: [0],
            dynamicOffsetIndices: [[]]
          };
          this._gpuPipelineState = {
            glPrimitive: gl.TRIANGLE_STRIP,
            gpuShader: this._gpuShader,
            gpuPipelineLayout: this._gpuPipelineLayout,
            rs: null,
            dss: new DepthStencilState(false, false),
            bs: null,
            dynamicStates: [],
            gpuRenderPass: null
          };
          this._gpuVertexBuffer = {
            usage: BufferUsageBit.VERTEX,
            memUsage: MemoryUsageBit.DEVICE,
            size: 16 * Float32Array.BYTES_PER_ELEMENT,
            stride: 4 * Float32Array.BYTES_PER_ELEMENT,
            buffer: null,
            vf32: null,
            indirects: new WebGLIndirectDrawInfos(),
            glTarget: 0,
            glBuffer: null
          };
          WebGLCmdFuncCreateBuffer(WebGLDeviceManager.instance, this._gpuVertexBuffer);
          WebGLDeviceManager.instance.memoryStatus.bufferSize += this._gpuVertexBuffer.size;
          var data = new Float32Array([-1.0, -1.0, 0.0, 0.0, 1.0, -1.0, 1.0, 0.0, -1.0, 1.0, 0.0, 1.0, 1.0, 1.0, 1.0, 1.0]);
          WebGLCmdFuncUpdateBuffer(WebGLDeviceManager.instance, this._gpuVertexBuffer, data, 0, data.length);
          this._gpuInputAssembler = {
            attributes: [new Attribute("a_position", Format.RG32F), new Attribute("a_texCoord", Format.RG32F)],
            gpuVertexBuffers: [this._gpuVertexBuffer],
            gpuIndexBuffer: null,
            gpuIndirectBuffer: null,
            glAttribs: [],
            glIndexType: 0,
            glVAOs: new Map()
          };
          WebGLCmdFuncCreateInputAssember(WebGLDeviceManager.instance, this._gpuInputAssembler);
          this._gpuPointSampler = {
            glMinFilter: 0x2600,
            glMagFilter: 0x2600,
            glWrapS: 0x2901,
            glWrapT: 0x2901,
            glWrapR: 0x2901
          };
          this._gpuLinearSampler = {
            glMinFilter: 0x2601,
            glMagFilter: 0x2601,
            glWrapS: 0x2901,
            glWrapT: 0x2901,
            glWrapR: 0x2901
          };
          this._uniformBuffer = new Float32Array(8);
          this._gpuUniformBuffer = {
            usage: BufferUsageBit.UNIFORM,
            memUsage: MemoryUsageBit.DEVICE,
            size: 8 * Float32Array.BYTES_PER_ELEMENT,
            stride: 8 * Float32Array.BYTES_PER_ELEMENT,
            buffer: this._uniformBuffer,
            vf32: null,
            indirects: new WebGLIndirectDrawInfos(),
            glTarget: 0,
            glBuffer: null
          };
          WebGLCmdFuncCreateBuffer(WebGLDeviceManager.instance, this._gpuUniformBuffer);
          WebGLDeviceManager.instance.memoryStatus.bufferSize += this._gpuUniformBuffer.size;
          this._gpuDescriptorSet = {
            gpuDescriptors: [{
              type: DescriptorType.UNIFORM_BUFFER,
              gpuBuffer: this._gpuUniformBuffer,
              gpuTexture: null,
              gpuSampler: null
            }, {
              type: DescriptorType.SAMPLER_TEXTURE,
              gpuBuffer: null,
              gpuTexture: null,
              gpuSampler: null
            }],
            descriptorIndices: this._gpuDescriptorSetLayout.descriptorIndices
          };
          this._drawInfo = new DrawInfo(4, 0, 0, 0, 0, 0, 0);
          this._glFramebuffer = WebGLDeviceManager.instance.gl.createFramebuffer();
        }
        var _proto2 = IWebGLBlitManager.prototype;
        _proto2.destroy = function destroy() {
          if (this._glFramebuffer) {
            WebGLDeviceManager.instance.gl.deleteFramebuffer(this._glFramebuffer);
            this._glFramebuffer = null;
          }
          if (this._gpuVertexBuffer) {
            WebGLDeviceManager.instance.memoryStatus.bufferSize -= this._gpuVertexBuffer.size;
            WebGLCmdFuncDestroyBuffer(WebGLDeviceManager.instance, this._gpuVertexBuffer);
          }
          if (this._gpuUniformBuffer) {
            WebGLDeviceManager.instance.memoryStatus.bufferSize -= this._gpuUniformBuffer.size;
            WebGLCmdFuncDestroyBuffer(WebGLDeviceManager.instance, this._gpuUniformBuffer);
          }
          if (this._gpuShader) {
            WebGLCmdFuncDestroyShader(WebGLDeviceManager.instance, this._gpuShader);
          }
          if (this._gpuInputAssembler) {
            WebGLCmdFuncDestroyInputAssembler(WebGLDeviceManager.instance, this._gpuInputAssembler);
          }
        };
        _proto2.draw = function draw(gpuTextureSrc, gpuTextureDst, regions, filter) {
          var device = WebGLDeviceManager.instance;
          var gl = device.gl;
          var stateCache = device.stateCache;
          var origFramebuffer = stateCache.glFramebuffer;
          gl.viewport(0, 0, gpuTextureDst.width, gpuTextureDst.height);
          gl.scissor(0, 0, gpuTextureDst.width, gpuTextureDst.height);
          if (!this._uniformBuffer || !this._gpuUniformBuffer || !this._gpuPipelineState || !this._gpuInputAssembler || !this._gpuDescriptorSet || !this._drawInfo) {
            return;
          }
          var descriptor = this._gpuDescriptorSet.gpuDescriptors[1];
          descriptor.gpuTexture = gpuTextureSrc;
          descriptor.gpuSampler = filter === Filter$1.POINT ? this._gpuPointSampler : this._gpuLinearSampler;
          var formatInfo = FormatInfos[gpuTextureDst.format];
          var attachment = gl.COLOR_ATTACHMENT0;
          if (formatInfo.hasStencil) {
            attachment = gl.DEPTH_STENCIL_ATTACHMENT;
          } else if (formatInfo.hasDepth) {
            attachment = gl.DEPTH_ATTACHMENT;
          }
          var regionIndices = regions.map(function (_, i) {
            return i;
          });
          regionIndices.sort(function (a, b) {
            return regions[a].srcSubres.mipLevel - regions[b].srcSubres.mipLevel;
          });
          if (stateCache.glFramebuffer !== this._glFramebuffer) {
            device.gl.bindFramebuffer(device.gl.FRAMEBUFFER, this._glFramebuffer);
            stateCache.glFramebuffer = this._glFramebuffer;
          }
          var mipLevel = regions[0].dstSubres.mipLevel;
          if (gpuTextureDst.glTexture) {
            gl.framebufferTexture2D(gl.FRAMEBUFFER, attachment, gpuTextureDst.glTarget, gpuTextureDst.glTexture, mipLevel);
          } else {
            gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, gpuTextureDst.glRenderbuffer);
          }
          for (var i = 0; i < regionIndices.length; ++i) {
            var region = regions[regionIndices[i]];
            if (gpuTextureSrc.glTexture && mipLevel !== region.srcSubres.mipLevel) {
              mipLevel = region.srcSubres.mipLevel;
              gl.framebufferTexture2D(gl.FRAMEBUFFER, attachment, gpuTextureDst.glTarget, gpuTextureDst.glTexture, mipLevel);
            }
            var srcWidth = gpuTextureSrc.width;
            var srcHeight = gpuTextureSrc.height;
            var dstWidth = gpuTextureDst.width;
            var dstHeight = gpuTextureDst.height;
            this._uniformBuffer[0] = region.srcExtent.width / srcWidth;
            this._uniformBuffer[1] = region.srcExtent.height / srcHeight;
            this._uniformBuffer[2] = region.srcOffset.x / srcWidth;
            this._uniformBuffer[3] = region.srcOffset.y / srcHeight;
            this._uniformBuffer[4] = region.dstExtent.width / dstWidth;
            this._uniformBuffer[5] = region.dstExtent.height / dstHeight;
            this._uniformBuffer[6] = region.dstOffset.x / dstWidth;
            this._uniformBuffer[7] = region.dstOffset.y / dstHeight;
            WebGLCmdFuncUpdateBuffer(device, this._gpuUniformBuffer, this._uniformBuffer, 0, this._uniformBuffer.length * Float32Array.BYTES_PER_ELEMENT);
            WebGLCmdFuncBindStates(device, this._gpuPipelineState, this._gpuInputAssembler, [this._gpuDescriptorSet], [], null);
            WebGLCmdFuncDraw(device, this._drawInfo);
          }
          if (stateCache.glFramebuffer !== origFramebuffer) {
            device.gl.bindFramebuffer(device.gl.FRAMEBUFFER, origFramebuffer);
            stateCache.glFramebuffer = origFramebuffer;
          }
          var origViewport = stateCache.viewport;
          gl.viewport(origViewport.left, origViewport.top, origViewport.width, origViewport.height);
          var origScissor = stateCache.scissorRect;
          gl.scissor(origScissor.x, origScissor.y, origScissor.width, origScissor.height);
        };
        return IWebGLBlitManager;
      }();

      var WebGLBuffer = function (_Buffer) {
        _inheritsLoose(WebGLBuffer, _Buffer);
        function WebGLBuffer() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Buffer.call.apply(_Buffer, [this].concat(args)) || this;
          _this._gpuBuffer = null;
          _this._gpuBufferView = null;
          _this._uniformBuffer = null;
          return _this;
        }
        var _proto = WebGLBuffer.prototype;
        _proto.initialize = function initialize(info) {
          if ('buffer' in info) {
            this._isBufferView = true;
            var buffer = info.buffer;
            this._usage = buffer.usage;
            this._memUsage = buffer.memUsage;
            this._size = this._stride = info.range;
            this._count = 1;
            this._flags = buffer.flags;
            this._gpuBufferView = {
              gpuBuffer: buffer.gpuBuffer,
              offset: info.offset,
              range: info.range
            };
          } else {
            this._usage = info.usage;
            this._memUsage = info.memUsage;
            this._size = info.size;
            this._stride = Math.max(info.stride || this._size, 1);
            this._count = this._size / this._stride;
            this._flags = info.flags;
            if (this._usage & BufferUsageBit.UNIFORM && this._size > 0) {
              this._uniformBuffer = new Uint8Array(this._size);
            }
            this._gpuBuffer = {
              usage: this._usage,
              memUsage: this._memUsage,
              size: this._size,
              stride: this._stride,
              buffer: null,
              vf32: null,
              indirects: new WebGLIndirectDrawInfos(),
              glTarget: 0,
              glBuffer: null
            };
            if (this._usage & BufferUsageBit.UNIFORM) {
              this._gpuBuffer.buffer = this._uniformBuffer;
            }
            WebGLCmdFuncCreateBuffer(WebGLDeviceManager.instance, this._gpuBuffer);
            WebGLDeviceManager.instance.memoryStatus.bufferSize += this._size;
          }
        };
        _proto.destroy = function destroy() {
          if (this._gpuBuffer) {
            WebGLCmdFuncDestroyBuffer(WebGLDeviceManager.instance, this._gpuBuffer);
            WebGLDeviceManager.instance.memoryStatus.bufferSize -= this._size;
            this._gpuBuffer = null;
          }
          if (this._gpuBufferView) {
            this._gpuBufferView = null;
          }
        };
        _proto.resize = function resize(size) {
          if (this._isBufferView) {
            console.warn('cannot resize buffer views!');
            return;
          }
          var oldSize = this._size;
          if (oldSize === size) {
            return;
          }
          this._size = size;
          this._count = this._size / this._stride;
          if (this._uniformBuffer) {
            this._uniformBuffer = new Uint8Array(size);
          }
          if (this._gpuBuffer) {
            if (this._uniformBuffer) {
              this._gpuBuffer.buffer = this._uniformBuffer;
            }
            this._gpuBuffer.size = size;
            if (size > 0) {
              WebGLCmdFuncResizeBuffer(WebGLDeviceManager.instance, this._gpuBuffer);
              WebGLDeviceManager.instance.memoryStatus.bufferSize -= oldSize;
              WebGLDeviceManager.instance.memoryStatus.bufferSize += size;
            }
          }
        };
        _proto.update = function update(buffer, size) {
          if (this._isBufferView) {
            console.warn('cannot update through buffer views!');
            return;
          }
          var buffSize;
          if (size !== undefined) {
            buffSize = size;
          } else if (this._usage & BufferUsageBit.INDIRECT) {
            buffSize = 0;
          } else {
            buffSize = buffer.byteLength;
          }
          WebGLCmdFuncUpdateBuffer(WebGLDeviceManager.instance, this._gpuBuffer, buffer, 0, buffSize);
        };
        _createClass(WebGLBuffer, [{
          key: "gpuBuffer",
          get: function get() {
            return this._gpuBuffer;
          }
        }, {
          key: "gpuBufferView",
          get: function get() {
            return this._gpuBufferView;
          }
        }]);
        return WebGLBuffer;
      }(Buffer);

      var WebGLCommandPool = function () {
        function WebGLCommandPool(Clazz, count) {
          this._frees = void 0;
          this._freeIdx = 0;
          this._freeCmds = void 0;
          this._frees = new Array(count);
          this._freeCmds = new CachedArray(count);
          for (var i = 0; i < count; ++i) {
            this._frees[i] = new Clazz();
          }
          this._freeIdx = count - 1;
        }
        var _proto = WebGLCommandPool.prototype;
        _proto.alloc = function alloc(Clazz) {
          if (this._freeIdx < 0) {
            var size = this._frees.length * 2;
            var temp = this._frees;
            this._frees = new Array(size);
            var increase = size - temp.length;
            for (var i = 0; i < increase; ++i) {
              this._frees[i] = new Clazz();
            }
            for (var _i = increase, j = 0; _i < size; ++_i, ++j) {
              this._frees[_i] = temp[j];
            }
            this._freeIdx += increase;
          }
          var cmd = this._frees[this._freeIdx];
          this._frees[this._freeIdx--] = null;
          ++cmd.refCount;
          return cmd;
        };
        _proto.free = function free(cmd) {
          if (--cmd.refCount === 0) {
            this._freeCmds.push(cmd);
          }
        };
        _proto.freeCmds = function freeCmds(cmds) {
          for (var i = 0; i < cmds.length; ++i) {
            if (--cmds.array[i].refCount === 0) {
              this._freeCmds.push(cmds.array[i]);
            }
          }
        };
        _proto.release = function release() {
          for (var i = 0; i < this._freeCmds.length; ++i) {
            var cmd = this._freeCmds.array[i];
            cmd.clear();
            this._frees[++this._freeIdx] = cmd;
          }
          this._freeCmds.clear();
        };
        return WebGLCommandPool;
      }();
      var WebGLCommandAllocator = function () {
        function WebGLCommandAllocator() {
          this.beginRenderPassCmdPool = void 0;
          this.bindStatesCmdPool = void 0;
          this.drawCmdPool = void 0;
          this.updateBufferCmdPool = void 0;
          this.copyBufferToTextureCmdPool = void 0;
          this.blitTextureCmdPool = void 0;
          this.beginRenderPassCmdPool = new WebGLCommandPool(WebGLCmdBeginRenderPass, 1);
          this.bindStatesCmdPool = new WebGLCommandPool(WebGLCmdBindStates, 1);
          this.drawCmdPool = new WebGLCommandPool(WebGLCmdDraw, 1);
          this.updateBufferCmdPool = new WebGLCommandPool(WebGLCmdUpdateBuffer, 1);
          this.copyBufferToTextureCmdPool = new WebGLCommandPool(WebGLCmdCopyBufferToTexture, 1);
          this.blitTextureCmdPool = new WebGLCommandPool(WebGLCmdBlitTexture, 1);
        }
        var _proto2 = WebGLCommandAllocator.prototype;
        _proto2.clearCmds = function clearCmds(cmdPackage) {
          if (cmdPackage.beginRenderPassCmds.length) {
            this.beginRenderPassCmdPool.freeCmds(cmdPackage.beginRenderPassCmds);
            cmdPackage.beginRenderPassCmds.clear();
          }
          if (cmdPackage.bindStatesCmds.length) {
            this.bindStatesCmdPool.freeCmds(cmdPackage.bindStatesCmds);
            cmdPackage.bindStatesCmds.clear();
          }
          if (cmdPackage.drawCmds.length) {
            this.drawCmdPool.freeCmds(cmdPackage.drawCmds);
            cmdPackage.drawCmds.clear();
          }
          if (cmdPackage.updateBufferCmds.length) {
            this.updateBufferCmdPool.freeCmds(cmdPackage.updateBufferCmds);
            cmdPackage.updateBufferCmds.clear();
          }
          if (cmdPackage.copyBufferToTextureCmds.length) {
            this.copyBufferToTextureCmdPool.freeCmds(cmdPackage.copyBufferToTextureCmds);
            cmdPackage.copyBufferToTextureCmds.clear();
          }
          if (cmdPackage.blitTextureCmds.length) {
            this.blitTextureCmdPool.freeCmds(cmdPackage.blitTextureCmds);
            cmdPackage.blitTextureCmds.clear();
          }
          cmdPackage.cmds.clear();
        };
        _proto2.releaseCmds = function releaseCmds() {
          this.beginRenderPassCmdPool.release();
          this.bindStatesCmdPool.release();
          this.drawCmdPool.release();
          this.updateBufferCmdPool.release();
          this.copyBufferToTextureCmdPool.release();
          this.blitTextureCmdPool.release();
        };
        return WebGLCommandAllocator;
      }();

      var WebGLCommandBuffer = function (_CommandBuffer) {
        _inheritsLoose(WebGLCommandBuffer, _CommandBuffer);
        function WebGLCommandBuffer() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _CommandBuffer.call.apply(_CommandBuffer, [this].concat(args)) || this;
          _this.cmdPackage = new WebGLCmdPackage();
          _this._cmdAllocator = new WebGLCommandAllocator();
          _this._isInRenderPass = false;
          _this._curGPUPipelineState = null;
          _this._curGPUInputAssembler = null;
          _this._curGPUDescriptorSets = [];
          _this._curDynamicOffsets = Array(8).fill(0);
          _this._curDynamicStates = new DynamicStates();
          _this._isStateInvalied = false;
          return _this;
        }
        var _proto = WebGLCommandBuffer.prototype;
        _proto.initialize = function initialize(info) {
          this._type = info.type;
          this._queue = info.queue;
          var setCount = WebGLDeviceManager.instance.bindingMappings.blockOffsets.length;
          for (var i = 0; i < setCount; i++) {
            this._curGPUDescriptorSets.push(null);
          }
        };
        _proto.destroy = function destroy() {
          this._cmdAllocator.clearCmds(this.cmdPackage);
        };
        _proto.begin = function begin(renderPass, subpass, frameBuffer) {
          this._cmdAllocator.clearCmds(this.cmdPackage);
          this._curGPUPipelineState = null;
          this._curGPUInputAssembler = null;
          this._curGPUDescriptorSets.length = 0;
          this._numDrawCalls = 0;
          this._numInstances = 0;
          this._numTris = 0;
        };
        _proto.end = function end() {
          if (this._isStateInvalied) {
            this.bindStates();
          }
          this._isInRenderPass = false;
        };
        _proto.beginRenderPass = function beginRenderPass(renderPass, framebuffer, renderArea, clearColors, clearDepth, clearStencil) {
          var cmd = this._cmdAllocator.beginRenderPassCmdPool.alloc(WebGLCmdBeginRenderPass);
          cmd.gpuRenderPass = renderPass.gpuRenderPass;
          cmd.gpuFramebuffer = framebuffer.gpuFramebuffer;
          cmd.renderArea.copy(renderArea);
          cmd.clearColors.length = clearColors.length;
          for (var i = 0; i < clearColors.length; ++i) {
            cmd.clearColors[i] = clearColors[i];
          }
          cmd.clearDepth = clearDepth;
          cmd.clearStencil = clearStencil;
          this.cmdPackage.beginRenderPassCmds.push(cmd);
          this.cmdPackage.cmds.push(WebGLCmd.BEGIN_RENDER_PASS);
          this._isInRenderPass = true;
        };
        _proto.endRenderPass = function endRenderPass() {
          this._isInRenderPass = false;
        };
        _proto.bindPipelineState = function bindPipelineState(pipelineState) {
          var gpuPipelineState = pipelineState.gpuPipelineState;
          if (gpuPipelineState !== this._curGPUPipelineState) {
            this._curGPUPipelineState = gpuPipelineState;
            this._isStateInvalied = true;
          }
        };
        _proto.bindDescriptorSet = function bindDescriptorSet(set, descriptorSet, dynamicOffsets) {
          var gpuDescriptorSet = descriptorSet.gpuDescriptorSet;
          if (gpuDescriptorSet !== this._curGPUDescriptorSets[set]) {
            this._curGPUDescriptorSets[set] = gpuDescriptorSet;
            this._isStateInvalied = true;
          }
          if (dynamicOffsets) {
            var _this$_curGPUPipeline;
            var gpuPipelineLayout = (_this$_curGPUPipeline = this._curGPUPipelineState) === null || _this$_curGPUPipeline === void 0 ? void 0 : _this$_curGPUPipeline.gpuPipelineLayout;
            if (gpuPipelineLayout) {
              var offsets = this._curDynamicOffsets;
              var idx = gpuPipelineLayout.dynamicOffsetOffsets[set];
              for (var i = 0; i < dynamicOffsets.length; i++) offsets[idx + i] = dynamicOffsets[i];
              this._isStateInvalied = true;
            }
          }
        };
        _proto.bindInputAssembler = function bindInputAssembler(inputAssembler) {
          var gpuInputAssembler = inputAssembler.gpuInputAssembler;
          this._curGPUInputAssembler = gpuInputAssembler;
          this._isStateInvalied = true;
        };
        _proto.setViewport = function setViewport(viewport) {
          var cache = this._curDynamicStates.viewport;
          if (cache.left !== viewport.left || cache.top !== viewport.top || cache.width !== viewport.width || cache.height !== viewport.height || cache.minDepth !== viewport.minDepth || cache.maxDepth !== viewport.maxDepth) {
            cache.left = viewport.left;
            cache.top = viewport.top;
            cache.width = viewport.width;
            cache.height = viewport.height;
            cache.minDepth = viewport.minDepth;
            cache.maxDepth = viewport.maxDepth;
            this._isStateInvalied = true;
          }
        };
        _proto.setScissor = function setScissor(scissor) {
          var cache = this._curDynamicStates.scissor;
          if (cache.x !== scissor.x || cache.y !== scissor.y || cache.width !== scissor.width || cache.height !== scissor.height) {
            cache.x = scissor.x;
            cache.y = scissor.y;
            cache.width = scissor.width;
            cache.height = scissor.height;
            this._isStateInvalied = true;
          }
        };
        _proto.setLineWidth = function setLineWidth(lineWidth) {
          if (this._curDynamicStates.lineWidth !== lineWidth) {
            this._curDynamicStates.lineWidth = lineWidth;
            this._isStateInvalied = true;
          }
        };
        _proto.setDepthBias = function setDepthBias(depthBiasConstantFactor, depthBiasClamp, depthBiasSlopeFactor) {
          var cache = this._curDynamicStates;
          if (cache.depthBiasConstant !== depthBiasConstantFactor || cache.depthBiasClamp !== depthBiasClamp || cache.depthBiasSlope !== depthBiasSlopeFactor) {
            cache.depthBiasConstant = depthBiasConstantFactor;
            cache.depthBiasClamp = depthBiasClamp;
            cache.depthBiasSlope = depthBiasSlopeFactor;
            this._isStateInvalied = true;
          }
        };
        _proto.setBlendConstants = function setBlendConstants(blendConstants) {
          var cache = this._curDynamicStates.blendConstant;
          if (cache.x !== blendConstants.x || cache.y !== blendConstants.y || cache.z !== blendConstants.z || cache.w !== blendConstants.w) {
            cache.copy(blendConstants);
            this._isStateInvalied = true;
          }
        };
        _proto.setDepthBound = function setDepthBound(minDepthBounds, maxDepthBounds) {
          var cache = this._curDynamicStates;
          if (cache.depthMinBounds !== minDepthBounds || cache.depthMaxBounds !== maxDepthBounds) {
            cache.depthMinBounds = minDepthBounds;
            cache.depthMaxBounds = maxDepthBounds;
            this._isStateInvalied = true;
          }
        };
        _proto.setStencilWriteMask = function setStencilWriteMask(face, writeMask) {
          var front = this._curDynamicStates.stencilStatesFront;
          var back = this._curDynamicStates.stencilStatesBack;
          if (face & StencilFace.FRONT) {
            if (front.writeMask !== writeMask) {
              front.writeMask = writeMask;
              this._isStateInvalied = true;
            }
          }
          if (face & StencilFace.BACK) {
            if (back.writeMask !== writeMask) {
              back.writeMask = writeMask;
              this._isStateInvalied = true;
            }
          }
        };
        _proto.setStencilCompareMask = function setStencilCompareMask(face, reference, compareMask) {
          var front = this._curDynamicStates.stencilStatesFront;
          var back = this._curDynamicStates.stencilStatesBack;
          if (face & StencilFace.FRONT) {
            if (front.compareMask !== compareMask || front.reference !== reference) {
              front.reference = reference;
              front.compareMask = compareMask;
              this._isStateInvalied = true;
            }
          }
          if (face & StencilFace.BACK) {
            if (back.compareMask !== compareMask || back.reference !== reference) {
              back.reference = reference;
              back.compareMask = compareMask;
              this._isStateInvalied = true;
            }
          }
        };
        _proto.draw = function draw(infoOrAssembler) {
          if (this._type === CommandBufferType.PRIMARY && this._isInRenderPass || this._type === CommandBufferType.SECONDARY) {
            if (this._isStateInvalied) {
              this.bindStates();
            }
            var info = 'drawInfo' in infoOrAssembler ? infoOrAssembler.drawInfo : infoOrAssembler;
            var cmd = this._cmdAllocator.drawCmdPool.alloc(WebGLCmdDraw);
            cmd.drawInfo.copy(info);
            this.cmdPackage.drawCmds.push(cmd);
            this.cmdPackage.cmds.push(WebGLCmd.DRAW);
            ++this._numDrawCalls;
            this._numInstances += info.instanceCount;
            var indexCount = info.indexCount || info.vertexCount;
            if (this._curGPUPipelineState) {
              var glPrimitive = this._curGPUPipelineState.glPrimitive;
              switch (glPrimitive) {
                case 0x0004:
                  {
                    this._numTris += indexCount / 3 * Math.max(info.instanceCount, 1);
                    break;
                  }
                case 0x0005:
                case 0x0006:
                  {
                    this._numTris += (indexCount - 2) * Math.max(info.instanceCount, 1);
                    break;
                  }
              }
            }
          } else {
            console.error('Command \'draw\' must be recorded inside a render pass.');
          }
        };
        _proto.updateBuffer = function updateBuffer(buffer, data, size) {
          if (this._type === CommandBufferType.PRIMARY && !this._isInRenderPass || this._type === CommandBufferType.SECONDARY) {
            var gpuBuffer = buffer.gpuBuffer;
            if (gpuBuffer) {
              var cmd = this._cmdAllocator.updateBufferCmdPool.alloc(WebGLCmdUpdateBuffer);
              var buffSize = 0;
              var buff = null;
              if (buffer.usage & BufferUsageBit.INDIRECT) {
                buff = data;
              } else {
                if (size !== undefined) {
                  buffSize = size;
                } else {
                  buffSize = data.byteLength;
                }
                buff = data;
              }
              cmd.gpuBuffer = gpuBuffer;
              cmd.buffer = buff;
              cmd.offset = 0;
              cmd.size = buffSize;
              this.cmdPackage.updateBufferCmds.push(cmd);
              this.cmdPackage.cmds.push(WebGLCmd.UPDATE_BUFFER);
            }
          } else {
            console.error('Command \'updateBuffer\' must be recorded outside a render pass.');
          }
        };
        _proto.copyBuffersToTexture = function copyBuffersToTexture(buffers, texture, regions) {
          if (this._type === CommandBufferType.PRIMARY && !this._isInRenderPass || this._type === CommandBufferType.SECONDARY) {
            var gpuTexture = texture.gpuTexture;
            if (gpuTexture) {
              var cmd = this._cmdAllocator.copyBufferToTextureCmdPool.alloc(WebGLCmdCopyBufferToTexture);
              if (cmd) {
                cmd.gpuTexture = gpuTexture;
                cmd.regions = regions;
                cmd.buffers = buffers;
                this.cmdPackage.copyBufferToTextureCmds.push(cmd);
                this.cmdPackage.cmds.push(WebGLCmd.COPY_BUFFER_TO_TEXTURE);
              }
            }
          } else {
            console.error('Command \'copyBufferToTexture\' must be recorded outside a render pass.');
          }
        };
        _proto.execute = function execute(cmdBuffs, count) {
          for (var i = 0; i < count; ++i) {
            var webGLCmdBuff = cmdBuffs[i];
            for (var c = 0; c < webGLCmdBuff.cmdPackage.beginRenderPassCmds.length; ++c) {
              var cmd = webGLCmdBuff.cmdPackage.beginRenderPassCmds.array[c];
              ++cmd.refCount;
              this.cmdPackage.beginRenderPassCmds.push(cmd);
            }
            for (var _c = 0; _c < webGLCmdBuff.cmdPackage.bindStatesCmds.length; ++_c) {
              var _cmd = webGLCmdBuff.cmdPackage.bindStatesCmds.array[_c];
              ++_cmd.refCount;
              this.cmdPackage.bindStatesCmds.push(_cmd);
            }
            for (var _c2 = 0; _c2 < webGLCmdBuff.cmdPackage.drawCmds.length; ++_c2) {
              var _cmd2 = webGLCmdBuff.cmdPackage.drawCmds.array[_c2];
              ++_cmd2.refCount;
              this.cmdPackage.drawCmds.push(_cmd2);
            }
            for (var _c3 = 0; _c3 < webGLCmdBuff.cmdPackage.updateBufferCmds.length; ++_c3) {
              var _cmd3 = webGLCmdBuff.cmdPackage.updateBufferCmds.array[_c3];
              ++_cmd3.refCount;
              this.cmdPackage.updateBufferCmds.push(_cmd3);
            }
            for (var _c4 = 0; _c4 < webGLCmdBuff.cmdPackage.copyBufferToTextureCmds.length; ++_c4) {
              var _cmd4 = webGLCmdBuff.cmdPackage.copyBufferToTextureCmds.array[_c4];
              ++_cmd4.refCount;
              this.cmdPackage.copyBufferToTextureCmds.push(_cmd4);
            }
            for (var _c5 = 0; _c5 < webGLCmdBuff.cmdPackage.blitTextureCmds.length; ++_c5) {
              var _cmd5 = webGLCmdBuff.cmdPackage.blitTextureCmds.array[_c5];
              ++_cmd5.refCount;
              this.cmdPackage.blitTextureCmds.push(_cmd5);
            }
            this.cmdPackage.cmds.concat(webGLCmdBuff.cmdPackage.cmds.array);
            this._numDrawCalls += webGLCmdBuff._numDrawCalls;
            this._numInstances += webGLCmdBuff._numInstances;
            this._numTris += webGLCmdBuff._numTris;
          }
        };
        _proto.pipelineBarrier = function pipelineBarrier(GeneralBarrier, bufferBarriers, buffers, textureBarriers, textures) {};
        _proto.bindStates = function bindStates() {
          var bindStatesCmd = this._cmdAllocator.bindStatesCmdPool.alloc(WebGLCmdBindStates);
          if (bindStatesCmd) {
            bindStatesCmd.gpuPipelineState = this._curGPUPipelineState;
            Array.prototype.push.apply(bindStatesCmd.gpuDescriptorSets, this._curGPUDescriptorSets);
            Array.prototype.push.apply(bindStatesCmd.dynamicOffsets, this._curDynamicOffsets);
            bindStatesCmd.gpuInputAssembler = this._curGPUInputAssembler;
            bindStatesCmd.dynamicStates.copy(this._curDynamicStates);
            this.cmdPackage.bindStatesCmds.push(bindStatesCmd);
            this.cmdPackage.cmds.push(WebGLCmd.BIND_STATES);
            this._isStateInvalied = false;
          }
        };
        _proto.blitTexture = function blitTexture(srcTexture, dstTexture, regions, filter) {
          var blitTextureCmd = this._cmdAllocator.blitTextureCmdPool.alloc(WebGLCmdBlitTexture);
          blitTextureCmd.srcTexture = srcTexture.gpuTexture;
          blitTextureCmd.dstTexture = dstTexture.gpuTexture;
          blitTextureCmd.regions = regions;
          blitTextureCmd.filter = filter;
          ++this._numDrawCalls;
          this.cmdPackage.blitTextureCmds.push(blitTextureCmd);
          this.cmdPackage.cmds.push(WebGLCmd.BLIT_TEXTURE);
        };
        return WebGLCommandBuffer;
      }(CommandBuffer);

      var WebGLFramebuffer = function (_Framebuffer) {
        _inheritsLoose(WebGLFramebuffer, _Framebuffer);
        function WebGLFramebuffer() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Framebuffer.call.apply(_Framebuffer, [this].concat(args)) || this;
          _this._gpuFramebuffer = null;
          return _this;
        }
        var _proto = WebGLFramebuffer.prototype;
        _proto.initialize = function initialize(info) {
          this._renderPass = info.renderPass;
          this._colorTextures = info.colorTextures || [];
          this._depthStencilTexture = info.depthStencilTexture || null;
          var lodLevel = 0;
          var gpuColorTextures = [];
          for (var i = 0; i < info.colorTextures.length; ++i) {
            var colorTexture = info.colorTextures[i];
            if (colorTexture) {
              gpuColorTextures.push(colorTexture.gpuTexture);
              lodLevel = colorTexture.lodLevel;
            }
          }
          var gpuDepthStencilTexture = null;
          if (info.depthStencilTexture) {
            gpuDepthStencilTexture = info.depthStencilTexture.gpuTexture;
            lodLevel = info.depthStencilTexture.lodLevel;
          }
          var width = Number.MAX_SAFE_INTEGER;
          var height = Number.MAX_SAFE_INTEGER;
          this._gpuFramebuffer = {
            gpuRenderPass: info.renderPass.gpuRenderPass,
            gpuColorTextures: gpuColorTextures,
            gpuDepthStencilTexture: gpuDepthStencilTexture,
            glFramebuffer: null,
            isOffscreen: true,
            get width() {
              if (this.isOffscreen) {
                return width;
              } else if (this.gpuColorTextures.length > 0) {
                return this.gpuColorTextures[0].width;
              } else {
                return this.gpuDepthStencilTexture.width;
              }
            },
            set width(val) {
              width = val;
            },
            get height() {
              if (this.isOffscreen) {
                return height;
              } else if (this.gpuColorTextures.length > 0) {
                return this.gpuColorTextures[0].height;
              } else {
                return this.gpuDepthStencilTexture.height;
              }
            },
            set height(val) {
              height = val;
            },
            lodLevel: lodLevel
          };
          WebGLCmdFuncCreateFramebuffer(WebGLDeviceManager.instance, this._gpuFramebuffer);
          this._width = this._gpuFramebuffer.width;
          this._height = this._gpuFramebuffer.height;
        };
        _proto.destroy = function destroy() {
          if (this._gpuFramebuffer) {
            WebGLCmdFuncDestroyFramebuffer(WebGLDeviceManager.instance, this._gpuFramebuffer);
            this._gpuFramebuffer = null;
          }
        };
        _createClass(WebGLFramebuffer, [{
          key: "gpuFramebuffer",
          get: function get() {
            return this._gpuFramebuffer;
          }
        }]);
        return WebGLFramebuffer;
      }(Framebuffer);

      var WebGLInputAssembler = function (_InputAssembler) {
        _inheritsLoose(WebGLInputAssembler, _InputAssembler);
        function WebGLInputAssembler() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _InputAssembler.call.apply(_InputAssembler, [this].concat(args)) || this;
          _this._gpuInputAssembler = null;
          return _this;
        }
        var _proto = WebGLInputAssembler.prototype;
        _proto.initialize = function initialize(info) {
          if (info.vertexBuffers.length === 0) {
            console.error('InputAssemblerInfo.vertexBuffers is null.');
            return;
          }
          this._attributes = info.attributes;
          this._attributesHash = this.computeAttributesHash();
          this._vertexBuffers = info.vertexBuffers;
          if (info.indexBuffer) {
            this._indexBuffer = info.indexBuffer;
            this._drawInfo.indexCount = this._indexBuffer.size / this._indexBuffer.stride;
            this._drawInfo.firstIndex = 0;
          } else {
            var vertBuff = this._vertexBuffers[0];
            this._drawInfo.vertexCount = vertBuff.size / vertBuff.stride;
            this._drawInfo.firstVertex = 0;
            this._drawInfo.vertexOffset = 0;
          }
          this._drawInfo.instanceCount = 0;
          this._drawInfo.firstInstance = 0;
          this._indirectBuffer = info.indirectBuffer || null;
          var gpuVertexBuffers = new Array(info.vertexBuffers.length);
          for (var i = 0; i < info.vertexBuffers.length; ++i) {
            var vb = info.vertexBuffers[i];
            if (vb.gpuBuffer) {
              gpuVertexBuffers[i] = vb.gpuBuffer;
            }
          }
          var gpuIndexBuffer = null;
          var glIndexType = 0;
          if (info.indexBuffer) {
            gpuIndexBuffer = info.indexBuffer.gpuBuffer;
            if (gpuIndexBuffer) {
              switch (gpuIndexBuffer.stride) {
                case 1:
                  glIndexType = 0x1401;
                  break;
                case 2:
                  glIndexType = 0x1403;
                  break;
                case 4:
                  glIndexType = 0x1405;
                  break;
                default:
                  {
                    console.error('Error index buffer stride.');
                  }
              }
            }
          }
          var gpuIndirectBuffer = null;
          if (info.indirectBuffer) {
            gpuIndirectBuffer = info.indirectBuffer.gpuBuffer;
          }
          this._gpuInputAssembler = {
            attributes: info.attributes,
            gpuVertexBuffers: gpuVertexBuffers,
            gpuIndexBuffer: gpuIndexBuffer,
            gpuIndirectBuffer: gpuIndirectBuffer,
            glAttribs: [],
            glIndexType: glIndexType,
            glVAOs: new Map()
          };
          WebGLCmdFuncCreateInputAssember(WebGLDeviceManager.instance, this._gpuInputAssembler);
        };
        _proto.destroy = function destroy() {
          var device = WebGLDeviceManager.instance;
          if (this._gpuInputAssembler && device.extensions.useVAO) {
            WebGLCmdFuncDestroyInputAssembler(device, this._gpuInputAssembler);
          }
          this._gpuInputAssembler = null;
        };
        _createClass(WebGLInputAssembler, [{
          key: "gpuInputAssembler",
          get: function get() {
            return this._gpuInputAssembler;
          }
        }]);
        return WebGLInputAssembler;
      }(InputAssembler);

      var WebGLDescriptorSetLayout = function (_DescriptorSetLayout) {
        _inheritsLoose(WebGLDescriptorSetLayout, _DescriptorSetLayout);
        function WebGLDescriptorSetLayout() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _DescriptorSetLayout.call.apply(_DescriptorSetLayout, [this].concat(args)) || this;
          _this._gpuDescriptorSetLayout = null;
          return _this;
        }
        var _proto = WebGLDescriptorSetLayout.prototype;
        _proto.initialize = function initialize(info) {
          Array.prototype.push.apply(this._bindings, info.bindings);
          var descriptorCount = 0;
          var maxBinding = -1;
          var flattenedIndices = [];
          for (var i = 0; i < this._bindings.length; i++) {
            var binding = this._bindings[i];
            flattenedIndices.push(descriptorCount);
            descriptorCount += binding.count;
            if (binding.binding > maxBinding) maxBinding = binding.binding;
          }
          this._bindingIndices = Array(maxBinding + 1).fill(-1);
          var descriptorIndices = this._descriptorIndices = Array(maxBinding + 1).fill(-1);
          for (var _i = 0; _i < this._bindings.length; _i++) {
            var _binding = this._bindings[_i];
            this._bindingIndices[_binding.binding] = _i;
            descriptorIndices[_binding.binding] = flattenedIndices[_i];
          }
          var dynamicBindings = [];
          for (var _i2 = 0; _i2 < this._bindings.length; _i2++) {
            var _binding2 = this._bindings[_i2];
            if (_binding2.descriptorType & DESCRIPTOR_DYNAMIC_TYPE) {
              for (var j = 0; j < _binding2.count; j++) {
                dynamicBindings.push(_binding2.binding);
              }
            }
          }
          this._gpuDescriptorSetLayout = {
            bindings: this._bindings,
            dynamicBindings: dynamicBindings,
            descriptorIndices: descriptorIndices,
            descriptorCount: descriptorCount
          };
        };
        _proto.destroy = function destroy() {
          this._bindings.length = 0;
        };
        _createClass(WebGLDescriptorSetLayout, [{
          key: "gpuDescriptorSetLayout",
          get: function get() {
            return this._gpuDescriptorSetLayout;
          }
        }]);
        return WebGLDescriptorSetLayout;
      }(DescriptorSetLayout);

      var WebGLPipelineLayout = function (_PipelineLayout) {
        _inheritsLoose(WebGLPipelineLayout, _PipelineLayout);
        function WebGLPipelineLayout() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _PipelineLayout.call.apply(_PipelineLayout, [this].concat(args)) || this;
          _this._gpuPipelineLayout = null;
          return _this;
        }
        var _proto = WebGLPipelineLayout.prototype;
        _proto.initialize = function initialize(info) {
          Array.prototype.push.apply(this._setLayouts, info.setLayouts);
          var dynamicOffsetIndices = [];
          var gpuSetLayouts = [];
          var dynamicOffsetCount = 0;
          var dynamicOffsetOffsets = [];
          for (var i = 0; i < this._setLayouts.length; i++) {
            var setLayout = this._setLayouts[i];
            var dynamicBindings = setLayout.gpuDescriptorSetLayout.dynamicBindings;
            var indices = Array(setLayout.bindingIndices.length).fill(-1);
            for (var j = 0; j < dynamicBindings.length; j++) {
              var binding = dynamicBindings[j];
              if (indices[binding] < 0) indices[binding] = dynamicOffsetCount + j;
            }
            gpuSetLayouts.push(setLayout.gpuDescriptorSetLayout);
            dynamicOffsetIndices.push(indices);
            dynamicOffsetOffsets.push(dynamicOffsetCount);
            dynamicOffsetCount += dynamicBindings.length;
          }
          this._gpuPipelineLayout = {
            gpuSetLayouts: gpuSetLayouts,
            dynamicOffsetIndices: dynamicOffsetIndices,
            dynamicOffsetCount: dynamicOffsetCount,
            dynamicOffsetOffsets: dynamicOffsetOffsets
          };
        };
        _proto.destroy = function destroy() {
          this._setLayouts.length = 0;
        };
        _createClass(WebGLPipelineLayout, [{
          key: "gpuPipelineLayout",
          get: function get() {
            return this._gpuPipelineLayout;
          }
        }]);
        return WebGLPipelineLayout;
      }(PipelineLayout);

      var WebGLPrimitives$1 = [0x0000, 0x0001, 0x0003, 0x0002, 0x0000, 0x0000, 0x0000, 0x0004, 0x0005, 0x0006, 0x0000, 0x0000, 0x0000, 0x0000];
      var WebGLPipelineState = function (_PipelineState) {
        _inheritsLoose(WebGLPipelineState, _PipelineState);
        function WebGLPipelineState() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _PipelineState.call.apply(_PipelineState, [this].concat(args)) || this;
          _this._gpuPipelineState = null;
          return _this;
        }
        var _proto = WebGLPipelineState.prototype;
        _proto.initialize = function initialize(info) {
          this._primitive = info.primitive;
          this._shader = info.shader;
          this._pipelineLayout = info.pipelineLayout;
          var bs = this._bs;
          if (info.blendState) {
            var bsInfo = info.blendState;
            var targets = bsInfo.targets;
            if (targets) {
              targets.forEach(function (t, i) {
                bs.setTarget(i, t);
              });
            }
            if (bsInfo.isA2C !== undefined) {
              bs.isA2C = bsInfo.isA2C;
            }
            if (bsInfo.isIndepend !== undefined) {
              bs.isIndepend = bsInfo.isIndepend;
            }
            if (bsInfo.blendColor !== undefined) {
              bs.blendColor = bsInfo.blendColor;
            }
          }
          Object.assign(this._rs, info.rasterizerState);
          Object.assign(this._dss, info.depthStencilState);
          this._is = info.inputState;
          this._renderPass = info.renderPass;
          this._dynamicStates = info.dynamicStates;
          var dynamicStates = [];
          for (var i = 0; i < 31; i++) {
            if (this._dynamicStates & 1 << i) {
              dynamicStates.push(1 << i);
            }
          }
          this._gpuPipelineState = {
            glPrimitive: WebGLPrimitives$1[info.primitive],
            gpuShader: info.shader.gpuShader,
            gpuPipelineLayout: info.pipelineLayout.gpuPipelineLayout,
            rs: info.rasterizerState,
            dss: info.depthStencilState,
            bs: info.blendState,
            gpuRenderPass: info.renderPass.gpuRenderPass,
            dynamicStates: dynamicStates
          };
        };
        _proto.destroy = function destroy() {
          this._gpuPipelineState = null;
        };
        _createClass(WebGLPipelineState, [{
          key: "gpuPipelineState",
          get: function get() {
            return this._gpuPipelineState;
          }
        }]);
        return WebGLPipelineState;
      }(PipelineState);

      var WebGLPrimaryCommandBuffer = function (_WebGLCommandBuffer) {
        _inheritsLoose(WebGLPrimaryCommandBuffer, _WebGLCommandBuffer);
        function WebGLPrimaryCommandBuffer() {
          return _WebGLCommandBuffer.apply(this, arguments) || this;
        }
        var _proto = WebGLPrimaryCommandBuffer.prototype;
        _proto.beginRenderPass = function beginRenderPass(renderPass, framebuffer, renderArea, clearColors, clearDepth, clearStencil) {
          WebGLCmdFuncBeginRenderPass(WebGLDeviceManager.instance, renderPass.gpuRenderPass, framebuffer.gpuFramebuffer, renderArea, clearColors, clearDepth, clearStencil);
          this._isInRenderPass = true;
        };
        _proto.draw = function draw(infoOrAssembler) {
          if (this._isInRenderPass) {
            if (this._isStateInvalied) {
              this.bindStates();
            }
            var info = 'drawInfo' in infoOrAssembler ? infoOrAssembler.drawInfo : infoOrAssembler;
            WebGLCmdFuncDraw(WebGLDeviceManager.instance, info);
            ++this._numDrawCalls;
            this._numInstances += info.instanceCount;
            var indexCount = info.indexCount || info.vertexCount;
            if (this._curGPUPipelineState) {
              var glPrimitive = this._curGPUPipelineState.glPrimitive;
              switch (glPrimitive) {
                case 0x0004:
                  {
                    this._numTris += indexCount / 3 * Math.max(info.instanceCount, 1);
                    break;
                  }
                case 0x0005:
                case 0x0006:
                  {
                    this._numTris += (indexCount - 2) * Math.max(info.instanceCount, 1);
                    break;
                  }
              }
            }
          } else {
            console.error('Command \'draw\' must be recorded inside a render pass.');
          }
        };
        _proto.setViewport = function setViewport(viewport) {
          var _WebGLDeviceManager$i = WebGLDeviceManager.instance,
            cache = _WebGLDeviceManager$i.stateCache,
            gl = _WebGLDeviceManager$i.gl;
          if (cache.viewport.left !== viewport.left || cache.viewport.top !== viewport.top || cache.viewport.width !== viewport.width || cache.viewport.height !== viewport.height) {
            gl.viewport(viewport.left, viewport.top, viewport.width, viewport.height);
            cache.viewport.left = viewport.left;
            cache.viewport.top = viewport.top;
            cache.viewport.width = viewport.width;
            cache.viewport.height = viewport.height;
          }
        };
        _proto.setScissor = function setScissor(scissor) {
          var _WebGLDeviceManager$i2 = WebGLDeviceManager.instance,
            cache = _WebGLDeviceManager$i2.stateCache,
            gl = _WebGLDeviceManager$i2.gl;
          if (cache.scissorRect.x !== scissor.x || cache.scissorRect.y !== scissor.y || cache.scissorRect.width !== scissor.width || cache.scissorRect.height !== scissor.height) {
            gl.scissor(scissor.x, scissor.y, scissor.width, scissor.height);
            cache.scissorRect.x = scissor.x;
            cache.scissorRect.y = scissor.y;
            cache.scissorRect.width = scissor.width;
            cache.scissorRect.height = scissor.height;
          }
        };
        _proto.updateBuffer = function updateBuffer(buffer, data, size) {
          if (!this._isInRenderPass) {
            var gpuBuffer = buffer.gpuBuffer;
            if (gpuBuffer) {
              var buffSize;
              if (size !== undefined) {
                buffSize = size;
              } else if (buffer.usage & BufferUsageBit.INDIRECT) {
                buffSize = 0;
              } else {
                buffSize = data.byteLength;
              }
              WebGLCmdFuncUpdateBuffer(WebGLDeviceManager.instance, gpuBuffer, data, 0, buffSize);
            }
          } else {
            console.error('Command \'updateBuffer\' must be recorded outside a render pass.');
          }
        };
        _proto.copyBuffersToTexture = function copyBuffersToTexture(buffers, texture, regions) {
          if (!this._isInRenderPass) {
            var gpuTexture = texture.gpuTexture;
            if (gpuTexture) {
              WebGLCmdFuncCopyBuffersToTexture(WebGLDeviceManager.instance, buffers, gpuTexture, regions);
            }
          } else {
            console.error('Command \'copyBufferToTexture\' must be recorded outside a render pass.');
          }
        };
        _proto.execute = function execute(cmdBuffs, count) {
          for (var i = 0; i < count; ++i) {
            var webGLCmdBuff = cmdBuffs[i];
            WebGLCmdFuncExecuteCmds(WebGLDeviceManager.instance, webGLCmdBuff.cmdPackage);
            this._numDrawCalls += webGLCmdBuff._numDrawCalls;
            this._numInstances += webGLCmdBuff._numInstances;
            this._numTris += webGLCmdBuff._numTris;
          }
        };
        _proto.bindStates = function bindStates() {
          WebGLCmdFuncBindStates(WebGLDeviceManager.instance, this._curGPUPipelineState, this._curGPUInputAssembler, this._curGPUDescriptorSets, this._curDynamicOffsets, this._curDynamicStates);
          this._isStateInvalied = false;
        };
        _proto.blitTexture = function blitTexture(srcTexture, dstTexture, regions, filter) {
          var gpuTextureSrc = srcTexture.gpuTexture;
          var gpuTextureDst = dstTexture.gpuTexture;
          WebGLCmdFuncBlitTexture(WebGLDeviceManager.instance, gpuTextureSrc, gpuTextureDst, regions, filter);
        };
        return WebGLPrimaryCommandBuffer;
      }(WebGLCommandBuffer);

      var WebGLQueue = function (_Queue) {
        _inheritsLoose(WebGLQueue, _Queue);
        function WebGLQueue() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Queue.call.apply(_Queue, [this].concat(args)) || this;
          _this.numDrawCalls = 0;
          _this.numInstances = 0;
          _this.numTris = 0;
          return _this;
        }
        var _proto = WebGLQueue.prototype;
        _proto.initialize = function initialize(info) {
          this._type = info.type;
        };
        _proto.destroy = function destroy() {};
        _proto.submit = function submit(cmdBuffs) {
          var len = cmdBuffs.length;
          for (var i = 0; i < len; i++) {
            var cmdBuff = cmdBuffs[i];
            this.numDrawCalls += cmdBuff.numDrawCalls;
            this.numInstances += cmdBuff.numInstances;
            this.numTris += cmdBuff.numTris;
          }
        };
        _proto.clear = function clear() {
          this.numDrawCalls = 0;
          this.numInstances = 0;
          this.numTris = 0;
        };
        return WebGLQueue;
      }(Queue);

      var WebGLRenderPass = function (_RenderPass) {
        _inheritsLoose(WebGLRenderPass, _RenderPass);
        function WebGLRenderPass() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _RenderPass.call.apply(_RenderPass, [this].concat(args)) || this;
          _this._gpuRenderPass = null;
          return _this;
        }
        var _proto = WebGLRenderPass.prototype;
        _proto.initialize = function initialize(info) {
          this._colorInfos = info.colorAttachments;
          this._depthStencilInfo = info.depthStencilAttachment;
          this._subpasses = info.subpasses;
          this._gpuRenderPass = {
            colorAttachments: this._colorInfos,
            depthStencilAttachment: this._depthStencilInfo
          };
          this._hash = this.computeHash();
        };
        _proto.destroy = function destroy() {
          this._gpuRenderPass = null;
        };
        _createClass(WebGLRenderPass, [{
          key: "gpuRenderPass",
          get: function get() {
            return this._gpuRenderPass;
          }
        }]);
        return WebGLRenderPass;
      }(RenderPass);

      var WebGLWraps$1 = [0x2901, 0x8370, 0x812F, 0x812F];
      var WebGLSampler = function (_Sampler) {
        _inheritsLoose(WebGLSampler, _Sampler);
        function WebGLSampler(info, hash) {
          var _this;
          _this = _Sampler.call(this, info, hash) || this;
          _this._gpuSampler = null;
          var glMinFilter = 0;
          var glMagFilter = 0;
          var minFilter = _this._info.minFilter;
          var magFilter = _this._info.magFilter;
          var mipFilter = _this._info.mipFilter;
          if (minFilter === Filter$1.LINEAR || minFilter === Filter$1.ANISOTROPIC) {
            if (mipFilter === Filter$1.LINEAR || mipFilter === Filter$1.ANISOTROPIC) {
              glMinFilter = 0x2703;
            } else if (mipFilter === Filter$1.POINT) {
              glMinFilter = 0x2701;
            } else {
              glMinFilter = 0x2601;
            }
          } else if (mipFilter === Filter$1.LINEAR || mipFilter === Filter$1.ANISOTROPIC) {
            glMinFilter = 0x2702;
          } else if (mipFilter === Filter$1.POINT) {
            glMinFilter = 0x2700;
          } else {
            glMinFilter = 0x2600;
          }
          if (magFilter === Filter$1.LINEAR || magFilter === Filter$1.ANISOTROPIC) {
            glMagFilter = 0x2601;
          } else {
            glMagFilter = 0x2600;
          }
          var glWrapS = WebGLWraps$1[_this._info.addressU];
          var glWrapT = WebGLWraps$1[_this._info.addressV];
          var glWrapR = WebGLWraps$1[_this._info.addressW];
          _this._gpuSampler = {
            glMinFilter: glMinFilter,
            glMagFilter: glMagFilter,
            glWrapS: glWrapS,
            glWrapT: glWrapT,
            glWrapR: glWrapR
          };
          return _this;
        }
        _createClass(WebGLSampler, [{
          key: "gpuSampler",
          get: function get() {
            return this._gpuSampler;
          }
        }]);
        return WebGLSampler;
      }(Sampler);

      var WebGLShader = function (_Shader) {
        _inheritsLoose(WebGLShader, _Shader);
        function WebGLShader() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Shader.call.apply(_Shader, [this].concat(args)) || this;
          _this._gpuShader = null;
          return _this;
        }
        var _proto = WebGLShader.prototype;
        _proto.initialize = function initialize(info) {
          this._name = info.name;
          this._stages = info.stages;
          this._attributes = info.attributes;
          this._blocks = info.blocks;
          this._samplers = info.samplers;
          this._gpuShader = {
            name: info.name,
            blocks: info.blocks.slice(),
            samplerTextures: info.samplerTextures.slice(),
            subpassInputs: info.subpassInputs.slice(),
            gpuStages: new Array(info.stages.length),
            glProgram: null,
            glInputs: [],
            glUniforms: [],
            glBlocks: [],
            glSamplerTextures: []
          };
          for (var i = 0; i < info.stages.length; ++i) {
            var stage = info.stages[i];
            this._gpuShader.gpuStages[i] = {
              type: stage.stage,
              source: stage.source,
              glShader: null
            };
          }
        };
        _proto.destroy = function destroy() {
          if (this._gpuShader) {
            WebGLCmdFuncDestroyShader(WebGLDeviceManager.instance, this._gpuShader);
            this._gpuShader = null;
          }
        };
        _createClass(WebGLShader, [{
          key: "gpuShader",
          get: function get() {
            if (this._gpuShader.glProgram === null) {
              WebGLCmdFuncCreateShader(WebGLDeviceManager.instance, this._gpuShader);
            }
            return this._gpuShader;
          }
        }]);
        return WebGLShader;
      }(Shader);

      var WebGLStateCache = function () {
        function WebGLStateCache() {
          this.glArrayBuffer = null;
          this.glElementArrayBuffer = null;
          this.glVAO = null;
          this.texUnit = 0;
          this.glTexUnits = [];
          this.glRenderbuffer = null;
          this.glFramebuffer = null;
          this.viewport = new Viewport();
          this.scissorRect = new Rect(0, 0, 0, 0);
          this.rs = new RasterizerState();
          this.dss = new DepthStencilState();
          this.bs = new BlendState();
          this.glProgram = null;
          this.glEnabledAttribLocs = [];
          this.glCurrentAttribLocs = [];
          this.texUnitCacheMap = {};
        }
        var _proto = WebGLStateCache.prototype;
        _proto.initialize = function initialize(texUnit, vertexAttributes) {
          for (var i = 0; i < texUnit; ++i) this.glTexUnits.push({
            glTexture: null
          });
          this.glEnabledAttribLocs.length = vertexAttributes;
          this.glEnabledAttribLocs.fill(false);
          this.glCurrentAttribLocs.length = vertexAttributes;
          this.glCurrentAttribLocs.fill(false);
        };
        return WebGLStateCache;
      }();

      var WebGLTexture = function (_Texture) {
        _inheritsLoose(WebGLTexture, _Texture);
        function WebGLTexture() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Texture.call.apply(_Texture, [this].concat(args)) || this;
          _this._gpuTexture = null;
          _this._lodLevel = 0;
          return _this;
        }
        var _proto = WebGLTexture.prototype;
        _proto.initialize = function initialize(info, isSwapchainTexture) {
          var texInfo = info;
          var viewInfo = info;
          if ('texture' in info) {
            texInfo = viewInfo.texture.info;
            this._isTextureView = true;
          }
          this._info.copy(texInfo);
          this._isPowerOf2 = IsPowerOf2(this._info.width) && IsPowerOf2(this._info.height);
          this._size = FormatSurfaceSize(this._info.format, this.width, this.height, this.depth, this._info.levelCount) * this._info.layerCount;
          if (!this._isTextureView) {
            this._gpuTexture = {
              type: texInfo.type,
              format: texInfo.format,
              usage: texInfo.usage,
              width: texInfo.width,
              height: texInfo.height,
              depth: texInfo.depth,
              size: this._size,
              arrayLayer: texInfo.layerCount,
              mipLevel: texInfo.levelCount,
              samples: texInfo.samples,
              flags: texInfo.flags,
              isPowerOf2: this._isPowerOf2,
              glTarget: 0,
              glInternalFmt: 0,
              glFormat: 0,
              glType: 0,
              glUsage: 0,
              glTexture: null,
              glRenderbuffer: null,
              glWrapS: 0,
              glWrapT: 0,
              glMinFilter: 0,
              glMagFilter: 0,
              isSwapchainTexture: isSwapchainTexture || false
            };
            if (!this._gpuTexture.isSwapchainTexture) {
              WebGLCmdFuncCreateTexture(WebGLDeviceManager.instance, this._gpuTexture);
              WebGLDeviceManager.instance.memoryStatus.textureSize += this._size;
            }
            this._viewInfo.texture = this;
            this._viewInfo.type = info.type;
            this._viewInfo.format = info.format;
            this._viewInfo.baseLevel = 0;
            this._viewInfo.levelCount = info.levelCount;
            this._viewInfo.baseLayer = 0;
            this._viewInfo.layerCount = info.layerCount;
          } else {
            this._viewInfo.copy(viewInfo);
            this._lodLevel = viewInfo.baseLevel;
            this._gpuTexture = viewInfo.texture._gpuTexture;
          }
        };
        _proto.destroy = function destroy() {
          if (!this._isTextureView && this._gpuTexture) {
            WebGLCmdFuncDestroyTexture(WebGLDeviceManager.instance, this._gpuTexture);
            WebGLDeviceManager.instance.memoryStatus.textureSize -= this._size;
            this._gpuTexture = null;
          }
        };
        _proto.getGLTextureHandle = function getGLTextureHandle() {
          var gpuTexture = this._gpuTexture;
          if (!gpuTexture) {
            return 0;
          }
          if (gpuTexture.glTexture) {
            return gpuTexture.glTexture;
          } else if (gpuTexture.glRenderbuffer) {
            return gpuTexture.glRenderbuffer;
          }
          return 0;
        };
        _proto.resize = function resize(width, height) {
          if (this._info.width === width && this._info.height === height) {
            return;
          }
          if (this._info.levelCount === WebGLTexture.getLevelCount(this._info.width, this._info.height)) {
            this._info.levelCount = WebGLTexture.getLevelCount(width, height);
          } else if (this._info.levelCount > 1) {
            this._info.levelCount = Math.min(this._info.levelCount, WebGLTexture.getLevelCount(width, height));
          }
          var oldSize = this._size;
          this._info.width = width;
          this._info.height = height;
          this._size = FormatSurfaceSize(this._info.format, this.width, this.height, this.depth, this._info.levelCount) * this._info.layerCount;
          if (!this._isTextureView && this._gpuTexture) {
            this._gpuTexture.width = width;
            this._gpuTexture.height = height;
            this._gpuTexture.size = this._size;
            if (!this._gpuTexture.isSwapchainTexture) {
              WebGLCmdFuncResizeTexture(WebGLDeviceManager.instance, this._gpuTexture);
              WebGLDeviceManager.instance.memoryStatus.textureSize -= oldSize;
              WebGLDeviceManager.instance.memoryStatus.textureSize += this._size;
            }
          }
        };
        _proto.initAsSwapchainTexture = function initAsSwapchainTexture(info) {
          var texInfo = new TextureInfo();
          texInfo.format = info.format;
          texInfo.usage = FormatInfos[info.format].hasDepth ? TextureUsageBit.DEPTH_STENCIL_ATTACHMENT : TextureUsageBit.COLOR_ATTACHMENT;
          texInfo.width = info.width;
          texInfo.height = info.height;
          this.initialize(texInfo, true);
        };
        _createClass(WebGLTexture, [{
          key: "gpuTexture",
          get: function get() {
            return this._gpuTexture;
          }
        }, {
          key: "lodLevel",
          get: function get() {
            return this._lodLevel;
          }
        }]);
        return WebGLTexture;
      }(Texture);

      var eventWebGLContextLost$1 = 'webglcontextlost';
      function initStates$1(gl) {
        gl.activeTexture(gl.TEXTURE0);
        gl.pixelStorei(gl.PACK_ALIGNMENT, 1);
        gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
        gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false);
        gl.bindFramebuffer(gl.FRAMEBUFFER, null);
        gl.enable(gl.SCISSOR_TEST);
        gl.enable(gl.CULL_FACE);
        gl.cullFace(gl.BACK);
        gl.frontFace(gl.CCW);
        gl.disable(gl.POLYGON_OFFSET_FILL);
        gl.polygonOffset(0.0, 0.0);
        gl.enable(gl.DEPTH_TEST);
        gl.depthMask(true);
        gl.depthFunc(gl.LESS);
        gl.depthRange(0.0, 1.0);
        gl.stencilFuncSeparate(gl.FRONT, gl.ALWAYS, 1, 0xffff);
        gl.stencilOpSeparate(gl.FRONT, gl.KEEP, gl.KEEP, gl.KEEP);
        gl.stencilMaskSeparate(gl.FRONT, 0xffff);
        gl.stencilFuncSeparate(gl.BACK, gl.ALWAYS, 1, 0xffff);
        gl.stencilOpSeparate(gl.BACK, gl.KEEP, gl.KEEP, gl.KEEP);
        gl.stencilMaskSeparate(gl.BACK, 0xffff);
        gl.disable(gl.STENCIL_TEST);
        gl.disable(gl.SAMPLE_ALPHA_TO_COVERAGE);
        gl.disable(gl.BLEND);
        gl.blendEquationSeparate(gl.FUNC_ADD, gl.FUNC_ADD);
        gl.blendFuncSeparate(gl.ONE, gl.ZERO, gl.ONE, gl.ZERO);
        gl.colorMask(true, true, true, true);
        gl.blendColor(0.0, 0.0, 0.0, 0.0);
      }
      function getExtension$1(gl, ext) {
        var prefixes = ['', 'WEBKIT_', 'MOZ_'];
        for (var i = 0; i < prefixes.length; ++i) {
          var _ext = gl.getExtension(prefixes[i] + ext);
          if (_ext) {
            return _ext;
          }
        }
        return null;
      }
      function getExtensions$1(gl) {
        var res = {
          EXT_texture_filter_anisotropic: getExtension$1(gl, 'EXT_texture_filter_anisotropic'),
          EXT_blend_minmax: getExtension$1(gl, 'EXT_blend_minmax'),
          EXT_frag_depth: getExtension$1(gl, 'EXT_frag_depth'),
          EXT_shader_texture_lod: getExtension$1(gl, 'EXT_shader_texture_lod'),
          EXT_sRGB: getExtension$1(gl, 'EXT_sRGB'),
          OES_vertex_array_object: getExtension$1(gl, 'OES_vertex_array_object'),
          EXT_color_buffer_half_float: getExtension$1(gl, 'EXT_color_buffer_half_float'),
          WEBGL_color_buffer_float: getExtension$1(gl, 'WEBGL_color_buffer_float'),
          WEBGL_compressed_texture_etc1: getExtension$1(gl, 'WEBGL_compressed_texture_etc1'),
          WEBGL_compressed_texture_etc: getExtension$1(gl, 'WEBGL_compressed_texture_etc'),
          WEBGL_compressed_texture_pvrtc: getExtension$1(gl, 'WEBGL_compressed_texture_pvrtc'),
          WEBGL_compressed_texture_s3tc: getExtension$1(gl, 'WEBGL_compressed_texture_s3tc'),
          WEBGL_compressed_texture_s3tc_srgb: getExtension$1(gl, 'WEBGL_compressed_texture_s3tc_srgb'),
          WEBGL_debug_shaders: getExtension$1(gl, 'WEBGL_debug_shaders'),
          WEBGL_draw_buffers: getExtension$1(gl, 'WEBGL_draw_buffers'),
          WEBGL_lose_context: getExtension$1(gl, 'WEBGL_lose_context'),
          WEBGL_depth_texture: getExtension$1(gl, 'WEBGL_depth_texture'),
          OES_texture_half_float: getExtension$1(gl, 'OES_texture_half_float'),
          OES_texture_half_float_linear: getExtension$1(gl, 'OES_texture_half_float_linear'),
          OES_texture_float: getExtension$1(gl, 'OES_texture_float'),
          OES_texture_float_linear: getExtension$1(gl, 'OES_texture_float_linear'),
          OES_standard_derivatives: getExtension$1(gl, 'OES_standard_derivatives'),
          OES_element_index_uint: getExtension$1(gl, 'OES_element_index_uint'),
          ANGLE_instanced_arrays: getExtension$1(gl, 'ANGLE_instanced_arrays'),
          WEBGL_debug_renderer_info: getExtension$1(gl, 'WEBGL_debug_renderer_info'),
          WEBGL_multi_draw: null,
          WEBGL_compressed_texture_astc: null,
          destroyShadersImmediately: true,
          noCompressedTexSubImage2D: false,
          isLocationActive: function isLocationActive(glLoc) {
            return !!glLoc;
          },
          useVAO: false
        };
        {
          if (systemInfo.os !== OS.IOS || systemInfo.osMainVersion !== 14 || !systemInfo.isBrowser) {
            res.WEBGL_compressed_texture_astc = getExtension$1(gl, 'WEBGL_compressed_texture_astc');
          }
          if (systemInfo.os !== OS.ANDROID && systemInfo.os !== OS.IOS) {
            res.WEBGL_multi_draw = getExtension$1(gl, 'WEBGL_multi_draw');
          }
          if (systemInfo.browserType === BrowserType.UC) {
            res.ANGLE_instanced_arrays = null;
          }
          if (systemInfo.os === OS.IOS && systemInfo.osMainVersion <= 10 || (WECHAT_MINI_PROGRAM) ) {
            res.destroyShadersImmediately = false;
          }
        }
        if (res.OES_vertex_array_object) {
          res.useVAO = true;
        }
        return res;
      }
      function getContext$1(canvas) {
        var context = null;
        try {
          var webGLCtxAttribs = {
            alpha: macro.ENABLE_TRANSPARENT_CANVAS,
            antialias: EDITOR || macro.ENABLE_WEBGL_ANTIALIAS,
            depth: true,
            stencil: true,
            premultipliedAlpha: false,
            preserveDrawingBuffer: false,
            powerPreference: 'default',
            failIfMajorPerformanceCaveat: false
          };
          context = canvas.getContext('webgl', webGLCtxAttribs);
        } catch (err) {
          return null;
        }
        return context;
      }
      var WebGLSwapchain = function (_Swapchain) {
        _inheritsLoose(WebGLSwapchain, _Swapchain);
        function WebGLSwapchain() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Swapchain.call.apply(_Swapchain, [this].concat(args)) || this;
          _this.stateCache = new WebGLStateCache();
          _this.cmdAllocator = new WebGLCommandAllocator();
          _this.nullTex2D = null;
          _this.nullTexCube = null;
          _this._canvas = null;
          _this._webGLContextLostHandler = null;
          _this._extensions = null;
          _this._blitManager = null;
          return _this;
        }
        var _proto = WebGLSwapchain.prototype;
        _proto.initialize = function initialize(info) {
          this._canvas = info.windowHandle;
          this._webGLContextLostHandler = this._onWebGLContextLost.bind(this);
          this._canvas.addEventListener(eventWebGLContextLost$1, this._onWebGLContextLost);
          var gl = WebGLDeviceManager.instance.gl;
          this.stateCache.initialize(WebGLDeviceManager.instance.capabilities.maxTextureUnits, WebGLDeviceManager.instance.capabilities.maxVertexAttributes);
          this._extensions = getExtensions$1(gl);
          initStates$1(gl);
          var colorFmt = Format.RGBA8;
          var depthStencilFmt = Format.DEPTH_STENCIL;
          var depthBits = gl.getParameter(gl.DEPTH_BITS);
          var stencilBits = gl.getParameter(gl.STENCIL_BITS);
          if (depthBits && stencilBits) depthStencilFmt = Format.DEPTH_STENCIL;else if (depthBits) depthStencilFmt = Format.DEPTH;
          this._colorTexture = new WebGLTexture();
          this._colorTexture.initAsSwapchainTexture({
            swapchain: this,
            format: colorFmt,
            width: info.width,
            height: info.height
          });
          this._depthStencilTexture = new WebGLTexture();
          this._depthStencilTexture.initAsSwapchainTexture({
            swapchain: this,
            format: depthStencilFmt,
            width: info.width,
            height: info.height
          });
          this.nullTex2D = WebGLDeviceManager.instance.createTexture(new TextureInfo(TextureType.TEX2D, TextureUsageBit.SAMPLED, Format.RGBA8, 2, 2, TextureFlagBit.GEN_MIPMAP));
          this.nullTexCube = WebGLDeviceManager.instance.createTexture(new TextureInfo(TextureType.CUBE, TextureUsageBit.SAMPLED, Format.RGBA8, 2, 2, TextureFlagBit.GEN_MIPMAP, 6));
          var nullTexRegion = new BufferTextureCopy();
          nullTexRegion.texExtent.width = 2;
          nullTexRegion.texExtent.height = 2;
          var nullTexBuff = new Uint8Array(this.nullTex2D.size);
          nullTexBuff.fill(0);
          WebGLDeviceManager.instance.copyBuffersToTexture([nullTexBuff], this.nullTex2D, [nullTexRegion]);
          nullTexRegion.texSubres.layerCount = 6;
          WebGLDeviceManager.instance.copyBuffersToTexture([nullTexBuff, nullTexBuff, nullTexBuff, nullTexBuff, nullTexBuff, nullTexBuff], this.nullTexCube, [nullTexRegion]);
          this._blitManager = new IWebGLBlitManager();
        };
        _proto.destroy = function destroy() {
          if (this._canvas && this._webGLContextLostHandler) {
            this._canvas.removeEventListener(eventWebGLContextLost$1, this._webGLContextLostHandler);
            this._webGLContextLostHandler = null;
          }
          if (this.nullTex2D) {
            this.nullTex2D.destroy();
            this.nullTex2D = null;
          }
          if (this.nullTexCube) {
            this.nullTexCube.destroy();
            this.nullTexCube = null;
          }
          if (this._blitManager) {
            this._blitManager.destroy();
            this._blitManager = null;
          }
          this._extensions = null;
          this._canvas = null;
        };
        _proto.resize = function resize(width, height, surfaceTransform) {
          if (this._colorTexture.width !== width || this._colorTexture.height !== height) {
            debug("Resizing swapchain: " + width + "x" + height);
            this._canvas.width = width;
            this._canvas.height = height;
            this._colorTexture.resize(width, height);
            this._depthStencilTexture.resize(width, height);
          }
        };
        _proto._onWebGLContextLost = function _onWebGLContextLost(event) {
          warnID(11000);
          warn(event);
        };
        _createClass(WebGLSwapchain, [{
          key: "extensions",
          get: function get() {
            return this._extensions;
          }
        }, {
          key: "blitManager",
          get: function get() {
            return this._blitManager;
          }
        }]);
        return WebGLSwapchain;
      }(Swapchain);

      var WebGLDevice = exports('eF', function (_Device) {
        _inheritsLoose(WebGLDevice, _Device);
        function WebGLDevice() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Device.call.apply(_Device, [this].concat(args)) || this;
          _this._swapchain = null;
          _this._context = null;
          _this._bindingMappings = null;
          _this._textureExclusive = new Array(Format.COUNT);
          return _this;
        }
        var _proto = WebGLDevice.prototype;
        _proto.initialize = function initialize(info) {
          WebGLDeviceManager.setInstance(this);
          this._gfxAPI = API.WEBGL;
          var mapping = this._bindingMappingInfo = info.bindingMappingInfo;
          var blockOffsets = [];
          var samplerTextureOffsets = [];
          var firstSet = mapping.setIndices[0];
          blockOffsets[firstSet] = 0;
          samplerTextureOffsets[firstSet] = 0;
          for (var i = 1; i < mapping.setIndices.length; ++i) {
            var curSet = mapping.setIndices[i];
            var prevSet = mapping.setIndices[i - 1];
            blockOffsets[curSet] = mapping.maxBlockCounts[prevSet] + blockOffsets[prevSet];
            samplerTextureOffsets[curSet] = mapping.maxSamplerTextureCounts[prevSet] + samplerTextureOffsets[prevSet];
          }
          for (var _i = 0; _i < mapping.setIndices.length; ++_i) {
            var _curSet = mapping.setIndices[_i];
            samplerTextureOffsets[_curSet] -= mapping.maxBlockCounts[_curSet];
          }
          this._bindingMappings = {
            blockOffsets: blockOffsets,
            samplerTextureOffsets: samplerTextureOffsets,
            flexibleSet: mapping.setIndices[mapping.setIndices.length - 1]
          };
          var gl = this._context = getContext$1(Device.canvas);
          if (!gl) {
            console.error('This device does not support WebGL.');
            return false;
          }
          this._queue = this.createQueue(new QueueInfo(QueueType.GRAPHICS));
          this._cmdBuff = this.createCommandBuffer(new CommandBufferInfo(this._queue));
          this._caps.maxVertexAttributes = gl.getParameter(gl.MAX_VERTEX_ATTRIBS);
          this._caps.maxVertexUniformVectors = gl.getParameter(gl.MAX_VERTEX_UNIFORM_VECTORS);
          this._caps.maxFragmentUniformVectors = gl.getParameter(gl.MAX_FRAGMENT_UNIFORM_VECTORS);
          this._caps.maxTextureUnits = gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS);
          this._caps.maxVertexTextureUnits = gl.getParameter(gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
          this._caps.maxTextureSize = gl.getParameter(gl.MAX_TEXTURE_SIZE);
          this._caps.maxCubeMapTextureSize = gl.getParameter(gl.MAX_CUBE_MAP_TEXTURE_SIZE);
          this._caps.maxArrayTextureLayers = 0;
          this._caps.max3DTextureSize = 0;
          this._caps.maxUniformBufferBindings = 16;
          var extensions = gl.getSupportedExtensions();
          var extStr = '';
          if (extensions) {
            for (var _iterator = _createForOfIteratorHelperLoose(extensions), _step; !(_step = _iterator()).done;) {
              var ext = _step.value;
              extStr += ext + " ";
            }
          }
          var exts = getExtensions$1(gl);
          if (exts.WEBGL_debug_renderer_info) {
            this._renderer = gl.getParameter(exts.WEBGL_debug_renderer_info.UNMASKED_RENDERER_WEBGL);
            this._vendor = gl.getParameter(exts.WEBGL_debug_renderer_info.UNMASKED_VENDOR_WEBGL);
          } else {
            this._renderer = gl.getParameter(gl.RENDERER);
            this._vendor = gl.getParameter(gl.VENDOR);
          }
          var version = gl.getParameter(gl.VERSION);
          this._features.fill(false);
          this.initFormatFeatures(exts);
          if (exts.EXT_blend_minmax) {
            this._features[Feature.BLEND_MINMAX] = true;
          }
          if (exts.OES_element_index_uint) {
            this._features[Feature.ELEMENT_INDEX_UINT] = true;
          }
          if (exts.ANGLE_instanced_arrays) {
            this._features[Feature.INSTANCED_ARRAYS] = true;
          }
          if (exts.WEBGL_draw_buffers) {
            this._features[Feature.MULTIPLE_RENDER_TARGETS] = true;
          }
          var compressedFormat = '';
          if (this.getFormatFeatures(Format.ETC_RGB8)) {
            compressedFormat += 'etc1 ';
          }
          if (this.getFormatFeatures(Format.ETC2_RGB8)) {
            compressedFormat += 'etc2 ';
          }
          if (this.getFormatFeatures(Format.BC1)) {
            compressedFormat += 'dxt ';
          }
          if (this.getFormatFeatures(Format.PVRTC_RGB2)) {
            compressedFormat += 'pvrtc ';
          }
          if (this.getFormatFeatures(Format.ASTC_RGBA_4X4)) {
            compressedFormat += 'astc ';
          }
          debug('WebGL device initialized.');
          debug("RENDERER: " + this._renderer);
          debug("VENDOR: " + this._vendor);
          debug("VERSION: " + version);
          debug("COMPRESSED_FORMAT: " + compressedFormat);
          debug("EXTENSIONS: " + extStr);
          return true;
        };
        _proto.destroy = function destroy() {
          if (this._queue) {
            this._queue.destroy();
            this._queue = null;
          }
          if (this._cmdBuff) {
            this._cmdBuff.destroy();
            this._cmdBuff = null;
          }
          this._swapchain = null;
        };
        _proto.flushCommands = function flushCommands(cmdBuffs) {};
        _proto.acquire = function acquire(swapchains) {};
        _proto.present = function present() {
          var queue = this._queue;
          this._numDrawCalls = queue.numDrawCalls;
          this._numInstances = queue.numInstances;
          this._numTris = queue.numTris;
          queue.clear();
        };
        _proto.initFormatFeatures = function initFormatFeatures(exts) {
          this._formatFeatures.fill(FormatFeatureBit.NONE);
          this._textureExclusive.fill(true);
          var tempFeature = FormatFeatureBit.RENDER_TARGET | FormatFeatureBit.SAMPLED_TEXTURE | FormatFeatureBit.LINEAR_FILTER;
          this._formatFeatures[Format.RGB8] = tempFeature;
          this._formatFeatures[Format.R5G6B5] = tempFeature;
          this._textureExclusive[Format.R5G6B5] = false;
          this._formatFeatures[Format.RGBA8] = tempFeature;
          this._formatFeatures[Format.RGBA4] = tempFeature;
          this._textureExclusive[Format.RGBA4] = false;
          this._formatFeatures[Format.RGB5A1] = tempFeature;
          this._textureExclusive[Format.RGB5A1] = false;
          this._formatFeatures[Format.DEPTH] = FormatFeatureBit.RENDER_TARGET;
          this._textureExclusive[Format.DEPTH] = false;
          this._formatFeatures[Format.DEPTH_STENCIL] = FormatFeatureBit.RENDER_TARGET;
          this._textureExclusive[Format.DEPTH_STENCIL] = false;
          this._formatFeatures[Format.R8I] |= FormatFeatureBit.VERTEX_ATTRIBUTE;
          this._formatFeatures[Format.RG8I] |= FormatFeatureBit.VERTEX_ATTRIBUTE;
          this._formatFeatures[Format.RGB8I] |= FormatFeatureBit.VERTEX_ATTRIBUTE;
          this._formatFeatures[Format.RGBA8I] |= FormatFeatureBit.VERTEX_ATTRIBUTE;
          this._formatFeatures[Format.R8UI] |= FormatFeatureBit.VERTEX_ATTRIBUTE;
          this._formatFeatures[Format.RG8UI] |= FormatFeatureBit.VERTEX_ATTRIBUTE;
          this._formatFeatures[Format.RGB8UI] |= FormatFeatureBit.VERTEX_ATTRIBUTE;
          this._formatFeatures[Format.RGBA8UI] |= FormatFeatureBit.VERTEX_ATTRIBUTE;
          this._formatFeatures[Format.R8I] |= FormatFeatureBit.VERTEX_ATTRIBUTE;
          this._formatFeatures[Format.RG8I] |= FormatFeatureBit.VERTEX_ATTRIBUTE;
          this._formatFeatures[Format.RGB8I] |= FormatFeatureBit.VERTEX_ATTRIBUTE;
          this._formatFeatures[Format.RGBA8I] |= FormatFeatureBit.VERTEX_ATTRIBUTE;
          this._formatFeatures[Format.R8UI] |= FormatFeatureBit.VERTEX_ATTRIBUTE;
          this._formatFeatures[Format.RG8UI] |= FormatFeatureBit.VERTEX_ATTRIBUTE;
          this._formatFeatures[Format.RGB8UI] |= FormatFeatureBit.VERTEX_ATTRIBUTE;
          this._formatFeatures[Format.RGBA8UI] |= FormatFeatureBit.VERTEX_ATTRIBUTE;
          this._formatFeatures[Format.R32F] |= FormatFeatureBit.VERTEX_ATTRIBUTE;
          this._formatFeatures[Format.RG32F] |= FormatFeatureBit.VERTEX_ATTRIBUTE;
          this._formatFeatures[Format.RGB32F] |= FormatFeatureBit.VERTEX_ATTRIBUTE;
          this._formatFeatures[Format.RGBA32F] |= FormatFeatureBit.VERTEX_ATTRIBUTE;
          if (exts.EXT_sRGB) {
            this._formatFeatures[Format.SRGB8] = tempFeature;
            this._formatFeatures[Format.SRGB8_A8] = tempFeature;
            this._textureExclusive[Format.SRGB8_A8] = false;
          }
          if (exts.WEBGL_depth_texture) {
            this._formatFeatures[Format.DEPTH] |= tempFeature;
            this._formatFeatures[Format.DEPTH_STENCIL] |= tempFeature;
          }
          if (exts.WEBGL_color_buffer_float) {
            this._formatFeatures[Format.RGB32F] |= FormatFeatureBit.RENDER_TARGET;
            this._formatFeatures[Format.RGBA32F] |= FormatFeatureBit.RENDER_TARGET;
            this._textureExclusive[Format.RGB32F] = false;
            this._textureExclusive[Format.RGBA32F] = false;
          }
          if (exts.EXT_color_buffer_half_float) {
            this._formatFeatures[Format.RGB16F] |= FormatFeatureBit.RENDER_TARGET;
            this._formatFeatures[Format.RGBA16F] |= FormatFeatureBit.RENDER_TARGET;
            this._textureExclusive[Format.RGB16F] = false;
            this._textureExclusive[Format.RGBA16F] = false;
          }
          if (exts.OES_texture_float) {
            this._formatFeatures[Format.RGB32F] |= FormatFeatureBit.RENDER_TARGET | FormatFeatureBit.SAMPLED_TEXTURE;
            this._formatFeatures[Format.RGBA32F] |= FormatFeatureBit.RENDER_TARGET | FormatFeatureBit.SAMPLED_TEXTURE;
          }
          if (exts.OES_texture_half_float) {
            this._formatFeatures[Format.RGB16F] |= FormatFeatureBit.RENDER_TARGET | FormatFeatureBit.SAMPLED_TEXTURE;
            this._formatFeatures[Format.RGBA16F] |= FormatFeatureBit.RENDER_TARGET | FormatFeatureBit.SAMPLED_TEXTURE;
          }
          if (exts.OES_texture_float_linear) {
            this._formatFeatures[Format.RGB32F] |= FormatFeatureBit.LINEAR_FILTER;
            this._formatFeatures[Format.RGBA32F] |= FormatFeatureBit.LINEAR_FILTER;
          }
          if (exts.OES_texture_half_float_linear) {
            this._formatFeatures[Format.RGB16F] |= FormatFeatureBit.LINEAR_FILTER;
            this._formatFeatures[Format.RGBA16F] |= FormatFeatureBit.LINEAR_FILTER;
          }
          var compressedFeature = FormatFeatureBit.SAMPLED_TEXTURE | FormatFeatureBit.LINEAR_FILTER;
          if (exts.WEBGL_compressed_texture_etc1) {
            this._formatFeatures[Format.ETC_RGB8] = compressedFeature;
          }
          if (exts.WEBGL_compressed_texture_etc) {
            this._formatFeatures[Format.ETC2_RGB8] = compressedFeature;
            this._formatFeatures[Format.ETC2_RGBA8] = compressedFeature;
            this._formatFeatures[Format.ETC2_SRGB8] = compressedFeature;
            this._formatFeatures[Format.ETC2_SRGB8_A8] = compressedFeature;
            this._formatFeatures[Format.ETC2_RGB8_A1] = compressedFeature;
            this._formatFeatures[Format.ETC2_SRGB8_A1] = compressedFeature;
          }
          if (exts.WEBGL_compressed_texture_s3tc) {
            this._formatFeatures[Format.BC1] = compressedFeature;
            this._formatFeatures[Format.BC1_ALPHA] = compressedFeature;
            this._formatFeatures[Format.BC1_SRGB] = compressedFeature;
            this._formatFeatures[Format.BC1_SRGB_ALPHA] = compressedFeature;
            this._formatFeatures[Format.BC2] = compressedFeature;
            this._formatFeatures[Format.BC2_SRGB] = compressedFeature;
            this._formatFeatures[Format.BC3] = compressedFeature;
            this._formatFeatures[Format.BC3_SRGB] = compressedFeature;
          }
          if (exts.WEBGL_compressed_texture_pvrtc) {
            this._formatFeatures[Format.PVRTC_RGB2] |= compressedFeature;
            this._formatFeatures[Format.PVRTC_RGBA2] |= compressedFeature;
            this._formatFeatures[Format.PVRTC_RGB4] |= compressedFeature;
            this._formatFeatures[Format.PVRTC_RGBA4] |= compressedFeature;
          }
          if (exts.WEBGL_compressed_texture_astc) {
            this._formatFeatures[Format.ASTC_RGBA_4X4] |= compressedFeature;
            this._formatFeatures[Format.ASTC_RGBA_5X4] |= compressedFeature;
            this._formatFeatures[Format.ASTC_RGBA_5X5] |= compressedFeature;
            this._formatFeatures[Format.ASTC_RGBA_6X5] |= compressedFeature;
            this._formatFeatures[Format.ASTC_RGBA_6X6] |= compressedFeature;
            this._formatFeatures[Format.ASTC_RGBA_8X5] |= compressedFeature;
            this._formatFeatures[Format.ASTC_RGBA_8X6] |= compressedFeature;
            this._formatFeatures[Format.ASTC_RGBA_8X8] |= compressedFeature;
            this._formatFeatures[Format.ASTC_RGBA_10X5] |= compressedFeature;
            this._formatFeatures[Format.ASTC_RGBA_10X6] |= compressedFeature;
            this._formatFeatures[Format.ASTC_RGBA_10X8] |= compressedFeature;
            this._formatFeatures[Format.ASTC_RGBA_10X10] |= compressedFeature;
            this._formatFeatures[Format.ASTC_RGBA_12X10] |= compressedFeature;
            this._formatFeatures[Format.ASTC_RGBA_12X12] |= compressedFeature;
            this._formatFeatures[Format.ASTC_SRGBA_4X4] |= compressedFeature;
            this._formatFeatures[Format.ASTC_SRGBA_5X4] |= compressedFeature;
            this._formatFeatures[Format.ASTC_SRGBA_5X5] |= compressedFeature;
            this._formatFeatures[Format.ASTC_SRGBA_6X5] |= compressedFeature;
            this._formatFeatures[Format.ASTC_SRGBA_6X6] |= compressedFeature;
            this._formatFeatures[Format.ASTC_SRGBA_8X5] |= compressedFeature;
            this._formatFeatures[Format.ASTC_SRGBA_8X6] |= compressedFeature;
            this._formatFeatures[Format.ASTC_SRGBA_8X8] |= compressedFeature;
            this._formatFeatures[Format.ASTC_SRGBA_10X5] |= compressedFeature;
            this._formatFeatures[Format.ASTC_SRGBA_10X6] |= compressedFeature;
            this._formatFeatures[Format.ASTC_SRGBA_10X8] |= compressedFeature;
            this._formatFeatures[Format.ASTC_SRGBA_10X10] |= compressedFeature;
            this._formatFeatures[Format.ASTC_SRGBA_12X10] |= compressedFeature;
            this._formatFeatures[Format.ASTC_SRGBA_12X12] |= compressedFeature;
          }
        };
        _proto.createCommandBuffer = function createCommandBuffer(info) {
          var Ctor = info.type === CommandBufferType.PRIMARY ? WebGLPrimaryCommandBuffer : WebGLCommandBuffer;
          var cmdBuff = new Ctor();
          cmdBuff.initialize(info);
          return cmdBuff;
        };
        _proto.createSwapchain = function createSwapchain(info) {
          var swapchain = new WebGLSwapchain();
          this._swapchain = swapchain;
          swapchain.initialize(info);
          return swapchain;
        };
        _proto.createBuffer = function createBuffer(info) {
          var buffer = new WebGLBuffer();
          buffer.initialize(info);
          return buffer;
        };
        _proto.createTexture = function createTexture(info) {
          var texture = new WebGLTexture();
          texture.initialize(info);
          return texture;
        };
        _proto.createDescriptorSet = function createDescriptorSet(info) {
          var descriptorSet = new WebGLDescriptorSet();
          descriptorSet.initialize(info);
          return descriptorSet;
        };
        _proto.createShader = function createShader(info) {
          var shader = new WebGLShader();
          shader.initialize(info);
          return shader;
        };
        _proto.createInputAssembler = function createInputAssembler(info) {
          var inputAssembler = new WebGLInputAssembler();
          inputAssembler.initialize(info);
          return inputAssembler;
        };
        _proto.createRenderPass = function createRenderPass(info) {
          var renderPass = new WebGLRenderPass();
          renderPass.initialize(info);
          return renderPass;
        };
        _proto.createFramebuffer = function createFramebuffer(info) {
          var framebuffer = new WebGLFramebuffer();
          framebuffer.initialize(info);
          return framebuffer;
        };
        _proto.createDescriptorSetLayout = function createDescriptorSetLayout(info) {
          var descriptorSetLayout = new WebGLDescriptorSetLayout();
          descriptorSetLayout.initialize(info);
          return descriptorSetLayout;
        };
        _proto.createPipelineLayout = function createPipelineLayout(info) {
          var pipelineLayout = new WebGLPipelineLayout();
          pipelineLayout.initialize(info);
          return pipelineLayout;
        };
        _proto.createPipelineState = function createPipelineState(info) {
          var pipelineState = new WebGLPipelineState();
          pipelineState.initialize(info);
          return pipelineState;
        };
        _proto.createQueue = function createQueue(info) {
          var queue = new WebGLQueue();
          queue.initialize(info);
          return queue;
        };
        _proto.getSampler = function getSampler(info) {
          var hash = Sampler.computeHash(info);
          if (!this._samplers.has(hash)) {
            this._samplers.set(hash, new WebGLSampler(info, hash));
          }
          return this._samplers.get(hash);
        };
        _proto.getSwapchains = function getSwapchains() {
          return [this._swapchain];
        };
        _proto.getGeneralBarrier = function getGeneralBarrier(info) {
          var hash = GeneralBarrier.computeHash(info);
          if (!this._generalBarrierss.has(hash)) {
            this._generalBarrierss.set(hash, new GeneralBarrier(info, hash));
          }
          return this._generalBarrierss.get(hash);
        };
        _proto.getTextureBarrier = function getTextureBarrier(info) {
          var hash = TextureBarrier.computeHash(info);
          if (!this._textureBarriers.has(hash)) {
            this._textureBarriers.set(hash, new TextureBarrier(info, hash));
          }
          return this._textureBarriers.get(hash);
        };
        _proto.getBufferBarrier = function getBufferBarrier(info) {
          var hash = BufferBarrier.computeHash(info);
          if (!this._bufferBarriers.has(hash)) {
            this._bufferBarriers.set(hash, new BufferBarrier(info, hash));
          }
          return this._bufferBarriers.get(hash);
        };
        _proto.copyBuffersToTexture = function copyBuffersToTexture(buffers, texture, regions) {
          WebGLCmdFuncCopyBuffersToTexture(this, buffers, texture.gpuTexture, regions);
        };
        _proto.copyTextureToBuffers = function copyTextureToBuffers(texture, buffers, regions) {
          WebGLCmdFuncCopyTextureToBuffers(this, texture.gpuTexture, buffers, regions);
        };
        _proto.copyTexImagesToTexture = function copyTexImagesToTexture(texImages, texture, regions) {
          WebGLCmdFuncCopyTexImagesToTexture(this, texImages, texture.gpuTexture, regions);
        };
        _createClass(WebGLDevice, [{
          key: "gl",
          get: function get() {
            return this._context;
          }
        }, {
          key: "extensions",
          get: function get() {
            return this._swapchain.extensions;
          }
        }, {
          key: "stateCache",
          get: function get() {
            return this._swapchain.stateCache;
          }
        }, {
          key: "nullTex2D",
          get: function get() {
            return this._swapchain.nullTex2D;
          }
        }, {
          key: "nullTexCube",
          get: function get() {
            return this._swapchain.nullTexCube;
          }
        }, {
          key: "textureExclusive",
          get: function get() {
            return this._textureExclusive;
          }
        }, {
          key: "bindingMappings",
          get: function get() {
            return this._bindingMappings;
          }
        }, {
          key: "blitManager",
          get: function get() {
            return this._swapchain.blitManager;
          }
        }]);
        return WebGLDevice;
      }(Device));

      legacyCC.WebGLDevice = WebGLDevice;

      var WebGL2DescriptorSet = function (_DescriptorSet) {
        _inheritsLoose(WebGL2DescriptorSet, _DescriptorSet);
        function WebGL2DescriptorSet() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _DescriptorSet.call.apply(_DescriptorSet, [this].concat(args)) || this;
          _this._gpuDescriptorSet = null;
          return _this;
        }
        var _proto = WebGL2DescriptorSet.prototype;
        _proto.initialize = function initialize(info) {
          this._layout = info.layout;
          var _gpuDescriptorSetLayo = info.layout.gpuDescriptorSetLayout,
            bindings = _gpuDescriptorSetLayo.bindings,
            descriptorIndices = _gpuDescriptorSetLayo.descriptorIndices,
            descriptorCount = _gpuDescriptorSetLayo.descriptorCount;
          this._buffers = Array(descriptorCount).fill(null);
          this._textures = Array(descriptorCount).fill(null);
          this._samplers = Array(descriptorCount).fill(null);
          var gpuDescriptors = [];
          this._gpuDescriptorSet = {
            gpuDescriptors: gpuDescriptors,
            descriptorIndices: descriptorIndices
          };
          for (var i = 0; i < bindings.length; ++i) {
            var binding = bindings[i];
            for (var j = 0; j < binding.count; j++) {
              gpuDescriptors.push({
                type: binding.descriptorType,
                gpuBuffer: null,
                gpuTextureView: null,
                gpuSampler: null
              });
            }
          }
        };
        _proto.destroy = function destroy() {
          this._layout = null;
          this._gpuDescriptorSet = null;
        };
        _proto.update = function update() {
          if (this._isDirty && this._gpuDescriptorSet) {
            var descriptors = this._gpuDescriptorSet.gpuDescriptors;
            for (var i = 0; i < descriptors.length; ++i) {
              if (descriptors[i].type & DESCRIPTOR_BUFFER_TYPE) {
                if (this._buffers[i]) {
                  descriptors[i].gpuBuffer = this._buffers[i].gpuBuffer;
                }
              } else if (descriptors[i].type & DESCRIPTOR_SAMPLER_TYPE) {
                if (this._textures[i]) {
                  descriptors[i].gpuTextureView = this._textures[i].gpuTextureView;
                }
                if (this._samplers[i]) {
                  descriptors[i].gpuSampler = this._samplers[i].gpuSampler;
                }
              }
            }
            this._isDirty = false;
          }
        };
        _createClass(WebGL2DescriptorSet, [{
          key: "gpuDescriptorSet",
          get: function get() {
            return this._gpuDescriptorSet;
          }
        }]);
        return WebGL2DescriptorSet;
      }(DescriptorSet);

      var WebGL2EXT;
      (function (WebGL2EXT) {
        WebGL2EXT[WebGL2EXT["COMPRESSED_RGB_S3TC_DXT1_EXT"] = 33776] = "COMPRESSED_RGB_S3TC_DXT1_EXT";
        WebGL2EXT[WebGL2EXT["COMPRESSED_RGBA_S3TC_DXT1_EXT"] = 33777] = "COMPRESSED_RGBA_S3TC_DXT1_EXT";
        WebGL2EXT[WebGL2EXT["COMPRESSED_RGBA_S3TC_DXT3_EXT"] = 33778] = "COMPRESSED_RGBA_S3TC_DXT3_EXT";
        WebGL2EXT[WebGL2EXT["COMPRESSED_RGBA_S3TC_DXT5_EXT"] = 33779] = "COMPRESSED_RGBA_S3TC_DXT5_EXT";
        WebGL2EXT[WebGL2EXT["COMPRESSED_SRGB_S3TC_DXT1_EXT"] = 35916] = "COMPRESSED_SRGB_S3TC_DXT1_EXT";
        WebGL2EXT[WebGL2EXT["COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT"] = 35917] = "COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT";
        WebGL2EXT[WebGL2EXT["COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT"] = 35918] = "COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT";
        WebGL2EXT[WebGL2EXT["COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT"] = 35919] = "COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT";
        WebGL2EXT[WebGL2EXT["COMPRESSED_RGB_PVRTC_4BPPV1_IMG"] = 35840] = "COMPRESSED_RGB_PVRTC_4BPPV1_IMG";
        WebGL2EXT[WebGL2EXT["COMPRESSED_RGB_PVRTC_2BPPV1_IMG"] = 35841] = "COMPRESSED_RGB_PVRTC_2BPPV1_IMG";
        WebGL2EXT[WebGL2EXT["COMPRESSED_RGBA_PVRTC_4BPPV1_IMG"] = 35842] = "COMPRESSED_RGBA_PVRTC_4BPPV1_IMG";
        WebGL2EXT[WebGL2EXT["COMPRESSED_RGBA_PVRTC_2BPPV1_IMG"] = 35843] = "COMPRESSED_RGBA_PVRTC_2BPPV1_IMG";
        WebGL2EXT[WebGL2EXT["COMPRESSED_RGB_ETC1_WEBGL"] = 36196] = "COMPRESSED_RGB_ETC1_WEBGL";
        WebGL2EXT[WebGL2EXT["COMPRESSED_R11_EAC"] = 37488] = "COMPRESSED_R11_EAC";
        WebGL2EXT[WebGL2EXT["COMPRESSED_SIGNED_R11_EAC"] = 37489] = "COMPRESSED_SIGNED_R11_EAC";
        WebGL2EXT[WebGL2EXT["COMPRESSED_RG11_EAC"] = 37490] = "COMPRESSED_RG11_EAC";
        WebGL2EXT[WebGL2EXT["COMPRESSED_SIGNED_RG11_EAC"] = 37491] = "COMPRESSED_SIGNED_RG11_EAC";
        WebGL2EXT[WebGL2EXT["COMPRESSED_RGB8_ETC2"] = 37492] = "COMPRESSED_RGB8_ETC2";
        WebGL2EXT[WebGL2EXT["COMPRESSED_SRGB8_ETC2"] = 37493] = "COMPRESSED_SRGB8_ETC2";
        WebGL2EXT[WebGL2EXT["COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2"] = 37494] = "COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2";
        WebGL2EXT[WebGL2EXT["COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2"] = 37495] = "COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2";
        WebGL2EXT[WebGL2EXT["COMPRESSED_RGBA8_ETC2_EAC"] = 37496] = "COMPRESSED_RGBA8_ETC2_EAC";
        WebGL2EXT[WebGL2EXT["COMPRESSED_SRGB8_ALPHA8_ETC2_EAC"] = 37497] = "COMPRESSED_SRGB8_ALPHA8_ETC2_EAC";
        WebGL2EXT[WebGL2EXT["COMPRESSED_RGBA_ASTC_4x4_KHR"] = 37808] = "COMPRESSED_RGBA_ASTC_4x4_KHR";
        WebGL2EXT[WebGL2EXT["COMPRESSED_RGBA_ASTC_5x4_KHR"] = 37809] = "COMPRESSED_RGBA_ASTC_5x4_KHR";
        WebGL2EXT[WebGL2EXT["COMPRESSED_RGBA_ASTC_5x5_KHR"] = 37810] = "COMPRESSED_RGBA_ASTC_5x5_KHR";
        WebGL2EXT[WebGL2EXT["COMPRESSED_RGBA_ASTC_6x5_KHR"] = 37811] = "COMPRESSED_RGBA_ASTC_6x5_KHR";
        WebGL2EXT[WebGL2EXT["COMPRESSED_RGBA_ASTC_6x6_KHR"] = 37812] = "COMPRESSED_RGBA_ASTC_6x6_KHR";
        WebGL2EXT[WebGL2EXT["COMPRESSED_RGBA_ASTC_8x5_KHR"] = 37813] = "COMPRESSED_RGBA_ASTC_8x5_KHR";
        WebGL2EXT[WebGL2EXT["COMPRESSED_RGBA_ASTC_8x6_KHR"] = 37814] = "COMPRESSED_RGBA_ASTC_8x6_KHR";
        WebGL2EXT[WebGL2EXT["COMPRESSED_RGBA_ASTC_8x8_KHR"] = 37815] = "COMPRESSED_RGBA_ASTC_8x8_KHR";
        WebGL2EXT[WebGL2EXT["COMPRESSED_RGBA_ASTC_10x5_KHR"] = 37816] = "COMPRESSED_RGBA_ASTC_10x5_KHR";
        WebGL2EXT[WebGL2EXT["COMPRESSED_RGBA_ASTC_10x6_KHR"] = 37817] = "COMPRESSED_RGBA_ASTC_10x6_KHR";
        WebGL2EXT[WebGL2EXT["COMPRESSED_RGBA_ASTC_10x8_KHR"] = 37818] = "COMPRESSED_RGBA_ASTC_10x8_KHR";
        WebGL2EXT[WebGL2EXT["COMPRESSED_RGBA_ASTC_10x10_KHR"] = 37819] = "COMPRESSED_RGBA_ASTC_10x10_KHR";
        WebGL2EXT[WebGL2EXT["COMPRESSED_RGBA_ASTC_12x10_KHR"] = 37820] = "COMPRESSED_RGBA_ASTC_12x10_KHR";
        WebGL2EXT[WebGL2EXT["COMPRESSED_RGBA_ASTC_12x12_KHR"] = 37821] = "COMPRESSED_RGBA_ASTC_12x12_KHR";
        WebGL2EXT[WebGL2EXT["COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR"] = 37840] = "COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR";
        WebGL2EXT[WebGL2EXT["COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR"] = 37841] = "COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR";
        WebGL2EXT[WebGL2EXT["COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR"] = 37842] = "COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR";
        WebGL2EXT[WebGL2EXT["COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR"] = 37843] = "COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR";
        WebGL2EXT[WebGL2EXT["COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR"] = 37844] = "COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR";
        WebGL2EXT[WebGL2EXT["COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR"] = 37845] = "COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR";
        WebGL2EXT[WebGL2EXT["COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR"] = 37846] = "COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR";
        WebGL2EXT[WebGL2EXT["COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR"] = 37847] = "COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR";
        WebGL2EXT[WebGL2EXT["COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR"] = 37848] = "COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR";
        WebGL2EXT[WebGL2EXT["COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR"] = 37849] = "COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR";
        WebGL2EXT[WebGL2EXT["COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR"] = 37850] = "COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR";
        WebGL2EXT[WebGL2EXT["COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR"] = 37851] = "COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR";
        WebGL2EXT[WebGL2EXT["COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR"] = 37852] = "COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR";
        WebGL2EXT[WebGL2EXT["COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR"] = 37853] = "COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR";
      })(WebGL2EXT || (WebGL2EXT = {}));
      var WebGL2DeviceManager = function () {
        function WebGL2DeviceManager() {}
        WebGL2DeviceManager.setInstance = function setInstance(instance) {
          WebGL2DeviceManager._instance = instance;
        };
        _createClass(WebGL2DeviceManager, null, [{
          key: "instance",
          get: function get() {
            return WebGL2DeviceManager._instance;
          }
        }]);
        return WebGL2DeviceManager;
      }();
      WebGL2DeviceManager._instance = null;

      var WebGLWraps = [0x2901, 0x8370, 0x812F, 0x812F];
      var _f32v4 = new Float32Array(4);
      function GFXFormatToWebGLType(format, gl) {
        switch (format) {
          case Format.R8:
            return gl.UNSIGNED_BYTE;
          case Format.R8SN:
            return gl.BYTE;
          case Format.R8UI:
            return gl.UNSIGNED_BYTE;
          case Format.R8I:
            return gl.BYTE;
          case Format.R16F:
            return gl.HALF_FLOAT;
          case Format.R16UI:
            return gl.UNSIGNED_SHORT;
          case Format.R16I:
            return gl.SHORT;
          case Format.R32F:
            return gl.FLOAT;
          case Format.R32UI:
            return gl.UNSIGNED_INT;
          case Format.R32I:
            return gl.INT;
          case Format.RG8:
            return gl.UNSIGNED_BYTE;
          case Format.RG8SN:
            return gl.BYTE;
          case Format.RG8UI:
            return gl.UNSIGNED_BYTE;
          case Format.RG8I:
            return gl.BYTE;
          case Format.RG16F:
            return gl.HALF_FLOAT;
          case Format.RG16UI:
            return gl.UNSIGNED_SHORT;
          case Format.RG16I:
            return gl.SHORT;
          case Format.RG32F:
            return gl.FLOAT;
          case Format.RG32UI:
            return gl.UNSIGNED_INT;
          case Format.RG32I:
            return gl.INT;
          case Format.RGB8:
            return gl.UNSIGNED_BYTE;
          case Format.SRGB8:
            return gl.UNSIGNED_BYTE;
          case Format.RGB8SN:
            return gl.BYTE;
          case Format.RGB8UI:
            return gl.UNSIGNED_BYTE;
          case Format.RGB8I:
            return gl.BYTE;
          case Format.RGB16F:
            return gl.HALF_FLOAT;
          case Format.RGB16UI:
            return gl.UNSIGNED_SHORT;
          case Format.RGB16I:
            return gl.SHORT;
          case Format.RGB32F:
            return gl.FLOAT;
          case Format.RGB32UI:
            return gl.UNSIGNED_INT;
          case Format.RGB32I:
            return gl.INT;
          case Format.BGRA8:
            return gl.UNSIGNED_BYTE;
          case Format.RGBA8:
            return gl.UNSIGNED_BYTE;
          case Format.SRGB8_A8:
            return gl.UNSIGNED_BYTE;
          case Format.RGBA8SN:
            return gl.BYTE;
          case Format.RGBA8UI:
            return gl.UNSIGNED_BYTE;
          case Format.RGBA8I:
            return gl.BYTE;
          case Format.RGBA16F:
            return gl.HALF_FLOAT;
          case Format.RGBA16UI:
            return gl.UNSIGNED_SHORT;
          case Format.RGBA16I:
            return gl.SHORT;
          case Format.RGBA32F:
            return gl.FLOAT;
          case Format.RGBA32UI:
            return gl.UNSIGNED_INT;
          case Format.RGBA32I:
            return gl.INT;
          case Format.R5G6B5:
            return gl.UNSIGNED_SHORT_5_6_5;
          case Format.R11G11B10F:
            return gl.UNSIGNED_INT_10F_11F_11F_REV;
          case Format.RGB5A1:
            return gl.UNSIGNED_SHORT_5_5_5_1;
          case Format.RGBA4:
            return gl.UNSIGNED_SHORT_4_4_4_4;
          case Format.RGB10A2:
            return gl.UNSIGNED_INT_2_10_10_10_REV;
          case Format.RGB10A2UI:
            return gl.UNSIGNED_INT_2_10_10_10_REV;
          case Format.RGB9E5:
            return gl.FLOAT;
          case Format.DEPTH:
            return gl.FLOAT;
          case Format.DEPTH_STENCIL:
            return gl.UNSIGNED_INT_24_8;
          case Format.BC1:
            return gl.UNSIGNED_BYTE;
          case Format.BC1_SRGB:
            return gl.UNSIGNED_BYTE;
          case Format.BC2:
            return gl.UNSIGNED_BYTE;
          case Format.BC2_SRGB:
            return gl.UNSIGNED_BYTE;
          case Format.BC3:
            return gl.UNSIGNED_BYTE;
          case Format.BC3_SRGB:
            return gl.UNSIGNED_BYTE;
          case Format.BC4:
            return gl.UNSIGNED_BYTE;
          case Format.BC4_SNORM:
            return gl.BYTE;
          case Format.BC5:
            return gl.UNSIGNED_BYTE;
          case Format.BC5_SNORM:
            return gl.BYTE;
          case Format.BC6H_SF16:
            return gl.FLOAT;
          case Format.BC6H_UF16:
            return gl.FLOAT;
          case Format.BC7:
            return gl.UNSIGNED_BYTE;
          case Format.BC7_SRGB:
            return gl.UNSIGNED_BYTE;
          case Format.ETC_RGB8:
            return gl.UNSIGNED_BYTE;
          case Format.ETC2_RGB8:
            return gl.UNSIGNED_BYTE;
          case Format.ETC2_SRGB8:
            return gl.UNSIGNED_BYTE;
          case Format.ETC2_RGB8_A1:
            return gl.UNSIGNED_BYTE;
          case Format.ETC2_SRGB8_A1:
            return gl.UNSIGNED_BYTE;
          case Format.EAC_R11:
            return gl.UNSIGNED_BYTE;
          case Format.EAC_R11SN:
            return gl.BYTE;
          case Format.EAC_RG11:
            return gl.UNSIGNED_BYTE;
          case Format.EAC_RG11SN:
            return gl.BYTE;
          case Format.PVRTC_RGB2:
            return gl.UNSIGNED_BYTE;
          case Format.PVRTC_RGBA2:
            return gl.UNSIGNED_BYTE;
          case Format.PVRTC_RGB4:
            return gl.UNSIGNED_BYTE;
          case Format.PVRTC_RGBA4:
            return gl.UNSIGNED_BYTE;
          case Format.PVRTC2_2BPP:
            return gl.UNSIGNED_BYTE;
          case Format.PVRTC2_4BPP:
            return gl.UNSIGNED_BYTE;
          case Format.ASTC_RGBA_4X4:
          case Format.ASTC_RGBA_5X4:
          case Format.ASTC_RGBA_5X5:
          case Format.ASTC_RGBA_6X5:
          case Format.ASTC_RGBA_6X6:
          case Format.ASTC_RGBA_8X5:
          case Format.ASTC_RGBA_8X6:
          case Format.ASTC_RGBA_8X8:
          case Format.ASTC_RGBA_10X5:
          case Format.ASTC_RGBA_10X6:
          case Format.ASTC_RGBA_10X8:
          case Format.ASTC_RGBA_10X10:
          case Format.ASTC_RGBA_12X10:
          case Format.ASTC_RGBA_12X12:
          case Format.ASTC_SRGBA_4X4:
          case Format.ASTC_SRGBA_5X4:
          case Format.ASTC_SRGBA_5X5:
          case Format.ASTC_SRGBA_6X5:
          case Format.ASTC_SRGBA_6X6:
          case Format.ASTC_SRGBA_8X5:
          case Format.ASTC_SRGBA_8X6:
          case Format.ASTC_SRGBA_8X8:
          case Format.ASTC_SRGBA_10X5:
          case Format.ASTC_SRGBA_10X6:
          case Format.ASTC_SRGBA_10X8:
          case Format.ASTC_SRGBA_10X10:
          case Format.ASTC_SRGBA_12X10:
          case Format.ASTC_SRGBA_12X12:
            return gl.UNSIGNED_BYTE;
          default:
            {
              return gl.UNSIGNED_BYTE;
            }
        }
      }
      function GFXFormatToWebGLInternalFormat(format, gl) {
        switch (format) {
          case Format.A8:
            return gl.ALPHA;
          case Format.L8:
            return gl.LUMINANCE;
          case Format.LA8:
            return gl.LUMINANCE_ALPHA;
          case Format.R8:
            return gl.R8;
          case Format.R8SN:
            return gl.R8_SNORM;
          case Format.R8UI:
            return gl.R8UI;
          case Format.R8I:
            return gl.R8I;
          case Format.RG8:
            return gl.RG8;
          case Format.RG8SN:
            return gl.RG8_SNORM;
          case Format.RG8UI:
            return gl.RG8UI;
          case Format.RG8I:
            return gl.RG8I;
          case Format.RGB8:
            return gl.RGB8;
          case Format.RGB8SN:
            return gl.RGB8_SNORM;
          case Format.RGB8UI:
            return gl.RGB8UI;
          case Format.RGB8I:
            return gl.RGB8I;
          case Format.BGRA8:
            return gl.RGBA8;
          case Format.RGBA8:
            return gl.RGBA8;
          case Format.RGBA8SN:
            return gl.RGBA8_SNORM;
          case Format.RGBA8UI:
            return gl.RGBA8UI;
          case Format.RGBA8I:
            return gl.RGBA8I;
          case Format.R16I:
            return gl.R16I;
          case Format.R16UI:
            return gl.R16UI;
          case Format.R16F:
            return gl.R16F;
          case Format.RG16I:
            return gl.RG16I;
          case Format.RG16UI:
            return gl.RG16UI;
          case Format.RG16F:
            return gl.RG16F;
          case Format.RGB16I:
            return gl.RGB16I;
          case Format.RGB16UI:
            return gl.RGB16UI;
          case Format.RGB16F:
            return gl.RGB16F;
          case Format.RGBA16I:
            return gl.RGBA16I;
          case Format.RGBA16UI:
            return gl.RGBA16UI;
          case Format.RGBA16F:
            return gl.RGBA16F;
          case Format.R32I:
            return gl.R32I;
          case Format.R32UI:
            return gl.R32UI;
          case Format.R32F:
            return gl.R32F;
          case Format.RG32I:
            return gl.RG32I;
          case Format.RG32UI:
            return gl.RG32UI;
          case Format.RG32F:
            return gl.RG32F;
          case Format.RGB32I:
            return gl.RGB32I;
          case Format.RGB32UI:
            return gl.RGB32UI;
          case Format.RGB32F:
            return gl.RGB32F;
          case Format.RGBA32I:
            return gl.RGBA32I;
          case Format.RGBA32UI:
            return gl.RGBA32UI;
          case Format.RGBA32F:
            return gl.RGBA32F;
          case Format.R5G6B5:
            return gl.RGB565;
          case Format.RGB5A1:
            return gl.RGB5_A1;
          case Format.RGBA4:
            return gl.RGBA4;
          case Format.SRGB8:
            return gl.SRGB8;
          case Format.SRGB8_A8:
            return gl.SRGB8_ALPHA8;
          case Format.RGB10A2:
            return gl.RGB10_A2;
          case Format.RGB10A2UI:
            return gl.RGB10_A2UI;
          case Format.R11G11B10F:
            return gl.R11F_G11F_B10F;
          case Format.DEPTH:
            return gl.DEPTH_COMPONENT32F;
          case Format.DEPTH_STENCIL:
            return gl.DEPTH24_STENCIL8;
          case Format.BC1:
            return WebGL2EXT.COMPRESSED_RGB_S3TC_DXT1_EXT;
          case Format.BC1_ALPHA:
            return WebGL2EXT.COMPRESSED_RGBA_S3TC_DXT1_EXT;
          case Format.BC1_SRGB:
            return WebGL2EXT.COMPRESSED_SRGB_S3TC_DXT1_EXT;
          case Format.BC1_SRGB_ALPHA:
            return WebGL2EXT.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;
          case Format.BC2:
            return WebGL2EXT.COMPRESSED_RGBA_S3TC_DXT3_EXT;
          case Format.BC2_SRGB:
            return WebGL2EXT.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;
          case Format.BC3:
            return WebGL2EXT.COMPRESSED_RGBA_S3TC_DXT5_EXT;
          case Format.BC3_SRGB:
            return WebGL2EXT.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT;
          case Format.ETC_RGB8:
            return WebGL2EXT.COMPRESSED_RGB_ETC1_WEBGL;
          case Format.ETC2_RGB8:
            return WebGL2EXT.COMPRESSED_RGB8_ETC2;
          case Format.ETC2_SRGB8:
            return WebGL2EXT.COMPRESSED_SRGB8_ETC2;
          case Format.ETC2_RGB8_A1:
            return WebGL2EXT.COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2;
          case Format.ETC2_SRGB8_A1:
            return WebGL2EXT.COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2;
          case Format.ETC2_RGBA8:
            return WebGL2EXT.COMPRESSED_RGBA8_ETC2_EAC;
          case Format.ETC2_SRGB8_A8:
            return WebGL2EXT.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC;
          case Format.EAC_R11:
            return WebGL2EXT.COMPRESSED_R11_EAC;
          case Format.EAC_R11SN:
            return WebGL2EXT.COMPRESSED_SIGNED_R11_EAC;
          case Format.EAC_RG11:
            return WebGL2EXT.COMPRESSED_RG11_EAC;
          case Format.EAC_RG11SN:
            return WebGL2EXT.COMPRESSED_SIGNED_RG11_EAC;
          case Format.PVRTC_RGB2:
            return WebGL2EXT.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
          case Format.PVRTC_RGBA2:
            return WebGL2EXT.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
          case Format.PVRTC_RGB4:
            return WebGL2EXT.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
          case Format.PVRTC_RGBA4:
            return WebGL2EXT.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
          case Format.ASTC_RGBA_4X4:
            return WebGL2EXT.COMPRESSED_RGBA_ASTC_4x4_KHR;
          case Format.ASTC_RGBA_5X4:
            return WebGL2EXT.COMPRESSED_RGBA_ASTC_5x4_KHR;
          case Format.ASTC_RGBA_5X5:
            return WebGL2EXT.COMPRESSED_RGBA_ASTC_5x5_KHR;
          case Format.ASTC_RGBA_6X5:
            return WebGL2EXT.COMPRESSED_RGBA_ASTC_6x5_KHR;
          case Format.ASTC_RGBA_6X6:
            return WebGL2EXT.COMPRESSED_RGBA_ASTC_6x6_KHR;
          case Format.ASTC_RGBA_8X5:
            return WebGL2EXT.COMPRESSED_RGBA_ASTC_8x5_KHR;
          case Format.ASTC_RGBA_8X6:
            return WebGL2EXT.COMPRESSED_RGBA_ASTC_8x6_KHR;
          case Format.ASTC_RGBA_8X8:
            return WebGL2EXT.COMPRESSED_RGBA_ASTC_8x8_KHR;
          case Format.ASTC_RGBA_10X5:
            return WebGL2EXT.COMPRESSED_RGBA_ASTC_10x5_KHR;
          case Format.ASTC_RGBA_10X6:
            return WebGL2EXT.COMPRESSED_RGBA_ASTC_10x6_KHR;
          case Format.ASTC_RGBA_10X8:
            return WebGL2EXT.COMPRESSED_RGBA_ASTC_10x8_KHR;
          case Format.ASTC_RGBA_10X10:
            return WebGL2EXT.COMPRESSED_RGBA_ASTC_10x10_KHR;
          case Format.ASTC_RGBA_12X10:
            return WebGL2EXT.COMPRESSED_RGBA_ASTC_12x10_KHR;
          case Format.ASTC_RGBA_12X12:
            return WebGL2EXT.COMPRESSED_RGBA_ASTC_12x12_KHR;
          case Format.ASTC_SRGBA_4X4:
            return WebGL2EXT.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR;
          case Format.ASTC_SRGBA_5X4:
            return WebGL2EXT.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR;
          case Format.ASTC_SRGBA_5X5:
            return WebGL2EXT.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR;
          case Format.ASTC_SRGBA_6X5:
            return WebGL2EXT.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR;
          case Format.ASTC_SRGBA_6X6:
            return WebGL2EXT.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR;
          case Format.ASTC_SRGBA_8X5:
            return WebGL2EXT.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR;
          case Format.ASTC_SRGBA_8X6:
            return WebGL2EXT.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR;
          case Format.ASTC_SRGBA_8X8:
            return WebGL2EXT.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR;
          case Format.ASTC_SRGBA_10X5:
            return WebGL2EXT.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR;
          case Format.ASTC_SRGBA_10X6:
            return WebGL2EXT.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR;
          case Format.ASTC_SRGBA_10X8:
            return WebGL2EXT.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR;
          case Format.ASTC_SRGBA_10X10:
            return WebGL2EXT.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR;
          case Format.ASTC_SRGBA_12X10:
            return WebGL2EXT.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR;
          case Format.ASTC_SRGBA_12X12:
            return WebGL2EXT.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR;
          default:
            {
              error('Unsupported Format, convert to WebGL internal format failed.');
              return gl.RGBA;
            }
        }
      }
      function GFXFormatToWebGLFormat(format, gl) {
        switch (format) {
          case Format.A8:
            return gl.ALPHA;
          case Format.L8:
            return gl.LUMINANCE;
          case Format.LA8:
            return gl.LUMINANCE_ALPHA;
          case Format.R8:
          case Format.R8SN:
            return gl.RED;
          case Format.R8UI:
          case Format.R8I:
            return gl.RED;
          case Format.RG8:
          case Format.RG8SN:
          case Format.RG8UI:
          case Format.RG8I:
            return gl.RG;
          case Format.RGB8:
          case Format.RGB8SN:
          case Format.RGB8UI:
          case Format.RGB8I:
            return gl.RGB;
          case Format.BGRA8:
          case Format.RGBA8:
          case Format.RGBA8SN:
          case Format.RGBA8UI:
          case Format.RGBA8I:
            return gl.RGBA;
          case Format.R16UI:
          case Format.R16I:
          case Format.R16F:
            return gl.RED;
          case Format.RG16UI:
          case Format.RG16I:
          case Format.RG16F:
            return gl.RG;
          case Format.RGB16UI:
          case Format.RGB16I:
          case Format.RGB16F:
            return gl.RGB;
          case Format.RGBA16UI:
          case Format.RGBA16I:
          case Format.RGBA16F:
            return gl.RGBA;
          case Format.R32UI:
          case Format.R32I:
          case Format.R32F:
            return gl.RED;
          case Format.RG32UI:
          case Format.RG32I:
          case Format.RG32F:
            return gl.RG;
          case Format.RGB32UI:
          case Format.RGB32I:
          case Format.RGB32F:
            return gl.RGB;
          case Format.RGBA32UI:
          case Format.RGBA32I:
          case Format.RGBA32F:
            return gl.RGBA;
          case Format.RGB10A2:
            return gl.RGBA;
          case Format.R11G11B10F:
            return gl.RGB;
          case Format.R5G6B5:
            return gl.RGB;
          case Format.RGB5A1:
            return gl.RGBA;
          case Format.RGBA4:
            return gl.RGBA;
          case Format.SRGB8:
            return gl.RGB;
          case Format.SRGB8_A8:
            return gl.RGBA;
          case Format.DEPTH:
            return gl.DEPTH_COMPONENT;
          case Format.DEPTH_STENCIL:
            return gl.DEPTH_STENCIL;
          case Format.BC1:
            return WebGL2EXT.COMPRESSED_RGB_S3TC_DXT1_EXT;
          case Format.BC1_ALPHA:
            return WebGL2EXT.COMPRESSED_RGBA_S3TC_DXT1_EXT;
          case Format.BC1_SRGB:
            return WebGL2EXT.COMPRESSED_SRGB_S3TC_DXT1_EXT;
          case Format.BC1_SRGB_ALPHA:
            return WebGL2EXT.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;
          case Format.BC2:
            return WebGL2EXT.COMPRESSED_RGBA_S3TC_DXT3_EXT;
          case Format.BC2_SRGB:
            return WebGL2EXT.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;
          case Format.BC3:
            return WebGL2EXT.COMPRESSED_RGBA_S3TC_DXT5_EXT;
          case Format.BC3_SRGB:
            return WebGL2EXT.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT;
          case Format.ETC_RGB8:
            return WebGL2EXT.COMPRESSED_RGB_ETC1_WEBGL;
          case Format.ETC2_RGB8:
            return WebGL2EXT.COMPRESSED_RGB8_ETC2;
          case Format.ETC2_SRGB8:
            return WebGL2EXT.COMPRESSED_SRGB8_ETC2;
          case Format.ETC2_RGB8_A1:
            return WebGL2EXT.COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2;
          case Format.ETC2_SRGB8_A1:
            return WebGL2EXT.COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2;
          case Format.ETC2_RGBA8:
            return WebGL2EXT.COMPRESSED_RGBA8_ETC2_EAC;
          case Format.ETC2_SRGB8_A8:
            return WebGL2EXT.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC;
          case Format.EAC_R11:
            return WebGL2EXT.COMPRESSED_R11_EAC;
          case Format.EAC_R11SN:
            return WebGL2EXT.COMPRESSED_SIGNED_R11_EAC;
          case Format.EAC_RG11:
            return WebGL2EXT.COMPRESSED_RG11_EAC;
          case Format.EAC_RG11SN:
            return WebGL2EXT.COMPRESSED_SIGNED_RG11_EAC;
          case Format.PVRTC_RGB2:
            return WebGL2EXT.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
          case Format.PVRTC_RGBA2:
            return WebGL2EXT.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
          case Format.PVRTC_RGB4:
            return WebGL2EXT.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
          case Format.PVRTC_RGBA4:
            return WebGL2EXT.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
          case Format.ASTC_RGBA_4X4:
            return WebGL2EXT.COMPRESSED_RGBA_ASTC_4x4_KHR;
          case Format.ASTC_RGBA_5X4:
            return WebGL2EXT.COMPRESSED_RGBA_ASTC_5x4_KHR;
          case Format.ASTC_RGBA_5X5:
            return WebGL2EXT.COMPRESSED_RGBA_ASTC_5x5_KHR;
          case Format.ASTC_RGBA_6X5:
            return WebGL2EXT.COMPRESSED_RGBA_ASTC_6x5_KHR;
          case Format.ASTC_RGBA_6X6:
            return WebGL2EXT.COMPRESSED_RGBA_ASTC_6x6_KHR;
          case Format.ASTC_RGBA_8X5:
            return WebGL2EXT.COMPRESSED_RGBA_ASTC_8x5_KHR;
          case Format.ASTC_RGBA_8X6:
            return WebGL2EXT.COMPRESSED_RGBA_ASTC_8x6_KHR;
          case Format.ASTC_RGBA_8X8:
            return WebGL2EXT.COMPRESSED_RGBA_ASTC_8x8_KHR;
          case Format.ASTC_RGBA_10X5:
            return WebGL2EXT.COMPRESSED_RGBA_ASTC_10x5_KHR;
          case Format.ASTC_RGBA_10X6:
            return WebGL2EXT.COMPRESSED_RGBA_ASTC_10x6_KHR;
          case Format.ASTC_RGBA_10X8:
            return WebGL2EXT.COMPRESSED_RGBA_ASTC_10x8_KHR;
          case Format.ASTC_RGBA_10X10:
            return WebGL2EXT.COMPRESSED_RGBA_ASTC_10x10_KHR;
          case Format.ASTC_RGBA_12X10:
            return WebGL2EXT.COMPRESSED_RGBA_ASTC_12x10_KHR;
          case Format.ASTC_RGBA_12X12:
            return WebGL2EXT.COMPRESSED_RGBA_ASTC_12x12_KHR;
          case Format.ASTC_SRGBA_4X4:
            return WebGL2EXT.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR;
          case Format.ASTC_SRGBA_5X4:
            return WebGL2EXT.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR;
          case Format.ASTC_SRGBA_5X5:
            return WebGL2EXT.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR;
          case Format.ASTC_SRGBA_6X5:
            return WebGL2EXT.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR;
          case Format.ASTC_SRGBA_6X6:
            return WebGL2EXT.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR;
          case Format.ASTC_SRGBA_8X5:
            return WebGL2EXT.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR;
          case Format.ASTC_SRGBA_8X6:
            return WebGL2EXT.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR;
          case Format.ASTC_SRGBA_8X8:
            return WebGL2EXT.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR;
          case Format.ASTC_SRGBA_10X5:
            return WebGL2EXT.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR;
          case Format.ASTC_SRGBA_10X6:
            return WebGL2EXT.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR;
          case Format.ASTC_SRGBA_10X8:
            return WebGL2EXT.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR;
          case Format.ASTC_SRGBA_10X10:
            return WebGL2EXT.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR;
          case Format.ASTC_SRGBA_12X10:
            return WebGL2EXT.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR;
          case Format.ASTC_SRGBA_12X12:
            return WebGL2EXT.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR;
          default:
            {
              error('Unsupported Format, convert to WebGL format failed.');
              return gl.RGBA;
            }
        }
      }
      function GFXTypeToWebGLType(type, gl) {
        switch (type) {
          case Type$1.BOOL:
            return gl.BOOL;
          case Type$1.BOOL2:
            return gl.BOOL_VEC2;
          case Type$1.BOOL3:
            return gl.BOOL_VEC3;
          case Type$1.BOOL4:
            return gl.BOOL_VEC4;
          case Type$1.INT:
            return gl.INT;
          case Type$1.INT2:
            return gl.INT_VEC2;
          case Type$1.INT3:
            return gl.INT_VEC3;
          case Type$1.INT4:
            return gl.INT_VEC4;
          case Type$1.UINT:
            return gl.UNSIGNED_INT;
          case Type$1.FLOAT:
            return gl.FLOAT;
          case Type$1.FLOAT2:
            return gl.FLOAT_VEC2;
          case Type$1.FLOAT3:
            return gl.FLOAT_VEC3;
          case Type$1.FLOAT4:
            return gl.FLOAT_VEC4;
          case Type$1.MAT2:
            return gl.FLOAT_MAT2;
          case Type$1.MAT2X3:
            return gl.FLOAT_MAT2x3;
          case Type$1.MAT2X4:
            return gl.FLOAT_MAT2x4;
          case Type$1.MAT3X2:
            return gl.FLOAT_MAT3x2;
          case Type$1.MAT3:
            return gl.FLOAT_MAT3;
          case Type$1.MAT3X4:
            return gl.FLOAT_MAT3x4;
          case Type$1.MAT4X2:
            return gl.FLOAT_MAT4x2;
          case Type$1.MAT4X3:
            return gl.FLOAT_MAT4x3;
          case Type$1.MAT4:
            return gl.FLOAT_MAT4;
          case Type$1.SAMPLER2D:
            return gl.SAMPLER_2D;
          case Type$1.SAMPLER2D_ARRAY:
            return gl.SAMPLER_2D_ARRAY;
          case Type$1.SAMPLER3D:
            return gl.SAMPLER_3D;
          case Type$1.SAMPLER_CUBE:
            return gl.SAMPLER_CUBE;
          default:
            {
              error('Unsupported GLType, convert to GL type failed.');
              return Type$1.UNKNOWN;
            }
        }
      }
      function WebGLTypeToGFXType(glType, gl) {
        switch (glType) {
          case gl.BOOL:
            return Type$1.BOOL;
          case gl.BOOL_VEC2:
            return Type$1.BOOL2;
          case gl.BOOL_VEC3:
            return Type$1.BOOL3;
          case gl.BOOL_VEC4:
            return Type$1.BOOL4;
          case gl.INT:
            return Type$1.INT;
          case gl.INT_VEC2:
            return Type$1.INT2;
          case gl.INT_VEC3:
            return Type$1.INT3;
          case gl.INT_VEC4:
            return Type$1.INT4;
          case gl.UNSIGNED_INT:
            return Type$1.UINT;
          case gl.UNSIGNED_INT_VEC2:
            return Type$1.UINT2;
          case gl.UNSIGNED_INT_VEC3:
            return Type$1.UINT3;
          case gl.UNSIGNED_INT_VEC4:
            return Type$1.UINT4;
          case gl.FLOAT:
            return Type$1.FLOAT;
          case gl.FLOAT_VEC2:
            return Type$1.FLOAT2;
          case gl.FLOAT_VEC3:
            return Type$1.FLOAT3;
          case gl.FLOAT_VEC4:
            return Type$1.FLOAT4;
          case gl.FLOAT_MAT2:
            return Type$1.MAT2;
          case gl.FLOAT_MAT2x3:
            return Type$1.MAT2X3;
          case gl.FLOAT_MAT2x4:
            return Type$1.MAT2X4;
          case gl.FLOAT_MAT3x2:
            return Type$1.MAT3X2;
          case gl.FLOAT_MAT3:
            return Type$1.MAT3;
          case gl.FLOAT_MAT3x4:
            return Type$1.MAT3X4;
          case gl.FLOAT_MAT4x2:
            return Type$1.MAT4X2;
          case gl.FLOAT_MAT4x3:
            return Type$1.MAT4X3;
          case gl.FLOAT_MAT4:
            return Type$1.MAT4;
          case gl.SAMPLER_2D:
            return Type$1.SAMPLER2D;
          case gl.SAMPLER_2D_ARRAY:
            return Type$1.SAMPLER2D_ARRAY;
          case gl.SAMPLER_3D:
            return Type$1.SAMPLER3D;
          case gl.SAMPLER_CUBE:
            return Type$1.SAMPLER_CUBE;
          default:
            {
              error('Unsupported GLType, convert to Type failed.');
              return Type$1.UNKNOWN;
            }
        }
      }
      function WebGLGetTypeSize(glType, gl) {
        switch (glType) {
          case gl.BOOL:
            return 4;
          case gl.BOOL_VEC2:
            return 8;
          case gl.BOOL_VEC3:
            return 12;
          case gl.BOOL_VEC4:
            return 16;
          case gl.INT:
            return 4;
          case gl.INT_VEC2:
            return 8;
          case gl.INT_VEC3:
            return 12;
          case gl.INT_VEC4:
            return 16;
          case gl.UNSIGNED_INT:
            return 4;
          case gl.UNSIGNED_INT_VEC2:
            return 8;
          case gl.UNSIGNED_INT_VEC3:
            return 12;
          case gl.UNSIGNED_INT_VEC4:
            return 16;
          case gl.FLOAT:
            return 4;
          case gl.FLOAT_VEC2:
            return 8;
          case gl.FLOAT_VEC3:
            return 12;
          case gl.FLOAT_VEC4:
            return 16;
          case gl.FLOAT_MAT2:
            return 16;
          case gl.FLOAT_MAT2x3:
            return 24;
          case gl.FLOAT_MAT2x4:
            return 32;
          case gl.FLOAT_MAT3x2:
            return 24;
          case gl.FLOAT_MAT3:
            return 36;
          case gl.FLOAT_MAT3x4:
            return 48;
          case gl.FLOAT_MAT4x2:
            return 32;
          case gl.FLOAT_MAT4x3:
            return 48;
          case gl.FLOAT_MAT4:
            return 64;
          case gl.SAMPLER_2D:
            return 4;
          case gl.SAMPLER_2D_ARRAY:
            return 4;
          case gl.SAMPLER_2D_ARRAY_SHADOW:
            return 4;
          case gl.SAMPLER_3D:
            return 4;
          case gl.SAMPLER_CUBE:
            return 4;
          case gl.INT_SAMPLER_2D:
            return 4;
          case gl.INT_SAMPLER_2D_ARRAY:
            return 4;
          case gl.INT_SAMPLER_3D:
            return 4;
          case gl.INT_SAMPLER_CUBE:
            return 4;
          case gl.UNSIGNED_INT_SAMPLER_2D:
            return 4;
          case gl.UNSIGNED_INT_SAMPLER_2D_ARRAY:
            return 4;
          case gl.UNSIGNED_INT_SAMPLER_3D:
            return 4;
          case gl.UNSIGNED_INT_SAMPLER_CUBE:
            return 4;
          default:
            {
              error('Unsupported GLType, get type failed.');
              return 0;
            }
        }
      }
      function WebGLGetComponentCount(glType, gl) {
        switch (glType) {
          case gl.FLOAT_MAT2:
            return 2;
          case gl.FLOAT_MAT2x3:
            return 2;
          case gl.FLOAT_MAT2x4:
            return 2;
          case gl.FLOAT_MAT3x2:
            return 3;
          case gl.FLOAT_MAT3:
            return 3;
          case gl.FLOAT_MAT3x4:
            return 3;
          case gl.FLOAT_MAT4x2:
            return 4;
          case gl.FLOAT_MAT4x3:
            return 4;
          case gl.FLOAT_MAT4:
            return 4;
          default:
            {
              return 1;
            }
        }
      }
      var WebGLCmpFuncs = [0x0200, 0x0201, 0x0202, 0x0203, 0x0204, 0x0205, 0x0206, 0x0207];
      var WebGLStencilOps = [0x0000, 0x1E00, 0x1E01, 0x1E02, 0x1E03, 0x150A, 0x8507, 0x8508];
      var WebGLBlendOps = [0x8006, 0x800A, 0x800B, 0x8007, 0x8008];
      var WebGLBlendFactors = [0x0000, 0x0001, 0x0302, 0x0304, 0x0303, 0x0305, 0x0300, 0x0306, 0x0301, 0x0307, 0x0308, 0x8001, 0x8002, 0x8003, 0x8004];
      var WebGL2Cmd;
      (function (WebGL2Cmd) {
        WebGL2Cmd[WebGL2Cmd["BEGIN_RENDER_PASS"] = 0] = "BEGIN_RENDER_PASS";
        WebGL2Cmd[WebGL2Cmd["END_RENDER_PASS"] = 1] = "END_RENDER_PASS";
        WebGL2Cmd[WebGL2Cmd["BIND_STATES"] = 2] = "BIND_STATES";
        WebGL2Cmd[WebGL2Cmd["DRAW"] = 3] = "DRAW";
        WebGL2Cmd[WebGL2Cmd["UPDATE_BUFFER"] = 4] = "UPDATE_BUFFER";
        WebGL2Cmd[WebGL2Cmd["COPY_BUFFER_TO_TEXTURE"] = 5] = "COPY_BUFFER_TO_TEXTURE";
        WebGL2Cmd[WebGL2Cmd["BLIT_TEXTURE"] = 6] = "BLIT_TEXTURE";
        WebGL2Cmd[WebGL2Cmd["COUNT"] = 7] = "COUNT";
      })(WebGL2Cmd || (WebGL2Cmd = {}));
      var WebGL2CmdObject = function WebGL2CmdObject(type) {
        this.cmdType = void 0;
        this.refCount = 0;
        this.cmdType = type;
      };
      var WebGL2CmdBeginRenderPass = function (_WebGL2CmdObject) {
        _inheritsLoose(WebGL2CmdBeginRenderPass, _WebGL2CmdObject);
        function WebGL2CmdBeginRenderPass() {
          var _this;
          _this = _WebGL2CmdObject.call(this, WebGL2Cmd.BEGIN_RENDER_PASS) || this;
          _this.gpuRenderPass = null;
          _this.gpuFramebuffer = null;
          _this.renderArea = new Rect();
          _this.clearColors = [];
          _this.clearDepth = 1.0;
          _this.clearStencil = 0;
          return _this;
        }
        var _proto = WebGL2CmdBeginRenderPass.prototype;
        _proto.clear = function clear() {
          this.gpuFramebuffer = null;
          this.clearColors.length = 0;
        };
        return WebGL2CmdBeginRenderPass;
      }(WebGL2CmdObject);
      var WebGL2CmdBindStates = function (_WebGL2CmdObject2) {
        _inheritsLoose(WebGL2CmdBindStates, _WebGL2CmdObject2);
        function WebGL2CmdBindStates() {
          var _this2;
          _this2 = _WebGL2CmdObject2.call(this, WebGL2Cmd.BIND_STATES) || this;
          _this2.gpuPipelineState = null;
          _this2.gpuInputAssembler = null;
          _this2.gpuDescriptorSets = [];
          _this2.dynamicOffsets = [];
          _this2.dynamicStates = new DynamicStates();
          return _this2;
        }
        var _proto2 = WebGL2CmdBindStates.prototype;
        _proto2.clear = function clear() {
          this.gpuPipelineState = null;
          this.gpuInputAssembler = null;
          this.gpuDescriptorSets.length = 0;
          this.dynamicOffsets.length = 0;
        };
        return WebGL2CmdBindStates;
      }(WebGL2CmdObject);
      var WebGL2CmdDraw = function (_WebGL2CmdObject3) {
        _inheritsLoose(WebGL2CmdDraw, _WebGL2CmdObject3);
        function WebGL2CmdDraw() {
          var _this3;
          _this3 = _WebGL2CmdObject3.call(this, WebGL2Cmd.DRAW) || this;
          _this3.drawInfo = new DrawInfo();
          return _this3;
        }
        var _proto3 = WebGL2CmdDraw.prototype;
        _proto3.clear = function clear() {};
        return WebGL2CmdDraw;
      }(WebGL2CmdObject);
      var WebGL2CmdUpdateBuffer = function (_WebGL2CmdObject4) {
        _inheritsLoose(WebGL2CmdUpdateBuffer, _WebGL2CmdObject4);
        function WebGL2CmdUpdateBuffer() {
          var _this4;
          _this4 = _WebGL2CmdObject4.call(this, WebGL2Cmd.UPDATE_BUFFER) || this;
          _this4.gpuBuffer = null;
          _this4.buffer = null;
          _this4.offset = 0;
          _this4.size = 0;
          return _this4;
        }
        var _proto4 = WebGL2CmdUpdateBuffer.prototype;
        _proto4.clear = function clear() {
          this.gpuBuffer = null;
          this.buffer = null;
        };
        return WebGL2CmdUpdateBuffer;
      }(WebGL2CmdObject);
      var WebGL2CmdCopyBufferToTexture = function (_WebGL2CmdObject5) {
        _inheritsLoose(WebGL2CmdCopyBufferToTexture, _WebGL2CmdObject5);
        function WebGL2CmdCopyBufferToTexture() {
          var _this5;
          _this5 = _WebGL2CmdObject5.call(this, WebGL2Cmd.COPY_BUFFER_TO_TEXTURE) || this;
          _this5.gpuTexture = null;
          _this5.buffers = [];
          _this5.regions = [];
          return _this5;
        }
        var _proto5 = WebGL2CmdCopyBufferToTexture.prototype;
        _proto5.clear = function clear() {
          this.gpuTexture = null;
          this.buffers.length = 0;
          this.regions.length = 0;
        };
        return WebGL2CmdCopyBufferToTexture;
      }(WebGL2CmdObject);
      var WebGL2CmdBlitTexture = function (_WebGL2CmdObject6) {
        _inheritsLoose(WebGL2CmdBlitTexture, _WebGL2CmdObject6);
        function WebGL2CmdBlitTexture() {
          var _this6;
          _this6 = _WebGL2CmdObject6.call(this, WebGL2Cmd.BLIT_TEXTURE) || this;
          _this6.srcTexture = null;
          _this6.dstTexture = null;
          _this6.regions = [];
          _this6.filter = Filter$1.LINEAR;
          return _this6;
        }
        var _proto6 = WebGL2CmdBlitTexture.prototype;
        _proto6.clear = function clear() {
          this.srcTexture = null;
          this.dstTexture = null;
          this.regions.length = 0;
        };
        return WebGL2CmdBlitTexture;
      }(WebGL2CmdObject);
      var WebGL2CmdPackage = function () {
        function WebGL2CmdPackage() {
          this.cmds = new CachedArray(1);
          this.beginRenderPassCmds = new CachedArray(1);
          this.bindStatesCmds = new CachedArray(1);
          this.drawCmds = new CachedArray(1);
          this.updateBufferCmds = new CachedArray(1);
          this.copyBufferToTextureCmds = new CachedArray(1);
          this.blitTextureCmds = new CachedArray(1);
        }
        var _proto7 = WebGL2CmdPackage.prototype;
        _proto7.clearCmds = function clearCmds(allocator) {
          if (this.beginRenderPassCmds.length) {
            allocator.beginRenderPassCmdPool.freeCmds(this.beginRenderPassCmds);
            this.beginRenderPassCmds.clear();
          }
          if (this.bindStatesCmds.length) {
            allocator.bindStatesCmdPool.freeCmds(this.bindStatesCmds);
            this.bindStatesCmds.clear();
          }
          if (this.drawCmds.length) {
            allocator.drawCmdPool.freeCmds(this.drawCmds);
            this.drawCmds.clear();
          }
          if (this.updateBufferCmds.length) {
            allocator.updateBufferCmdPool.freeCmds(this.updateBufferCmds);
            this.updateBufferCmds.clear();
          }
          if (this.copyBufferToTextureCmds.length) {
            allocator.copyBufferToTextureCmdPool.freeCmds(this.copyBufferToTextureCmds);
            this.copyBufferToTextureCmds.clear();
          }
          if (this.blitTextureCmds.length) {
            allocator.blitTextureCmdPool.freeCmds(this.blitTextureCmds);
            this.blitTextureCmds.clear();
          }
          this.cmds.clear();
        };
        return WebGL2CmdPackage;
      }();
      function WebGL2CmdFuncCreateBuffer(device, gpuBuffer) {
        var gl = device.gl;
        var cache = device.stateCache;
        var glUsage = gpuBuffer.memUsage & MemoryUsageBit.HOST ? gl.DYNAMIC_DRAW : gl.STATIC_DRAW;
        if (gpuBuffer.usage & BufferUsageBit.VERTEX) {
          gpuBuffer.glTarget = gl.ARRAY_BUFFER;
          var glBuffer = gl.createBuffer();
          if (glBuffer) {
            gpuBuffer.glBuffer = glBuffer;
            if (gpuBuffer.size > 0) {
              if (device.extensions.useVAO) {
                if (cache.glVAO) {
                  gl.bindVertexArray(null);
                  cache.glVAO = null;
                }
              }
              gfxStateCache.gpuInputAssembler = null;
              if (device.stateCache.glArrayBuffer !== gpuBuffer.glBuffer) {
                gl.bindBuffer(gl.ARRAY_BUFFER, gpuBuffer.glBuffer);
                device.stateCache.glArrayBuffer = gpuBuffer.glBuffer;
              }
              gl.bufferData(gl.ARRAY_BUFFER, gpuBuffer.size, glUsage);
              gl.bindBuffer(gl.ARRAY_BUFFER, null);
              device.stateCache.glArrayBuffer = null;
            }
          }
        } else if (gpuBuffer.usage & BufferUsageBit.INDEX) {
          gpuBuffer.glTarget = gl.ELEMENT_ARRAY_BUFFER;
          var _glBuffer = gl.createBuffer();
          if (_glBuffer) {
            gpuBuffer.glBuffer = _glBuffer;
            if (gpuBuffer.size > 0) {
              if (device.extensions.useVAO) {
                if (cache.glVAO) {
                  gl.bindVertexArray(null);
                  cache.glVAO = null;
                }
              }
              gfxStateCache.gpuInputAssembler = null;
              if (device.stateCache.glElementArrayBuffer !== gpuBuffer.glBuffer) {
                gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, gpuBuffer.glBuffer);
                device.stateCache.glElementArrayBuffer = gpuBuffer.glBuffer;
              }
              gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, gpuBuffer.size, glUsage);
              gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, null);
              device.stateCache.glElementArrayBuffer = null;
            }
          }
        } else if (gpuBuffer.usage & BufferUsageBit.UNIFORM) {
          gpuBuffer.glTarget = gl.UNIFORM_BUFFER;
          var _glBuffer2 = gl.createBuffer();
          if (_glBuffer2 && gpuBuffer.size > 0) {
            gpuBuffer.glBuffer = _glBuffer2;
            if (device.stateCache.glUniformBuffer !== gpuBuffer.glBuffer) {
              gl.bindBuffer(gl.UNIFORM_BUFFER, gpuBuffer.glBuffer);
              device.stateCache.glUniformBuffer = gpuBuffer.glBuffer;
            }
            gl.bufferData(gl.UNIFORM_BUFFER, gpuBuffer.size, glUsage);
            gl.bindBuffer(gl.UNIFORM_BUFFER, null);
            device.stateCache.glUniformBuffer = null;
          }
        } else if (gpuBuffer.usage & BufferUsageBit.INDIRECT) {
          gpuBuffer.glTarget = gl.NONE;
        } else if (gpuBuffer.usage & BufferUsageBit.TRANSFER_DST) {
          gpuBuffer.glTarget = gl.NONE;
        } else if (gpuBuffer.usage & BufferUsageBit.TRANSFER_SRC) {
          gpuBuffer.glTarget = gl.NONE;
        } else {
          error('Unsupported BufferType, create buffer failed.');
          gpuBuffer.glTarget = gl.NONE;
        }
      }
      function WebGL2CmdFuncDestroyBuffer(device, gpuBuffer) {
        var gl = device.gl;
        var cache = device.stateCache;
        if (gpuBuffer.glBuffer) {
          switch (gpuBuffer.glTarget) {
            case gl.ARRAY_BUFFER:
              if (device.extensions.useVAO) {
                if (cache.glVAO) {
                  gl.bindVertexArray(null);
                  device.stateCache.glVAO = null;
                }
              }
              gfxStateCache.gpuInputAssembler = null;
              gl.bindBuffer(gl.ARRAY_BUFFER, null);
              device.stateCache.glArrayBuffer = null;
              break;
            case gl.ELEMENT_ARRAY_BUFFER:
              if (device.extensions.useVAO) {
                if (cache.glVAO) {
                  gl.bindVertexArray(null);
                  device.stateCache.glVAO = null;
                }
              }
              gfxStateCache.gpuInputAssembler = null;
              gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, null);
              device.stateCache.glElementArrayBuffer = null;
              break;
            case gl.UNIFORM_BUFFER:
              gl.bindBuffer(gl.UNIFORM_BUFFER, null);
              device.stateCache.glUniformBuffer = null;
              break;
          }
          gl.deleteBuffer(gpuBuffer.glBuffer);
          gpuBuffer.glBuffer = null;
        }
      }
      function WebGL2CmdFuncResizeBuffer(device, gpuBuffer) {
        var gl = device.gl;
        var cache = device.stateCache;
        var glUsage = gpuBuffer.memUsage & MemoryUsageBit.HOST ? gl.DYNAMIC_DRAW : gl.STATIC_DRAW;
        if (gpuBuffer.usage & BufferUsageBit.VERTEX) {
          if (device.extensions.useVAO) {
            if (cache.glVAO) {
              gl.bindVertexArray(null);
              cache.glVAO = null;
            }
          }
          gfxStateCache.gpuInputAssembler = null;
          if (cache.glArrayBuffer !== gpuBuffer.glBuffer) {
            gl.bindBuffer(gl.ARRAY_BUFFER, gpuBuffer.glBuffer);
          }
          if (gpuBuffer.buffer) {
            gl.bufferData(gl.ARRAY_BUFFER, gpuBuffer.buffer, glUsage);
          } else {
            gl.bufferData(gl.ARRAY_BUFFER, gpuBuffer.size, glUsage);
          }
          gl.bindBuffer(gl.ARRAY_BUFFER, null);
          cache.glArrayBuffer = null;
        } else if (gpuBuffer.usage & BufferUsageBit.INDEX) {
          if (device.extensions.useVAO) {
            if (cache.glVAO) {
              gl.bindVertexArray(null);
              cache.glVAO = null;
            }
          }
          gfxStateCache.gpuInputAssembler = null;
          if (device.stateCache.glElementArrayBuffer !== gpuBuffer.glBuffer) {
            gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, gpuBuffer.glBuffer);
          }
          if (gpuBuffer.buffer) {
            gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, gpuBuffer.buffer, glUsage);
          } else {
            gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, gpuBuffer.size, glUsage);
          }
          gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, null);
          device.stateCache.glElementArrayBuffer = null;
        } else if (gpuBuffer.usage & BufferUsageBit.UNIFORM) {
          if (device.stateCache.glUniformBuffer !== gpuBuffer.glBuffer) {
            gl.bindBuffer(gl.UNIFORM_BUFFER, gpuBuffer.glBuffer);
          }
          gl.bufferData(gl.UNIFORM_BUFFER, gpuBuffer.size, glUsage);
          gl.bindBuffer(gl.UNIFORM_BUFFER, null);
          device.stateCache.glUniformBuffer = null;
        } else if (gpuBuffer.usage & BufferUsageBit.INDIRECT || gpuBuffer.usage & BufferUsageBit.TRANSFER_DST || gpuBuffer.usage & BufferUsageBit.TRANSFER_SRC) {
          gpuBuffer.glTarget = gl.NONE;
        } else {
          error('Unsupported BufferType, create buffer failed.');
          gpuBuffer.glTarget = gl.NONE;
        }
      }
      function WebGL2CmdFuncUpdateBuffer(device, gpuBuffer, buffer, offset, size) {
        if (gpuBuffer.usage & BufferUsageBit.INDIRECT) {
          gpuBuffer.indirects.clearDraws();
          var drawInfos = buffer.drawInfos;
          for (var i = 0; i < drawInfos.length; ++i) {
            gpuBuffer.indirects.setDrawInfo(offset + i, drawInfos[i]);
          }
        } else {
          var buff = buffer;
          var gl = device.gl;
          var cache = device.stateCache;
          switch (gpuBuffer.glTarget) {
            case gl.ARRAY_BUFFER:
              {
                if (device.extensions.useVAO) {
                  if (cache.glVAO) {
                    gl.bindVertexArray(null);
                    cache.glVAO = null;
                  }
                }
                gfxStateCache.gpuInputAssembler = null;
                if (cache.glArrayBuffer !== gpuBuffer.glBuffer) {
                  gl.bindBuffer(gl.ARRAY_BUFFER, gpuBuffer.glBuffer);
                  cache.glArrayBuffer = gpuBuffer.glBuffer;
                }
                if (size === buff.byteLength) {
                  gl.bufferSubData(gpuBuffer.glTarget, offset, buff);
                } else {
                  gl.bufferSubData(gpuBuffer.glTarget, offset, buff.slice(0, size));
                }
                break;
              }
            case gl.ELEMENT_ARRAY_BUFFER:
              {
                if (device.extensions.useVAO) {
                  if (cache.glVAO) {
                    gl.bindVertexArray(null);
                    cache.glVAO = null;
                  }
                }
                gfxStateCache.gpuInputAssembler = null;
                if (cache.glElementArrayBuffer !== gpuBuffer.glBuffer) {
                  gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, gpuBuffer.glBuffer);
                  cache.glElementArrayBuffer = gpuBuffer.glBuffer;
                }
                if (size === buff.byteLength) {
                  gl.bufferSubData(gpuBuffer.glTarget, offset, buff);
                } else {
                  gl.bufferSubData(gpuBuffer.glTarget, offset, buff.slice(0, size));
                }
                break;
              }
            case gl.UNIFORM_BUFFER:
              {
                if (cache.glUniformBuffer !== gpuBuffer.glBuffer) {
                  gl.bindBuffer(gl.UNIFORM_BUFFER, gpuBuffer.glBuffer);
                  cache.glUniformBuffer = gpuBuffer.glBuffer;
                }
                if (size === buff.byteLength) {
                  gl.bufferSubData(gpuBuffer.glTarget, offset, buff);
                } else {
                  gl.bufferSubData(gpuBuffer.glTarget, offset, new Float32Array(buff, 0, size / 4));
                }
                break;
              }
            default:
              {
                error('Unsupported BufferType, update buffer failed.');
              }
          }
        }
      }
      function WebGL2CmdFuncCreateTexture(device, gpuTexture) {
        var gl = device.gl;
        gpuTexture.glInternalFmt = GFXFormatToWebGLInternalFormat(gpuTexture.format, gl);
        gpuTexture.glFormat = GFXFormatToWebGLFormat(gpuTexture.format, gl);
        gpuTexture.glType = GFXFormatToWebGLType(gpuTexture.format, gl);
        var w = gpuTexture.width;
        var h = gpuTexture.height;
        var d = gpuTexture.depth;
        var l = gpuTexture.arrayLayer;
        switch (gpuTexture.type) {
          case TextureType.TEX2D:
            {
              gpuTexture.glTarget = gl.TEXTURE_2D;
              var maxSize = Math.max(w, h);
              if (maxSize > device.capabilities.maxTextureSize) {
                errorID(9100, maxSize, device.capabilities.maxTextureSize);
              }
              if (gpuTexture.samples === SampleCount.X1) {
                gpuTexture.glTexture = gl.createTexture();
                if (gpuTexture.size > 0) {
                  var glTexUnit = device.stateCache.glTexUnits[device.stateCache.texUnit];
                  if (glTexUnit.glTexture !== gpuTexture.glTexture) {
                    gl.bindTexture(gl.TEXTURE_2D, gpuTexture.glTexture);
                    glTexUnit.glTexture = gpuTexture.glTexture;
                  }
                  if (FormatInfos[gpuTexture.format].isCompressed) {
                    for (var i = 0; i < gpuTexture.mipLevel; ++i) {
                      var imgSize = FormatSize(gpuTexture.format, w, h, 1);
                      var view = new Uint8Array(imgSize);
                      gl.compressedTexImage2D(gl.TEXTURE_2D, i, gpuTexture.glInternalFmt, w, h, 0, view);
                      w = Math.max(1, w >> 1);
                      h = Math.max(1, h >> 1);
                    }
                  } else {
                    gl.texStorage2D(gl.TEXTURE_2D, gpuTexture.mipLevel, gpuTexture.glInternalFmt, w, h);
                  }
                }
              } else {
                gpuTexture.glRenderbuffer = gl.createRenderbuffer();
                if (gpuTexture.size > 0) {
                  if (device.stateCache.glRenderbuffer !== gpuTexture.glRenderbuffer) {
                    gl.bindRenderbuffer(gl.RENDERBUFFER, gpuTexture.glRenderbuffer);
                    device.stateCache.glRenderbuffer = gpuTexture.glRenderbuffer;
                  }
                  gl.renderbufferStorageMultisample(gl.RENDERBUFFER, gpuTexture.samples, gpuTexture.glInternalFmt, gpuTexture.width, gpuTexture.height);
                }
              }
              break;
            }
          case TextureType.TEX2D_ARRAY:
            {
              gpuTexture.glTarget = gl.TEXTURE_2D_ARRAY;
              var _maxSize = Math.max(w, h);
              if (_maxSize > device.capabilities.maxTextureSize) {
                errorID(9100, _maxSize, device.capabilities.maxTextureSize);
              }
              if (l > device.capabilities.maxArrayTextureLayers) {
                errorID(9100, l, device.capabilities.maxArrayTextureLayers);
              }
              gpuTexture.glTexture = gl.createTexture();
              if (gpuTexture.size > 0) {
                var _glTexUnit = device.stateCache.glTexUnits[device.stateCache.texUnit];
                if (_glTexUnit.glTexture !== gpuTexture.glTexture) {
                  gl.bindTexture(gl.TEXTURE_2D_ARRAY, gpuTexture.glTexture);
                  _glTexUnit.glTexture = gpuTexture.glTexture;
                }
                if (FormatInfos[gpuTexture.format].isCompressed) {
                  for (var _i = 0; _i < gpuTexture.mipLevel; ++_i) {
                    var _imgSize = FormatSize(gpuTexture.format, w, h, l);
                    var _view = new Uint8Array(_imgSize);
                    gl.compressedTexImage3D(gl.TEXTURE_2D_ARRAY, _i, gpuTexture.glInternalFmt, w, h, l, 0, _view);
                    w = Math.max(1, w >> 1);
                    h = Math.max(1, h >> 1);
                  }
                } else {
                  gl.texStorage3D(gl.TEXTURE_2D_ARRAY, gpuTexture.mipLevel, gpuTexture.glInternalFmt, w, h, l);
                }
              }
              break;
            }
          case TextureType.TEX3D:
            {
              gpuTexture.glTarget = gl.TEXTURE_3D;
              var _maxSize2 = Math.max(Math.max(w, h), d);
              if (_maxSize2 > device.capabilities.max3DTextureSize) {
                errorID(9100, _maxSize2, device.capabilities.max3DTextureSize);
              }
              gpuTexture.glTexture = gl.createTexture();
              if (gpuTexture.size > 0) {
                var _glTexUnit2 = device.stateCache.glTexUnits[device.stateCache.texUnit];
                if (_glTexUnit2.glTexture !== gpuTexture.glTexture) {
                  gl.bindTexture(gl.TEXTURE_3D, gpuTexture.glTexture);
                  _glTexUnit2.glTexture = gpuTexture.glTexture;
                }
                if (FormatInfos[gpuTexture.format].isCompressed) {
                  for (var _i2 = 0; _i2 < gpuTexture.mipLevel; ++_i2) {
                    var _imgSize2 = FormatSize(gpuTexture.format, w, h, d);
                    var _view2 = new Uint8Array(_imgSize2);
                    gl.compressedTexImage3D(gl.TEXTURE_3D, _i2, gpuTexture.glInternalFmt, w, h, d, 0, _view2);
                    w = Math.max(1, w >> 1);
                    h = Math.max(1, h >> 1);
                  }
                } else {
                  gl.texStorage3D(gl.TEXTURE_3D, gpuTexture.mipLevel, gpuTexture.glInternalFmt, w, h, d);
                }
              }
              break;
            }
          case TextureType.CUBE:
            {
              gpuTexture.glTarget = gl.TEXTURE_CUBE_MAP;
              var _maxSize3 = Math.max(w, h);
              if (_maxSize3 > device.capabilities.maxCubeMapTextureSize) {
                errorID(9100, _maxSize3, device.capabilities.maxTextureSize);
              }
              gpuTexture.glTexture = gl.createTexture();
              if (gpuTexture.size > 0) {
                var _glTexUnit3 = device.stateCache.glTexUnits[device.stateCache.texUnit];
                if (_glTexUnit3.glTexture !== gpuTexture.glTexture) {
                  gl.bindTexture(gl.TEXTURE_CUBE_MAP, gpuTexture.glTexture);
                  _glTexUnit3.glTexture = gpuTexture.glTexture;
                }
                if (FormatInfos[gpuTexture.format].isCompressed) {
                  for (var _i3 = 0; _i3 < gpuTexture.mipLevel; ++_i3) {
                    var _imgSize3 = FormatSize(gpuTexture.format, w, h, 1);
                    var _view3 = new Uint8Array(_imgSize3);
                    for (var f = 0; f < 6; ++f) {
                      gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + f, _i3, gpuTexture.glInternalFmt, w, h, 0, _view3);
                    }
                    w = Math.max(1, w >> 1);
                    h = Math.max(1, h >> 1);
                  }
                } else {
                  gl.texStorage2D(gl.TEXTURE_CUBE_MAP, gpuTexture.mipLevel, gpuTexture.glInternalFmt, w, h);
                }
              }
              break;
            }
          default:
            {
              error('Unsupported TextureType, create texture failed.');
              gpuTexture.type = TextureType.TEX2D;
              gpuTexture.glTarget = gl.TEXTURE_2D;
            }
        }
      }
      function WebGL2CmdFuncDestroyTexture(device, gpuTexture) {
        var gl = device.gl;
        if (gpuTexture.glTexture) {
          var glTexUnits = device.stateCache.glTexUnits;
          var texUnit = device.stateCache.texUnit;
          gl.deleteTexture(gpuTexture.glTexture);
          for (var i = 0; i < glTexUnits.length; ++i) {
            if (glTexUnits[i].glTexture === gpuTexture.glTexture) {
              gl.activeTexture(gl.TEXTURE0 + i);
              texUnit = i;
              gl.bindTexture(gpuTexture.glTarget, null);
              glTexUnits[i].glTexture = null;
            }
          }
          device.stateCache.texUnit = texUnit;
          gpuTexture.glTexture = null;
        }
        if (gpuTexture.glRenderbuffer) {
          var glRenderbuffer = device.stateCache.glRenderbuffer;
          gl.deleteRenderbuffer(gpuTexture.glRenderbuffer);
          if (glRenderbuffer === gpuTexture.glRenderbuffer) {
            gl.bindRenderbuffer(gl.RENDERBUFFER, null);
            glRenderbuffer = null;
          }
          gpuTexture.glRenderbuffer = null;
        }
      }
      function WebGL2CmdFuncResizeTexture(device, gpuTexture) {
        if (!gpuTexture.size) return;
        var gl = device.gl;
        var w = gpuTexture.width;
        var h = gpuTexture.height;
        var d = gpuTexture.depth;
        var l = gpuTexture.arrayLayer;
        switch (gpuTexture.type) {
          case TextureType.TEX2D:
            {
              gpuTexture.glTarget = gl.TEXTURE_2D;
              var maxSize = Math.max(w, h);
              if (maxSize > device.capabilities.maxTextureSize) {
                errorID(9100, maxSize, device.capabilities.maxTextureSize);
              }
              if (gpuTexture.samples === SampleCount.X1) {
                var glTexUnit = device.stateCache.glTexUnits[device.stateCache.texUnit];
                if (glTexUnit.glTexture !== gpuTexture.glTexture) {
                  gl.bindTexture(gl.TEXTURE_2D, gpuTexture.glTexture);
                  glTexUnit.glTexture = gpuTexture.glTexture;
                }
                if (FormatInfos[gpuTexture.format].isCompressed) {
                  for (var i = 0; i < gpuTexture.mipLevel; ++i) {
                    var imgSize = FormatSize(gpuTexture.format, w, h, 1);
                    var view = new Uint8Array(imgSize);
                    gl.compressedTexImage2D(gl.TEXTURE_2D, i, gpuTexture.glInternalFmt, w, h, 0, view);
                    w = Math.max(1, w >> 1);
                    h = Math.max(1, h >> 1);
                  }
                } else {
                  WebGL2CmdFuncDestroyTexture(device, gpuTexture);
                  WebGL2CmdFuncCreateTexture(device, gpuTexture);
                }
              } else if (gpuTexture.glRenderbuffer) {
                if (device.stateCache.glRenderbuffer !== gpuTexture.glRenderbuffer) {
                  gl.bindRenderbuffer(gl.RENDERBUFFER, gpuTexture.glRenderbuffer);
                  device.stateCache.glRenderbuffer = gpuTexture.glRenderbuffer;
                }
                gl.renderbufferStorageMultisample(gl.RENDERBUFFER, gpuTexture.samples, gpuTexture.glInternalFmt, gpuTexture.width, gpuTexture.height);
              }
              break;
            }
          case TextureType.TEX2D_ARRAY:
            {
              gpuTexture.glTarget = gl.TEXTURE_2D_ARRAY;
              var _maxSize4 = Math.max(w, h);
              if (_maxSize4 > device.capabilities.maxTextureSize) {
                errorID(9100, _maxSize4, device.capabilities.maxTextureSize);
              }
              if (l > device.capabilities.maxArrayTextureLayers) {
                errorID(9100, l, device.capabilities.maxArrayTextureLayers);
              }
              gpuTexture.glTexture = gl.createTexture();
              if (gpuTexture.size > 0) {
                var _glTexUnit4 = device.stateCache.glTexUnits[device.stateCache.texUnit];
                if (_glTexUnit4.glTexture !== gpuTexture.glTexture) {
                  gl.bindTexture(gl.TEXTURE_2D_ARRAY, gpuTexture.glTexture);
                  _glTexUnit4.glTexture = gpuTexture.glTexture;
                }
                if (FormatInfos[gpuTexture.format].isCompressed) {
                  for (var _i4 = 0; _i4 < gpuTexture.mipLevel; ++_i4) {
                    var _imgSize4 = FormatSize(gpuTexture.format, w, h, l);
                    var _view4 = new Uint8Array(_imgSize4);
                    gl.compressedTexImage3D(gl.TEXTURE_2D_ARRAY, _i4, gpuTexture.glInternalFmt, w, h, l, 0, _view4);
                    w = Math.max(1, w >> 1);
                    h = Math.max(1, h >> 1);
                  }
                } else {
                  gl.texStorage3D(gl.TEXTURE_2D_ARRAY, gpuTexture.mipLevel, gpuTexture.glInternalFmt, w, h, l);
                }
              }
              break;
            }
          case TextureType.TEX3D:
            {
              gpuTexture.glTarget = gl.TEXTURE_3D;
              var _maxSize5 = Math.max(Math.max(w, h), d);
              if (_maxSize5 > device.capabilities.max3DTextureSize) {
                errorID(9100, _maxSize5, device.capabilities.max3DTextureSize);
              }
              gpuTexture.glTexture = gl.createTexture();
              if (gpuTexture.size > 0) {
                var _glTexUnit5 = device.stateCache.glTexUnits[device.stateCache.texUnit];
                if (_glTexUnit5.glTexture !== gpuTexture.glTexture) {
                  gl.bindTexture(gl.TEXTURE_3D, gpuTexture.glTexture);
                  _glTexUnit5.glTexture = gpuTexture.glTexture;
                }
                if (FormatInfos[gpuTexture.format].isCompressed) {
                  for (var _i5 = 0; _i5 < gpuTexture.mipLevel; ++_i5) {
                    var _imgSize5 = FormatSize(gpuTexture.format, w, h, d);
                    var _view5 = new Uint8Array(_imgSize5);
                    gl.compressedTexImage3D(gl.TEXTURE_3D, _i5, gpuTexture.glInternalFmt, w, h, d, 0, _view5);
                    w = Math.max(1, w >> 1);
                    h = Math.max(1, h >> 1);
                  }
                } else {
                  gl.texStorage3D(gl.TEXTURE_3D, gpuTexture.mipLevel, gpuTexture.glInternalFmt, w, h, d);
                }
              }
              break;
            }
          case TextureType.CUBE:
            {
              gpuTexture.type = TextureType.CUBE;
              gpuTexture.glTarget = gl.TEXTURE_CUBE_MAP;
              var _maxSize6 = Math.max(w, h);
              if (_maxSize6 > device.capabilities.maxCubeMapTextureSize) {
                errorID(9100, _maxSize6, device.capabilities.maxTextureSize);
              }
              var _glTexUnit6 = device.stateCache.glTexUnits[device.stateCache.texUnit];
              if (_glTexUnit6.glTexture !== gpuTexture.glTexture) {
                gl.bindTexture(gl.TEXTURE_CUBE_MAP, gpuTexture.glTexture);
                _glTexUnit6.glTexture = gpuTexture.glTexture;
              }
              if (FormatInfos[gpuTexture.format].isCompressed) {
                for (var f = 0; f < 6; ++f) {
                  w = gpuTexture.width;
                  h = gpuTexture.height;
                  for (var _i6 = 0; _i6 < gpuTexture.mipLevel; ++_i6) {
                    var _imgSize6 = FormatSize(gpuTexture.format, w, h, 1);
                    var _view6 = new Uint8Array(_imgSize6);
                    gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + f, _i6, gpuTexture.glInternalFmt, w, h, 0, _view6);
                    w = Math.max(1, w >> 1);
                    h = Math.max(1, h >> 1);
                  }
                }
              } else {
                WebGL2CmdFuncDestroyTexture(device, gpuTexture);
                WebGL2CmdFuncCreateTexture(device, gpuTexture);
              }
              break;
            }
          default:
            {
              error('Unsupported TextureType, create texture failed.');
              gpuTexture.type = TextureType.TEX2D;
              gpuTexture.glTarget = gl.TEXTURE_2D;
            }
        }
      }
      function WebGL2CmdFuncPrepareSamplerInfo(device, gpuSampler) {
        var gl = device.gl;
        if (gpuSampler.minFilter === Filter$1.LINEAR || gpuSampler.minFilter === Filter$1.ANISOTROPIC) {
          if (gpuSampler.mipFilter === Filter$1.LINEAR || gpuSampler.mipFilter === Filter$1.ANISOTROPIC) {
            gpuSampler.glMinFilter = gl.LINEAR_MIPMAP_LINEAR;
          } else if (gpuSampler.mipFilter === Filter$1.POINT) {
            gpuSampler.glMinFilter = gl.LINEAR_MIPMAP_NEAREST;
          } else {
            gpuSampler.glMinFilter = gl.LINEAR;
          }
        } else if (gpuSampler.mipFilter === Filter$1.LINEAR || gpuSampler.mipFilter === Filter$1.ANISOTROPIC) {
          gpuSampler.glMinFilter = gl.NEAREST_MIPMAP_LINEAR;
        } else if (gpuSampler.mipFilter === Filter$1.POINT) {
          gpuSampler.glMinFilter = gl.NEAREST_MIPMAP_NEAREST;
        } else {
          gpuSampler.glMinFilter = gl.NEAREST;
        }
        if (gpuSampler.magFilter === Filter$1.LINEAR || gpuSampler.magFilter === Filter$1.ANISOTROPIC) {
          gpuSampler.glMagFilter = gl.LINEAR;
        } else {
          gpuSampler.glMagFilter = gl.NEAREST;
        }
        gpuSampler.glWrapS = WebGLWraps[gpuSampler.addressU];
        gpuSampler.glWrapT = WebGLWraps[gpuSampler.addressV];
        gpuSampler.glWrapR = WebGLWraps[gpuSampler.addressW];
      }
      function WebGL2CmdFuncDestroySampler(device, gpuSampler) {
        var gl = device.gl;
        var it = gpuSampler.glSamplers.values();
        var res = it.next();
        while (!res.done) {
          gl.deleteSampler(res.value);
          var glSamplerUnits = device.stateCache.glSamplerUnits;
          for (var i = 0; i < glSamplerUnits.length; ++i) {
            if (glSamplerUnits[i] === res.value) {
              gl.bindSampler(i, null);
              glSamplerUnits[i] = null;
            }
          }
        }
        gpuSampler.glSamplers.clear();
      }
      function WebGL2CmdFuncCreateFramebuffer(device, gpuFramebuffer) {
        for (var i = 0; i < gpuFramebuffer.gpuColorViews.length; ++i) {
          var tex = gpuFramebuffer.gpuColorViews[i].gpuTexture;
          if (tex.isSwapchainTexture) {
            gpuFramebuffer.isOffscreen = false;
            return;
          }
        }
        var gl = device.gl;
        var attachments = [];
        var glFramebuffer = gl.createFramebuffer();
        if (glFramebuffer) {
          gpuFramebuffer.glFramebuffer = glFramebuffer;
          if (device.stateCache.glFramebuffer !== gpuFramebuffer.glFramebuffer) {
            gl.bindFramebuffer(gl.FRAMEBUFFER, gpuFramebuffer.glFramebuffer);
          }
          for (var _i7 = 0; _i7 < gpuFramebuffer.gpuColorViews.length; ++_i7) {
            var colorTextureView = gpuFramebuffer.gpuColorViews[_i7];
            var colorTexture = colorTextureView.gpuTexture;
            if (colorTexture) {
              if (colorTexture.glTexture) {
                gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + _i7, colorTexture.glTarget, colorTexture.glTexture, colorTextureView.baseLevel);
              } else {
                gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + _i7, gl.RENDERBUFFER, colorTexture.glRenderbuffer);
              }
              attachments.push(gl.COLOR_ATTACHMENT0 + _i7);
              gpuFramebuffer.width = Math.min(gpuFramebuffer.width, colorTexture.width >> colorTextureView.baseLevel);
              gpuFramebuffer.height = Math.min(gpuFramebuffer.height, colorTexture.height >> colorTextureView.baseLevel);
            }
          }
          var dstView = gpuFramebuffer.gpuDepthStencilView;
          if (dstView) {
            var dst = dstView.gpuTexture;
            var glAttachment = FormatInfos[dst.format].hasStencil ? gl.DEPTH_STENCIL_ATTACHMENT : gl.DEPTH_ATTACHMENT;
            if (dst.glTexture) {
              gl.framebufferTexture2D(gl.FRAMEBUFFER, glAttachment, dst.glTarget, dst.glTexture, gpuFramebuffer.gpuDepthStencilView.baseLevel);
            } else {
              gl.framebufferRenderbuffer(gl.FRAMEBUFFER, glAttachment, gl.RENDERBUFFER, dst.glRenderbuffer);
            }
            gpuFramebuffer.width = Math.min(gpuFramebuffer.width, dst.width >> dstView.baseLevel);
            gpuFramebuffer.height = Math.min(gpuFramebuffer.height, dst.height >> dstView.baseLevel);
          }
          gl.drawBuffers(attachments);
          var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
          if (status !== gl.FRAMEBUFFER_COMPLETE) {
            switch (status) {
              case gl.FRAMEBUFFER_INCOMPLETE_ATTACHMENT:
                {
                  error('glCheckFramebufferStatus() - FRAMEBUFFER_INCOMPLETE_ATTACHMENT');
                  break;
                }
              case gl.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:
                {
                  error('glCheckFramebufferStatus() - FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT');
                  break;
                }
              case gl.FRAMEBUFFER_INCOMPLETE_DIMENSIONS:
                {
                  error('glCheckFramebufferStatus() - FRAMEBUFFER_INCOMPLETE_DIMENSIONS');
                  break;
                }
              case gl.FRAMEBUFFER_UNSUPPORTED:
                {
                  error('glCheckFramebufferStatus() - FRAMEBUFFER_UNSUPPORTED');
                  break;
                }
            }
          }
          if (device.stateCache.glFramebuffer !== gpuFramebuffer.glFramebuffer) {
            gl.bindFramebuffer(gl.FRAMEBUFFER, device.stateCache.glFramebuffer);
          }
        }
      }
      function WebGL2CmdFuncDestroyFramebuffer(device, gpuFramebuffer) {
        if (gpuFramebuffer.glFramebuffer) {
          device.gl.deleteFramebuffer(gpuFramebuffer.glFramebuffer);
          if (device.stateCache.glFramebuffer === gpuFramebuffer.glFramebuffer) {
            device.gl.bindFramebuffer(device.gl.FRAMEBUFFER, null);
            device.stateCache.glFramebuffer = null;
          }
          gpuFramebuffer.glFramebuffer = null;
        }
      }
      function WebGL2CmdFuncCreateShader(device, gpuShader) {
        var gl = device.gl;
        var _loop = function _loop() {
            var gpuStage = gpuShader.gpuStages[k];
            var glShaderType = 0;
            var shaderTypeStr = '';
            var lineNumber = 1;
            switch (gpuStage.type) {
              case ShaderStageFlagBit.VERTEX:
                {
                  shaderTypeStr = 'VertexShader';
                  glShaderType = gl.VERTEX_SHADER;
                  break;
                }
              case ShaderStageFlagBit.FRAGMENT:
                {
                  shaderTypeStr = 'FragmentShader';
                  glShaderType = gl.FRAGMENT_SHADER;
                  break;
                }
              default:
                {
                  error('Unsupported ShaderType.');
                  return {
                    v: void 0
                  };
                }
            }
            var glShader = gl.createShader(glShaderType);
            if (glShader) {
              gpuStage.glShader = glShader;
              gl.shaderSource(gpuStage.glShader, "#version 300 es\n" + gpuStage.source);
              gl.compileShader(gpuStage.glShader);
              if (!gl.getShaderParameter(gpuStage.glShader, gl.COMPILE_STATUS)) {
                error(shaderTypeStr + " in '" + gpuShader.name + "' compilation failed.");
                error('Shader source dump:', gpuStage.source.replace(/^|\n/g, function () {
                  return "\n" + lineNumber++ + " ";
                }));
                error(gl.getShaderInfoLog(gpuStage.glShader));
                for (var l = 0; l < gpuShader.gpuStages.length; l++) {
                  var stage = gpuShader.gpuStages[k];
                  if (stage.glShader) {
                    gl.deleteShader(stage.glShader);
                    stage.glShader = null;
                  }
                }
                return {
                  v: void 0
                };
              }
            }
          },
          _ret;
        for (var k = 0; k < gpuShader.gpuStages.length; k++) {
          _ret = _loop();
          if (_ret) return _ret.v;
        }
        var glProgram = gl.createProgram();
        if (!glProgram) {
          return;
        }
        gpuShader.glProgram = glProgram;
        var enableEffectImport = !!(legacyCC.rendering && legacyCC.rendering.enableEffectImport);
        for (var _k = 0; _k < gpuShader.gpuStages.length; _k++) {
          var gpuStage = gpuShader.gpuStages[_k];
          gl.attachShader(gpuShader.glProgram, gpuStage.glShader);
        }
        gl.linkProgram(gpuShader.glProgram);
        for (var _k2 = 0; _k2 < gpuShader.gpuStages.length; _k2++) {
          var _gpuStage = gpuShader.gpuStages[_k2];
          if (_gpuStage.glShader) {
            gl.detachShader(gpuShader.glProgram, _gpuStage.glShader);
            gl.deleteShader(_gpuStage.glShader);
            _gpuStage.glShader = null;
          }
        }
        if (gl.getProgramParameter(gpuShader.glProgram, gl.LINK_STATUS)) {
          debug("Shader '" + gpuShader.name + "' compilation succeeded.");
        } else {
          error("Failed to link shader '" + gpuShader.name + "'.");
          error(gl.getProgramInfoLog(gpuShader.glProgram));
          return;
        }
        var activeAttribCount = gl.getProgramParameter(gpuShader.glProgram, gl.ACTIVE_ATTRIBUTES);
        gpuShader.glInputs = new Array(activeAttribCount);
        for (var i = 0; i < activeAttribCount; ++i) {
          var attribInfo = gl.getActiveAttrib(gpuShader.glProgram, i);
          if (attribInfo) {
            var varName = void 0;
            var nameOffset = attribInfo.name.indexOf('[');
            if (nameOffset !== -1) {
              varName = attribInfo.name.substr(0, nameOffset);
            } else {
              varName = attribInfo.name;
            }
            var glLoc = gl.getAttribLocation(gpuShader.glProgram, varName);
            var type = WebGLTypeToGFXType(attribInfo.type, gl);
            var stride = WebGLGetTypeSize(attribInfo.type, gl);
            gpuShader.glInputs[i] = {
              name: varName,
              type: type,
              stride: stride,
              count: attribInfo.size,
              size: stride * attribInfo.size,
              glType: attribInfo.type,
              glLoc: glLoc
            };
          }
        }
        var activeBlockCount = gl.getProgramParameter(gpuShader.glProgram, gl.ACTIVE_UNIFORM_BLOCKS);
        var blockName;
        var blockIdx;
        var blockSize;
        var block;
        if (activeBlockCount) {
          gpuShader.glBlocks = new Array(activeBlockCount);
          for (var b = 0; b < activeBlockCount; ++b) {
            blockName = gl.getActiveUniformBlockName(gpuShader.glProgram, b);
            var _nameOffset = blockName.indexOf('[');
            if (_nameOffset !== -1) {
              blockName = blockName.substr(0, _nameOffset);
            }
            block = null;
            for (var _k3 = 0; _k3 < gpuShader.blocks.length; _k3++) {
              if (gpuShader.blocks[_k3].name === blockName) {
                block = gpuShader.blocks[_k3];
                break;
              }
            }
            if (!block) {
              error("Block '" + blockName + "' does not bound");
            } else {
              blockIdx = b;
              blockSize = gl.getActiveUniformBlockParameter(gpuShader.glProgram, blockIdx, gl.UNIFORM_BLOCK_DATA_SIZE);
              var glBinding = enableEffectImport ? block.flattened : block.binding + (device.bindingMappings.blockOffsets[block.set] || 0);
              gl.uniformBlockBinding(gpuShader.glProgram, blockIdx, glBinding);
              gpuShader.glBlocks[b] = {
                set: block.set,
                binding: block.binding,
                idx: blockIdx,
                name: blockName,
                size: blockSize,
                glBinding: glBinding
              };
            }
          }
        }
        for (var _i8 = 0; _i8 < gpuShader.subpassInputs.length; ++_i8) {
          var subpassInput = gpuShader.subpassInputs[_i8];
          gpuShader.samplerTextures.push(new UniformSamplerTexture(subpassInput.set, subpassInput.binding, subpassInput.name, Type$1.SAMPLER2D, subpassInput.count));
        }
        if (gpuShader.samplerTextures.length > 0) {
          gpuShader.glSamplerTextures = new Array(gpuShader.samplerTextures.length);
          for (var _i9 = 0; _i9 < gpuShader.samplerTextures.length; ++_i9) {
            var sampler = gpuShader.samplerTextures[_i9];
            gpuShader.glSamplerTextures[_i9] = {
              set: sampler.set,
              binding: sampler.binding,
              name: sampler.name,
              type: sampler.type,
              count: sampler.count,
              units: [],
              glUnits: null,
              glType: GFXTypeToWebGLType(sampler.type, gl),
              glLoc: null
            };
          }
        }
        var glActiveSamplers = [];
        var glActiveSamplerLocations = [];
        var texUnitCacheMap = device.stateCache.texUnitCacheMap;
        if (!enableEffectImport) {
          var flexibleSetBaseOffset = 0;
          for (var _i10 = 0; _i10 < gpuShader.blocks.length; ++_i10) {
            if (gpuShader.blocks[_i10].set === device.bindingMappings.flexibleSet) {
              flexibleSetBaseOffset++;
            }
          }
          var arrayOffset = 0;
          for (var _i11 = 0; _i11 < gpuShader.samplerTextures.length; ++_i11) {
            var _sampler = gpuShader.samplerTextures[_i11];
            var _glLoc = gl.getUniformLocation(gpuShader.glProgram, _sampler.name);
            if (_glLoc && _glLoc.id !== -1) {
              glActiveSamplers.push(gpuShader.glSamplerTextures[_i11]);
              glActiveSamplerLocations.push(_glLoc);
            }
            if (texUnitCacheMap[_sampler.name] === undefined) {
              var binding = _sampler.binding + device.bindingMappings.samplerTextureOffsets[_sampler.set] + arrayOffset;
              if (_sampler.set === device.bindingMappings.flexibleSet) {
                binding -= flexibleSetBaseOffset;
              }
              texUnitCacheMap[_sampler.name] = binding % device.capabilities.maxTextureUnits;
              arrayOffset += _sampler.count - 1;
            }
          }
        } else {
          for (var _i12 = 0; _i12 < gpuShader.samplerTextures.length; ++_i12) {
            var _sampler2 = gpuShader.samplerTextures[_i12];
            var _glLoc2 = gl.getUniformLocation(gpuShader.glProgram, _sampler2.name);
            if (_glLoc2 && _glLoc2.id !== -1) {
              glActiveSamplers.push(gpuShader.glSamplerTextures[_i12]);
              glActiveSamplerLocations.push(_glLoc2);
            }
            if (texUnitCacheMap[_sampler2.name] === undefined) {
              texUnitCacheMap[_sampler2.name] = _sampler2.flattened % device.capabilities.maxTextureUnits;
            }
          }
        }
        if (glActiveSamplers.length) {
          var usedTexUnits = [];
          for (var _i13 = 0; _i13 < glActiveSamplers.length; ++_i13) {
            var glSampler = glActiveSamplers[_i13];
            var cachedUnit = texUnitCacheMap[glSampler.name];
            if (cachedUnit !== undefined) {
              glSampler.glLoc = glActiveSamplerLocations[_i13];
              for (var t = 0; t < glSampler.count; ++t) {
                while (usedTexUnits[cachedUnit]) {
                  cachedUnit = (cachedUnit + 1) % device.capabilities.maxTextureUnits;
                }
                glSampler.units.push(cachedUnit);
                usedTexUnits[cachedUnit] = true;
              }
            }
          }
          var unitIdx = 0;
          for (var _i14 = 0; _i14 < glActiveSamplers.length; ++_i14) {
            var _glSampler = glActiveSamplers[_i14];
            if (!_glSampler.glLoc) {
              _glSampler.glLoc = glActiveSamplerLocations[_i14];
              while (usedTexUnits[unitIdx]) {
                unitIdx++;
              }
              for (var _t = 0; _t < _glSampler.count; ++_t) {
                while (usedTexUnits[unitIdx]) {
                  unitIdx = (unitIdx + 1) % device.capabilities.maxTextureUnits;
                }
                if (texUnitCacheMap[_glSampler.name] === undefined) {
                  texUnitCacheMap[_glSampler.name] = unitIdx;
                }
                _glSampler.units.push(unitIdx);
                usedTexUnits[unitIdx] = true;
              }
            }
          }
          if (device.stateCache.glProgram !== gpuShader.glProgram) {
            gl.useProgram(gpuShader.glProgram);
          }
          for (var _k4 = 0; _k4 < glActiveSamplers.length; _k4++) {
            var _glSampler2 = glActiveSamplers[_k4];
            _glSampler2.glUnits = new Int32Array(_glSampler2.units);
            gl.uniform1iv(_glSampler2.glLoc, _glSampler2.glUnits);
          }
          if (device.stateCache.glProgram !== gpuShader.glProgram) {
            gl.useProgram(device.stateCache.glProgram);
          }
        }
        gpuShader.glSamplerTextures = glActiveSamplers;
      }
      function WebGL2CmdFuncDestroyShader(device, gpuShader) {
        if (gpuShader.glProgram) {
          device.gl.deleteProgram(gpuShader.glProgram);
          if (device.stateCache.glProgram === gpuShader.glProgram) {
            device.gl.useProgram(null);
            device.stateCache.glProgram = null;
          }
          gpuShader.glProgram = null;
        }
      }
      function WebGL2CmdFuncCreateInputAssember(device, gpuInputAssembler) {
        var gl = device.gl;
        gpuInputAssembler.glAttribs = new Array(gpuInputAssembler.attributes.length);
        var offsets = [0, 0, 0, 0, 0, 0, 0, 0];
        for (var i = 0; i < gpuInputAssembler.attributes.length; ++i) {
          var attrib = gpuInputAssembler.attributes[i];
          var stream = attrib.stream !== undefined ? attrib.stream : 0;
          var gpuBuffer = gpuInputAssembler.gpuVertexBuffers[stream];
          var glType = GFXFormatToWebGLType(attrib.format, gl);
          var size = FormatInfos[attrib.format].size;
          gpuInputAssembler.glAttribs[i] = {
            name: attrib.name,
            glBuffer: gpuBuffer.glBuffer,
            glType: glType,
            size: size,
            count: FormatInfos[attrib.format].count,
            stride: gpuBuffer.stride,
            componentCount: WebGLGetComponentCount(glType, gl),
            isNormalized: attrib.isNormalized !== undefined ? attrib.isNormalized : false,
            isInstanced: attrib.isInstanced !== undefined ? attrib.isInstanced : false,
            offset: offsets[stream]
          };
          offsets[stream] += size;
        }
      }
      function WebGL2CmdFuncDestroyInputAssembler(device, gpuInputAssembler) {
        var it = gpuInputAssembler.glVAOs.values();
        var res = it.next();
        var gl = device.gl;
        var glVAO = device.stateCache.glVAO;
        while (!res.done) {
          gl.deleteVertexArray(res.value);
          if (glVAO === res.value) {
            gl.bindVertexArray(null);
            glVAO = null;
          }
          res = it.next();
        }
        device.stateCache.glVAO = glVAO;
        gpuInputAssembler.glVAOs.clear();
      }
      var gfxStateCache = {
        gpuPipelineState: null,
        gpuInputAssembler: null,
        glPrimitive: 0,
        invalidateAttachments: []
      };
      function WebGL2CmdFuncBeginRenderPass(device, gpuRenderPass, gpuFramebuffer, renderArea, clearColors, clearDepth, clearStencil) {
        var gl = device.gl;
        var cache = device.stateCache;
        var clears = 0;
        if (gpuFramebuffer && gpuRenderPass) {
          if (cache.glFramebuffer !== gpuFramebuffer.glFramebuffer) {
            gl.bindFramebuffer(gl.FRAMEBUFFER, gpuFramebuffer.glFramebuffer);
            cache.glFramebuffer = gpuFramebuffer.glFramebuffer;
          }
          if (cache.viewport.left !== renderArea.x || cache.viewport.top !== renderArea.y || cache.viewport.width !== renderArea.width || cache.viewport.height !== renderArea.height) {
            gl.viewport(renderArea.x, renderArea.y, renderArea.width, renderArea.height);
            cache.viewport.left = renderArea.x;
            cache.viewport.top = renderArea.y;
            cache.viewport.width = renderArea.width;
            cache.viewport.height = renderArea.height;
          }
          if (cache.scissorRect.x !== renderArea.x || cache.scissorRect.y !== renderArea.y || cache.scissorRect.width !== renderArea.width || cache.scissorRect.height !== renderArea.height) {
            gl.scissor(renderArea.x, renderArea.y, renderArea.width, renderArea.height);
            cache.scissorRect.x = renderArea.x;
            cache.scissorRect.y = renderArea.y;
            cache.scissorRect.width = renderArea.width;
            cache.scissorRect.height = renderArea.height;
          }
          gfxStateCache.invalidateAttachments.length = 0;
          for (var j = 0; j < clearColors.length; ++j) {
            var colorAttachment = gpuRenderPass.colorAttachments[j];
            if (colorAttachment.format !== Format.UNKNOWN) {
              switch (colorAttachment.loadOp) {
                case LoadOp.LOAD:
                  break;
                case LoadOp.CLEAR:
                  {
                    if (cache.bs.targets[0].blendColorMask !== ColorMask.ALL) {
                      gl.colorMask(true, true, true, true);
                    }
                    if (gpuRenderPass.colorAttachments.length === 1) {
                      var clearColor = clearColors[0];
                      gl.clearColor(clearColor.x, clearColor.y, clearColor.z, clearColor.w);
                      clears |= gl.COLOR_BUFFER_BIT;
                    } else {
                      _f32v4[0] = clearColors[j].x;
                      _f32v4[1] = clearColors[j].y;
                      _f32v4[2] = clearColors[j].z;
                      _f32v4[3] = clearColors[j].w;
                      gl.clearBufferfv(gl.COLOR, j, _f32v4);
                    }
                    break;
                  }
                case LoadOp.DISCARD:
                  {
                    gfxStateCache.invalidateAttachments.push(gl.COLOR_ATTACHMENT0 + j);
                    break;
                  }
              }
            }
          }
          if (gpuRenderPass.depthStencilAttachment) {
            if (gpuRenderPass.depthStencilAttachment.format !== Format.UNKNOWN) {
              switch (gpuRenderPass.depthStencilAttachment.depthLoadOp) {
                case LoadOp.LOAD:
                  break;
                case LoadOp.CLEAR:
                  {
                    if (!cache.dss.depthWrite) {
                      gl.depthMask(true);
                    }
                    gl.clearDepth(clearDepth);
                    clears |= gl.DEPTH_BUFFER_BIT;
                    break;
                  }
                case LoadOp.DISCARD:
                  {
                    gfxStateCache.invalidateAttachments.push(gl.DEPTH_ATTACHMENT);
                    break;
                  }
              }
              if (FormatInfos[gpuRenderPass.depthStencilAttachment.format].hasStencil) {
                switch (gpuRenderPass.depthStencilAttachment.stencilLoadOp) {
                  case LoadOp.LOAD:
                    break;
                  case LoadOp.CLEAR:
                    {
                      if (!cache.dss.stencilWriteMaskFront) {
                        gl.stencilMaskSeparate(gl.FRONT, 0xffff);
                      }
                      if (!cache.dss.stencilWriteMaskBack) {
                        gl.stencilMaskSeparate(gl.BACK, 0xffff);
                      }
                      gl.clearStencil(clearStencil);
                      clears |= gl.STENCIL_BUFFER_BIT;
                      break;
                    }
                  case LoadOp.DISCARD:
                    {
                      gfxStateCache.invalidateAttachments.push(gl.STENCIL_ATTACHMENT);
                      break;
                    }
                }
              }
            }
          }
          if (gpuFramebuffer.glFramebuffer && gfxStateCache.invalidateAttachments.length) {
            gl.invalidateFramebuffer(gl.FRAMEBUFFER, gfxStateCache.invalidateAttachments);
          }
          if (clears) {
            gl.clear(clears);
          }
          if (clears & gl.COLOR_BUFFER_BIT) {
            var colorMask = cache.bs.targets[0].blendColorMask;
            if (colorMask !== ColorMask.ALL) {
              var r = (colorMask & ColorMask.R) !== ColorMask.NONE;
              var g = (colorMask & ColorMask.G) !== ColorMask.NONE;
              var b = (colorMask & ColorMask.B) !== ColorMask.NONE;
              var a = (colorMask & ColorMask.A) !== ColorMask.NONE;
              gl.colorMask(r, g, b, a);
            }
          }
          if (clears & gl.DEPTH_BUFFER_BIT && !cache.dss.depthWrite) {
            gl.depthMask(false);
          }
          if (clears & gl.STENCIL_BUFFER_BIT) {
            if (!cache.dss.stencilWriteMaskFront) {
              gl.stencilMaskSeparate(gl.FRONT, 0);
            }
            if (!cache.dss.stencilWriteMaskBack) {
              gl.stencilMaskSeparate(gl.BACK, 0);
            }
          }
        }
      }
      function WebGL2CmdFuncBindStates(device, gpuPipelineState, gpuInputAssembler, gpuDescriptorSets, dynamicOffsets, dynamicStates) {
        var gl = device.gl;
        var cache = device.stateCache;
        var gpuShader = gpuPipelineState && gpuPipelineState.gpuShader;
        var isShaderChanged = false;
        if (gpuPipelineState && gfxStateCache.gpuPipelineState !== gpuPipelineState) {
          gfxStateCache.gpuPipelineState = gpuPipelineState;
          gfxStateCache.glPrimitive = gpuPipelineState.glPrimitive;
          if (gpuShader) {
            var glProgram = gpuShader.glProgram;
            if (cache.glProgram !== glProgram) {
              gl.useProgram(glProgram);
              cache.glProgram = glProgram;
              isShaderChanged = true;
            }
          }
          var rs = gpuPipelineState.rs;
          if (rs) {
            if (cache.rs.cullMode !== rs.cullMode) {
              switch (rs.cullMode) {
                case CullMode.NONE:
                  {
                    gl.disable(gl.CULL_FACE);
                    break;
                  }
                case CullMode.FRONT:
                  {
                    gl.enable(gl.CULL_FACE);
                    gl.cullFace(gl.FRONT);
                    break;
                  }
                case CullMode.BACK:
                  {
                    gl.enable(gl.CULL_FACE);
                    gl.cullFace(gl.BACK);
                    break;
                  }
              }
              device.stateCache.rs.cullMode = rs.cullMode;
            }
            var isFrontFaceCCW = rs.isFrontFaceCCW;
            if (device.stateCache.rs.isFrontFaceCCW !== isFrontFaceCCW) {
              gl.frontFace(isFrontFaceCCW ? gl.CCW : gl.CW);
              device.stateCache.rs.isFrontFaceCCW = isFrontFaceCCW;
            }
            if (device.stateCache.rs.depthBias !== rs.depthBias || device.stateCache.rs.depthBiasSlop !== rs.depthBiasSlop) {
              gl.polygonOffset(rs.depthBias, rs.depthBiasSlop);
              device.stateCache.rs.depthBias = rs.depthBias;
              device.stateCache.rs.depthBiasSlop = rs.depthBiasSlop;
            }
            if (device.stateCache.rs.lineWidth !== rs.lineWidth) {
              gl.lineWidth(rs.lineWidth);
              device.stateCache.rs.lineWidth = rs.lineWidth;
            }
          }
          var dss = gpuPipelineState.dss;
          if (dss) {
            if (cache.dss.depthTest !== dss.depthTest) {
              if (dss.depthTest) {
                gl.enable(gl.DEPTH_TEST);
              } else {
                gl.disable(gl.DEPTH_TEST);
              }
              cache.dss.depthTest = dss.depthTest;
            }
            if (cache.dss.depthWrite !== dss.depthWrite) {
              gl.depthMask(dss.depthWrite);
              cache.dss.depthWrite = dss.depthWrite;
            }
            if (cache.dss.depthFunc !== dss.depthFunc) {
              gl.depthFunc(WebGLCmpFuncs[dss.depthFunc]);
              cache.dss.depthFunc = dss.depthFunc;
            }
            if (cache.dss.stencilTestFront !== dss.stencilTestFront || cache.dss.stencilTestBack !== dss.stencilTestBack) {
              if (dss.stencilTestFront || dss.stencilTestBack) {
                gl.enable(gl.STENCIL_TEST);
              } else {
                gl.disable(gl.STENCIL_TEST);
              }
              cache.dss.stencilTestFront = dss.stencilTestFront;
              cache.dss.stencilTestBack = dss.stencilTestBack;
            }
            if (cache.dss.stencilFuncFront !== dss.stencilFuncFront || cache.dss.stencilRefFront !== dss.stencilRefFront || cache.dss.stencilReadMaskFront !== dss.stencilReadMaskFront) {
              gl.stencilFuncSeparate(gl.FRONT, WebGLCmpFuncs[dss.stencilFuncFront], dss.stencilRefFront, dss.stencilReadMaskFront);
              cache.dss.stencilFuncFront = dss.stencilFuncFront;
              cache.dss.stencilRefFront = dss.stencilRefFront;
              cache.dss.stencilReadMaskFront = dss.stencilReadMaskFront;
            }
            if (cache.dss.stencilFailOpFront !== dss.stencilFailOpFront || cache.dss.stencilZFailOpFront !== dss.stencilZFailOpFront || cache.dss.stencilPassOpFront !== dss.stencilPassOpFront) {
              gl.stencilOpSeparate(gl.FRONT, WebGLStencilOps[dss.stencilFailOpFront], WebGLStencilOps[dss.stencilZFailOpFront], WebGLStencilOps[dss.stencilPassOpFront]);
              cache.dss.stencilFailOpFront = dss.stencilFailOpFront;
              cache.dss.stencilZFailOpFront = dss.stencilZFailOpFront;
              cache.dss.stencilPassOpFront = dss.stencilPassOpFront;
            }
            if (cache.dss.stencilWriteMaskFront !== dss.stencilWriteMaskFront) {
              gl.stencilMaskSeparate(gl.FRONT, dss.stencilWriteMaskFront);
              cache.dss.stencilWriteMaskFront = dss.stencilWriteMaskFront;
            }
            if (cache.dss.stencilFuncBack !== dss.stencilFuncBack || cache.dss.stencilRefBack !== dss.stencilRefBack || cache.dss.stencilReadMaskBack !== dss.stencilReadMaskBack) {
              gl.stencilFuncSeparate(gl.BACK, WebGLCmpFuncs[dss.stencilFuncBack], dss.stencilRefBack, dss.stencilReadMaskBack);
              cache.dss.stencilFuncBack = dss.stencilFuncBack;
              cache.dss.stencilRefBack = dss.stencilRefBack;
              cache.dss.stencilReadMaskBack = dss.stencilReadMaskBack;
            }
            if (cache.dss.stencilFailOpBack !== dss.stencilFailOpBack || cache.dss.stencilZFailOpBack !== dss.stencilZFailOpBack || cache.dss.stencilPassOpBack !== dss.stencilPassOpBack) {
              gl.stencilOpSeparate(gl.BACK, WebGLStencilOps[dss.stencilFailOpBack], WebGLStencilOps[dss.stencilZFailOpBack], WebGLStencilOps[dss.stencilPassOpBack]);
              cache.dss.stencilFailOpBack = dss.stencilFailOpBack;
              cache.dss.stencilZFailOpBack = dss.stencilZFailOpBack;
              cache.dss.stencilPassOpBack = dss.stencilPassOpBack;
            }
            if (cache.dss.stencilWriteMaskBack !== dss.stencilWriteMaskBack) {
              gl.stencilMaskSeparate(gl.BACK, dss.stencilWriteMaskBack);
              cache.dss.stencilWriteMaskBack = dss.stencilWriteMaskBack;
            }
          }
          var bs = gpuPipelineState.bs;
          if (bs) {
            if (cache.bs.isA2C !== bs.isA2C) {
              if (bs.isA2C) {
                gl.enable(gl.SAMPLE_ALPHA_TO_COVERAGE);
              } else {
                gl.disable(gl.SAMPLE_ALPHA_TO_COVERAGE);
              }
              cache.bs.isA2C = bs.isA2C;
            }
            if (cache.bs.blendColor.x !== bs.blendColor.x || cache.bs.blendColor.y !== bs.blendColor.y || cache.bs.blendColor.z !== bs.blendColor.z || cache.bs.blendColor.w !== bs.blendColor.w) {
              gl.blendColor(bs.blendColor.x, bs.blendColor.y, bs.blendColor.z, bs.blendColor.w);
              cache.bs.blendColor.x = bs.blendColor.x;
              cache.bs.blendColor.y = bs.blendColor.y;
              cache.bs.blendColor.z = bs.blendColor.z;
              cache.bs.blendColor.w = bs.blendColor.w;
            }
            var target0 = bs.targets[0];
            var target0Cache = cache.bs.targets[0];
            if (target0Cache.blend !== target0.blend) {
              if (target0.blend) {
                gl.enable(gl.BLEND);
              } else {
                gl.disable(gl.BLEND);
              }
              target0Cache.blend = target0.blend;
            }
            if (target0Cache.blendEq !== target0.blendEq || target0Cache.blendAlphaEq !== target0.blendAlphaEq) {
              gl.blendEquationSeparate(WebGLBlendOps[target0.blendEq], WebGLBlendOps[target0.blendAlphaEq]);
              target0Cache.blendEq = target0.blendEq;
              target0Cache.blendAlphaEq = target0.blendAlphaEq;
            }
            if (target0Cache.blendSrc !== target0.blendSrc || target0Cache.blendDst !== target0.blendDst || target0Cache.blendSrcAlpha !== target0.blendSrcAlpha || target0Cache.blendDstAlpha !== target0.blendDstAlpha) {
              gl.blendFuncSeparate(WebGLBlendFactors[target0.blendSrc], WebGLBlendFactors[target0.blendDst], WebGLBlendFactors[target0.blendSrcAlpha], WebGLBlendFactors[target0.blendDstAlpha]);
              target0Cache.blendSrc = target0.blendSrc;
              target0Cache.blendDst = target0.blendDst;
              target0Cache.blendSrcAlpha = target0.blendSrcAlpha;
              target0Cache.blendDstAlpha = target0.blendDstAlpha;
            }
            if (target0Cache.blendColorMask !== target0.blendColorMask) {
              gl.colorMask((target0.blendColorMask & ColorMask.R) !== ColorMask.NONE, (target0.blendColorMask & ColorMask.G) !== ColorMask.NONE, (target0.blendColorMask & ColorMask.B) !== ColorMask.NONE, (target0.blendColorMask & ColorMask.A) !== ColorMask.NONE);
              target0Cache.blendColorMask = target0.blendColorMask;
            }
          }
        }
        if (gpuPipelineState && gpuPipelineState.gpuPipelineLayout && gpuShader) {
          var blockLen = gpuShader.glBlocks.length;
          var dynamicOffsetIndices = gpuPipelineState.gpuPipelineLayout.dynamicOffsetIndices;
          for (var j = 0; j < blockLen; j++) {
            var glBlock = gpuShader.glBlocks[j];
            var gpuDescriptorSet = gpuDescriptorSets[glBlock.set];
            var descriptorIndex = gpuDescriptorSet && gpuDescriptorSet.descriptorIndices[glBlock.binding];
            var gpuDescriptor = descriptorIndex >= 0 && gpuDescriptorSet.gpuDescriptors[descriptorIndex];
            if (!gpuDescriptor || !gpuDescriptor.gpuBuffer) {
              continue;
            }
            var dynamicOffsetIndexSet = dynamicOffsetIndices[glBlock.set];
            var dynamicOffsetIndex = dynamicOffsetIndexSet && dynamicOffsetIndexSet[glBlock.binding];
            var offset = gpuDescriptor.gpuBuffer.glOffset;
            if (dynamicOffsetIndex >= 0) {
              offset += dynamicOffsets[dynamicOffsetIndex];
            }
            if (cache.glBindUBOs[glBlock.glBinding] !== gpuDescriptor.gpuBuffer.glBuffer || cache.glBindUBOOffsets[glBlock.glBinding] !== offset) {
              if (offset) {
                gl.bindBufferRange(gl.UNIFORM_BUFFER, glBlock.glBinding, gpuDescriptor.gpuBuffer.glBuffer, offset, gpuDescriptor.gpuBuffer.size);
              } else {
                gl.bindBufferBase(gl.UNIFORM_BUFFER, glBlock.glBinding, gpuDescriptor.gpuBuffer.glBuffer);
              }
              cache.glUniformBuffer = cache.glBindUBOs[glBlock.glBinding] = gpuDescriptor.gpuBuffer.glBuffer;
              cache.glBindUBOOffsets[glBlock.glBinding] = offset;
            }
          }
          var samplerLen = gpuShader.glSamplerTextures.length;
          for (var i = 0; i < samplerLen; i++) {
            var glSampler = gpuShader.glSamplerTextures[i];
            var _gpuDescriptorSet = gpuDescriptorSets[glSampler.set];
            var _descriptorIndex = _gpuDescriptorSet && _gpuDescriptorSet.descriptorIndices[glSampler.binding];
            var _gpuDescriptor = _descriptorIndex >= 0 && _gpuDescriptorSet.gpuDescriptors[_descriptorIndex];
            for (var l = 0; l < glSampler.units.length; l++) {
              var texUnit = glSampler.units[l];
              var glTexUnit = cache.glTexUnits[texUnit];
              if (!_gpuDescriptor || !_gpuDescriptor.gpuTextureView || !_gpuDescriptor.gpuTextureView.gpuTexture || !_gpuDescriptor.gpuSampler) {
                continue;
              }
              var gpuTextureView = _gpuDescriptor.gpuTextureView;
              var gpuTexture = gpuTextureView.gpuTexture;
              var minLod = gpuTextureView.baseLevel;
              var maxLod = minLod + gpuTextureView.levelCount;
              if (gpuTexture.size > 0) {
                if (glTexUnit.glTexture !== gpuTexture.glTexture) {
                  if (cache.texUnit !== texUnit) {
                    gl.activeTexture(gl.TEXTURE0 + texUnit);
                    cache.texUnit = texUnit;
                  }
                  if (gpuTexture.glTexture) {
                    gl.bindTexture(gpuTexture.glTarget, gpuTexture.glTexture);
                  } else {
                    gl.bindTexture(gpuTexture.glTarget, device.nullTex2D.gpuTexture.glTexture);
                  }
                  glTexUnit.glTexture = gpuTexture.glTexture;
                }
                var _gpuDescriptor2 = _gpuDescriptor,
                  gpuSampler = _gpuDescriptor2.gpuSampler;
                var _glSampler3 = gpuSampler.getGLSampler(device, minLod, maxLod);
                if (cache.glSamplerUnits[texUnit] !== _glSampler3) {
                  gl.bindSampler(texUnit, _glSampler3);
                  cache.glSamplerUnits[texUnit] = _glSampler3;
                }
              }
              _gpuDescriptor = _gpuDescriptorSet.gpuDescriptors[++_descriptorIndex];
            }
          }
        }
        if (gpuInputAssembler && gpuShader && (isShaderChanged || gfxStateCache.gpuInputAssembler !== gpuInputAssembler)) {
          gfxStateCache.gpuInputAssembler = gpuInputAssembler;
          if (device.extensions.useVAO) {
            var glVAO = gpuInputAssembler.glVAOs.get(gpuShader.glProgram);
            if (!glVAO) {
              glVAO = gl.createVertexArray();
              gpuInputAssembler.glVAOs.set(gpuShader.glProgram, glVAO);
              gl.bindVertexArray(glVAO);
              gl.bindBuffer(gl.ARRAY_BUFFER, null);
              gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, null);
              cache.glArrayBuffer = null;
              cache.glElementArrayBuffer = null;
              var glAttrib;
              for (var _j = 0; _j < gpuShader.glInputs.length; _j++) {
                var glInput = gpuShader.glInputs[_j];
                glAttrib = null;
                for (var k = 0; k < gpuInputAssembler.glAttribs.length; k++) {
                  var attrib = gpuInputAssembler.glAttribs[k];
                  if (attrib.name === glInput.name) {
                    glAttrib = attrib;
                    break;
                  }
                }
                if (glAttrib) {
                  if (cache.glArrayBuffer !== glAttrib.glBuffer) {
                    gl.bindBuffer(gl.ARRAY_BUFFER, glAttrib.glBuffer);
                    cache.glArrayBuffer = glAttrib.glBuffer;
                  }
                  for (var c = 0; c < glAttrib.componentCount; ++c) {
                    var glLoc = glInput.glLoc + c;
                    var attribOffset = glAttrib.offset + glAttrib.size * c;
                    gl.enableVertexAttribArray(glLoc);
                    cache.glCurrentAttribLocs[glLoc] = true;
                    gl.vertexAttribPointer(glLoc, glAttrib.count, glAttrib.glType, glAttrib.isNormalized, glAttrib.stride, attribOffset);
                    gl.vertexAttribDivisor(glLoc, glAttrib.isInstanced ? 1 : 0);
                  }
                }
              }
              var gpuBuffer = gpuInputAssembler.gpuIndexBuffer;
              if (gpuBuffer) {
                gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, gpuBuffer.glBuffer);
              }
              gl.bindVertexArray(null);
              gl.bindBuffer(gl.ARRAY_BUFFER, null);
              gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, null);
              cache.glArrayBuffer = null;
              cache.glElementArrayBuffer = null;
            }
            if (cache.glVAO !== glVAO) {
              gl.bindVertexArray(glVAO);
              cache.glVAO = glVAO;
            }
          } else {
            for (var a = 0; a < device.capabilities.maxVertexAttributes; ++a) {
              cache.glCurrentAttribLocs[a] = false;
            }
            for (var _j2 = 0; _j2 < gpuShader.glInputs.length; _j2++) {
              var _glInput = gpuShader.glInputs[_j2];
              var _glAttrib = null;
              for (var _k5 = 0; _k5 < gpuInputAssembler.glAttribs.length; _k5++) {
                var _attrib = gpuInputAssembler.glAttribs[_k5];
                if (_attrib.name === _glInput.name) {
                  _glAttrib = _attrib;
                  break;
                }
              }
              if (_glAttrib) {
                if (cache.glArrayBuffer !== _glAttrib.glBuffer) {
                  gl.bindBuffer(gl.ARRAY_BUFFER, _glAttrib.glBuffer);
                  cache.glArrayBuffer = _glAttrib.glBuffer;
                }
                for (var _c = 0; _c < _glAttrib.componentCount; ++_c) {
                  var _glLoc3 = _glInput.glLoc + _c;
                  var _attribOffset = _glAttrib.offset + _glAttrib.size * _c;
                  if (!cache.glEnabledAttribLocs[_glLoc3] && _glLoc3 >= 0) {
                    gl.enableVertexAttribArray(_glLoc3);
                    cache.glEnabledAttribLocs[_glLoc3] = true;
                  }
                  cache.glCurrentAttribLocs[_glLoc3] = true;
                  gl.vertexAttribPointer(_glLoc3, _glAttrib.count, _glAttrib.glType, _glAttrib.isNormalized, _glAttrib.stride, _attribOffset);
                  gl.vertexAttribDivisor(_glLoc3, _glAttrib.isInstanced ? 1 : 0);
                }
              }
            }
            var _gpuBuffer = gpuInputAssembler.gpuIndexBuffer;
            if (_gpuBuffer) {
              if (cache.glElementArrayBuffer !== _gpuBuffer.glBuffer) {
                gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, _gpuBuffer.glBuffer);
                cache.glElementArrayBuffer = _gpuBuffer.glBuffer;
              }
            }
            for (var _a = 0; _a < device.capabilities.maxVertexAttributes; ++_a) {
              if (cache.glEnabledAttribLocs[_a] !== cache.glCurrentAttribLocs[_a]) {
                gl.disableVertexAttribArray(_a);
                cache.glEnabledAttribLocs[_a] = false;
              }
            }
          }
        }
        if (gpuPipelineState && gpuPipelineState.dynamicStates.length) {
          var dsLen = gpuPipelineState.dynamicStates.length;
          for (var _k6 = 0; _k6 < dsLen; _k6++) {
            var dynamicState = gpuPipelineState.dynamicStates[_k6];
            switch (dynamicState) {
              case DynamicStateFlagBit.LINE_WIDTH:
                {
                  if (cache.rs.lineWidth !== dynamicStates.lineWidth) {
                    gl.lineWidth(dynamicStates.lineWidth);
                    cache.rs.lineWidth = dynamicStates.lineWidth;
                  }
                  break;
                }
              case DynamicStateFlagBit.DEPTH_BIAS:
                {
                  if (cache.rs.depthBias !== dynamicStates.depthBiasConstant || cache.rs.depthBiasSlop !== dynamicStates.depthBiasSlope) {
                    gl.polygonOffset(dynamicStates.depthBiasConstant, dynamicStates.depthBiasSlope);
                    cache.rs.depthBias = dynamicStates.depthBiasConstant;
                    cache.rs.depthBiasSlop = dynamicStates.depthBiasSlope;
                  }
                  break;
                }
              case DynamicStateFlagBit.BLEND_CONSTANTS:
                {
                  var blendConstant = dynamicStates.blendConstant;
                  if (cache.bs.blendColor.x !== blendConstant.x || cache.bs.blendColor.y !== blendConstant.y || cache.bs.blendColor.z !== blendConstant.z || cache.bs.blendColor.w !== blendConstant.w) {
                    gl.blendColor(blendConstant.x, blendConstant.y, blendConstant.z, blendConstant.w);
                    cache.bs.blendColor.copy(blendConstant);
                  }
                  break;
                }
              case DynamicStateFlagBit.STENCIL_WRITE_MASK:
                {
                  var front = dynamicStates.stencilStatesFront;
                  var back = dynamicStates.stencilStatesBack;
                  if (cache.dss.stencilWriteMaskFront !== front.writeMask) {
                    gl.stencilMaskSeparate(gl.FRONT, front.writeMask);
                    cache.dss.stencilWriteMaskFront = front.writeMask;
                  }
                  if (cache.dss.stencilWriteMaskBack !== back.writeMask) {
                    gl.stencilMaskSeparate(gl.BACK, back.writeMask);
                    cache.dss.stencilWriteMaskBack = back.writeMask;
                  }
                  break;
                }
              case DynamicStateFlagBit.STENCIL_COMPARE_MASK:
                {
                  var _front = dynamicStates.stencilStatesFront;
                  var _back = dynamicStates.stencilStatesBack;
                  if (cache.dss.stencilRefFront !== _front.reference || cache.dss.stencilReadMaskFront !== _front.compareMask) {
                    gl.stencilFuncSeparate(gl.FRONT, WebGLCmpFuncs[cache.dss.stencilFuncFront], _front.reference, _front.compareMask);
                    cache.dss.stencilRefFront = _front.reference;
                    cache.dss.stencilReadMaskFront = _front.compareMask;
                  }
                  if (cache.dss.stencilRefBack !== _back.reference || cache.dss.stencilReadMaskBack !== _back.compareMask) {
                    gl.stencilFuncSeparate(gl.BACK, WebGLCmpFuncs[cache.dss.stencilFuncBack], _back.reference, _back.compareMask);
                    cache.dss.stencilRefBack = _back.reference;
                    cache.dss.stencilReadMaskBack = _back.compareMask;
                  }
                  break;
                }
            }
          }
        }
      }
      function WebGL2CmdFuncDraw(device, drawInfo) {
        var gl = device.gl;
        var gpuInputAssembler = gfxStateCache.gpuInputAssembler,
          glPrimitive = gfxStateCache.glPrimitive;
        var md = device.extensions.WEBGL_multi_draw;
        if (gpuInputAssembler) {
          var indexBuffer = gpuInputAssembler.gpuIndexBuffer;
          if (gpuInputAssembler.gpuIndirectBuffer) {
            var indirects = gpuInputAssembler.gpuIndirectBuffer.indirects;
            if (indirects.drawByIndex) {
              for (var j = 0; j < indirects.drawCount; j++) {
                indirects.byteOffsets[j] = indirects.offsets[j] * indexBuffer.stride;
              }
              if (md) {
                if (indirects.instancedDraw) {
                  md.multiDrawElementsInstancedWEBGL(glPrimitive, indirects.counts, 0, gpuInputAssembler.glIndexType, indirects.byteOffsets, 0, indirects.instances, 0, indirects.drawCount);
                } else {
                  md.multiDrawElementsWEBGL(glPrimitive, indirects.counts, 0, gpuInputAssembler.glIndexType, indirects.byteOffsets, 0, indirects.drawCount);
                }
              } else {
                for (var _j3 = 0; _j3 < indirects.drawCount; _j3++) {
                  if (indirects.instances[_j3]) {
                    gl.drawElementsInstanced(glPrimitive, indirects.counts[_j3], gpuInputAssembler.glIndexType, indirects.byteOffsets[_j3], indirects.instances[_j3]);
                  } else {
                    gl.drawElements(glPrimitive, indirects.counts[_j3], gpuInputAssembler.glIndexType, indirects.byteOffsets[_j3]);
                  }
                }
              }
            } else if (md) {
              if (indirects.instancedDraw) {
                md.multiDrawArraysInstancedWEBGL(glPrimitive, indirects.offsets, 0, indirects.counts, 0, indirects.instances, 0, indirects.drawCount);
              } else {
                md.multiDrawArraysWEBGL(glPrimitive, indirects.offsets, 0, indirects.counts, 0, indirects.drawCount);
              }
            } else {
              for (var _j4 = 0; _j4 < indirects.drawCount; _j4++) {
                if (indirects.instances[_j4]) {
                  gl.drawArraysInstanced(glPrimitive, indirects.offsets[_j4], indirects.counts[_j4], indirects.instances[_j4]);
                } else {
                  gl.drawArrays(glPrimitive, indirects.offsets[_j4], indirects.counts[_j4]);
                }
              }
            }
          } else if (drawInfo.instanceCount) {
            if (indexBuffer) {
              if (drawInfo.indexCount > 0) {
                var offset = drawInfo.firstIndex * indexBuffer.stride;
                gl.drawElementsInstanced(glPrimitive, drawInfo.indexCount, gpuInputAssembler.glIndexType, offset, drawInfo.instanceCount);
              }
            } else if (drawInfo.vertexCount > 0) {
              gl.drawArraysInstanced(glPrimitive, drawInfo.firstVertex, drawInfo.vertexCount, drawInfo.instanceCount);
            }
          } else if (indexBuffer) {
            if (drawInfo.indexCount > 0) {
              var _offset = drawInfo.firstIndex * indexBuffer.stride;
              gl.drawElements(glPrimitive, drawInfo.indexCount, gpuInputAssembler.glIndexType, _offset);
            }
          } else if (drawInfo.vertexCount > 0) {
            gl.drawArrays(glPrimitive, drawInfo.firstVertex, drawInfo.vertexCount);
          }
        }
      }
      var cmdIds = new Array(WebGL2Cmd.COUNT);
      function WebGL2CmdFuncExecuteCmds(device, cmdPackage) {
        cmdIds.fill(0);
        for (var i = 0; i < cmdPackage.cmds.length; ++i) {
          var cmd = cmdPackage.cmds.array[i];
          var cmdId = cmdIds[cmd]++;
          switch (cmd) {
            case WebGL2Cmd.BEGIN_RENDER_PASS:
              {
                var cmd0 = cmdPackage.beginRenderPassCmds.array[cmdId];
                WebGL2CmdFuncBeginRenderPass(device, cmd0.gpuRenderPass, cmd0.gpuFramebuffer, cmd0.renderArea, cmd0.clearColors, cmd0.clearDepth, cmd0.clearStencil);
                break;
              }
            case WebGL2Cmd.BIND_STATES:
              {
                var cmd2 = cmdPackage.bindStatesCmds.array[cmdId];
                WebGL2CmdFuncBindStates(device, cmd2.gpuPipelineState, cmd2.gpuInputAssembler, cmd2.gpuDescriptorSets, cmd2.dynamicOffsets, cmd2.dynamicStates);
                break;
              }
            case WebGL2Cmd.DRAW:
              {
                var cmd3 = cmdPackage.drawCmds.array[cmdId];
                WebGL2CmdFuncDraw(device, cmd3.drawInfo);
                break;
              }
            case WebGL2Cmd.UPDATE_BUFFER:
              {
                var cmd4 = cmdPackage.updateBufferCmds.array[cmdId];
                WebGL2CmdFuncUpdateBuffer(device, cmd4.gpuBuffer, cmd4.buffer, cmd4.offset, cmd4.size);
                break;
              }
            case WebGL2Cmd.COPY_BUFFER_TO_TEXTURE:
              {
                var cmd5 = cmdPackage.copyBufferToTextureCmds.array[cmdId];
                WebGL2CmdFuncCopyBuffersToTexture(device, cmd5.buffers, cmd5.gpuTexture, cmd5.regions);
                break;
              }
            case WebGL2Cmd.BLIT_TEXTURE:
              {
                var cmd6 = cmdPackage.blitTextureCmds.array[cmdId];
                WebGL2CmdFuncBlitTexture(device, cmd6.srcTexture, cmd6.dstTexture, cmd6.regions, cmd6.filter);
                break;
              }
          }
        }
      }
      function toUseTexImage2D(texImages, regions) {
        if (texImages.length > 1 || regions.length > 1) return false;
        var isVideoElement = texImages[0] instanceof HTMLVideoElement;
        if (isVideoElement) {
          var videoElement = texImages[0];
          var isSameSize = regions[0].texOffset.x === 0 && regions[0].texOffset.y === 0 && regions[0].texExtent.width === videoElement.videoWidth && regions[0].texExtent.height === videoElement.videoHeight;
          return isSameSize;
        }
        return false;
      }
      function WebGL2CmdFuncCopyTexImagesToTexture(device, texImages, gpuTexture, regions) {
        var gl = device.gl;
        var glTexUnit = device.stateCache.glTexUnits[device.stateCache.texUnit];
        if (glTexUnit.glTexture !== gpuTexture.glTexture) {
          gl.bindTexture(gpuTexture.glTarget, gpuTexture.glTexture);
          glTexUnit.glTexture = gpuTexture.glTexture;
        }
        var n = 0;
        var f = 0;
        switch (gpuTexture.glTarget) {
          case gl.TEXTURE_2D:
            {
              if (toUseTexImage2D(texImages, regions)) {
                gl.texImage2D(gl.TEXTURE_2D, regions[0].texSubres.mipLevel, gpuTexture.glInternalFmt, regions[0].texExtent.width, regions[0].texExtent.height, 0, gpuTexture.glFormat, gpuTexture.glType, texImages[0]);
              } else {
                for (var k = 0; k < regions.length; k++) {
                  var region = regions[k];
                  gl.texSubImage2D(gl.TEXTURE_2D, region.texSubres.mipLevel, region.texOffset.x, region.texOffset.y, gpuTexture.glFormat, gpuTexture.glType, texImages[n++]);
                }
              }
              break;
            }
          case gl.TEXTURE_CUBE_MAP:
            {
              for (var _k7 = 0; _k7 < regions.length; _k7++) {
                var _region = regions[_k7];
                var fcount = _region.texSubres.baseArrayLayer + _region.texSubres.layerCount;
                for (f = _region.texSubres.baseArrayLayer; f < fcount; ++f) {
                  gl.texSubImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + f, _region.texSubres.mipLevel, _region.texOffset.x, _region.texOffset.y, gpuTexture.glFormat, gpuTexture.glType, texImages[n++]);
                }
              }
              break;
            }
          default:
            {
              error('Unsupported GL texture type, copy buffer to texture failed.');
            }
        }
        if (gpuTexture.flags & TextureFlagBit.GEN_MIPMAP) {
          gl.generateMipmap(gpuTexture.glTarget);
        }
      }
      var stagingBuffer = new Uint8Array(1);
      function pixelBufferPick(buffer, format, offset, stride, extent) {
        var blockHeight = formatAlignment(format).height;
        var bufferSize = FormatSize(format, extent.width, extent.height, extent.depth);
        var rowStrideSize = FormatSize(format, stride.width, 1, 1);
        var sliceStrideSize = FormatSize(format, stride.width, stride.height, 1);
        var destRowSize = FormatSize(format, extent.width, 1, 1);
        var ArrayBufferCtor = getTypedArrayConstructor(FormatInfos[format]);
        if (stagingBuffer.byteLength < bufferSize) {
          stagingBuffer = new Uint8Array(bufferSize);
        }
        var destOffset = 0;
        var bufferOffset = offset;
        for (var i = 0; i < extent.depth; i++) {
          bufferOffset = offset + sliceStrideSize * i;
          for (var j = 0; j < extent.height; j += blockHeight) {
            stagingBuffer.subarray(destOffset, destOffset + destRowSize).set(new Uint8Array(buffer.buffer, buffer.byteOffset + bufferOffset, destRowSize));
            destOffset += destRowSize;
            bufferOffset += rowStrideSize;
          }
        }
        var length = bufferSize / ArrayBufferCtor.BYTES_PER_ELEMENT;
        assertID(Number.isInteger(length), 9101);
        return new ArrayBufferCtor(stagingBuffer.buffer, 0, length);
      }
      function WebGL2CmdFuncCopyBuffersToTexture(device, buffers, gpuTexture, regions) {
        var gl = device.gl;
        var glTexUnit = device.stateCache.glTexUnits[device.stateCache.texUnit];
        if (glTexUnit.glTexture !== gpuTexture.glTexture) {
          gl.bindTexture(gpuTexture.glTarget, gpuTexture.glTexture);
          glTexUnit.glTexture = gpuTexture.glTexture;
        }
        var n = 0;
        var f = 0;
        var fmtInfo = FormatInfos[gpuTexture.format];
        var ArrayBufferCtor = getTypedArrayConstructor(fmtInfo);
        var isCompressed = fmtInfo.isCompressed;
        var blockSize = formatAlignment(gpuTexture.format);
        var extent = new Extent();
        var offset = new Offset();
        var stride = new Extent();
        switch (gpuTexture.glTarget) {
          case gl.TEXTURE_2D:
            {
              for (var k = 0; k < regions.length; k++) {
                var region = regions[k];
                var mipLevel = region.texSubres.mipLevel;
                offset.x = region.texOffset.x === 0 ? 0 : alignTo(region.texOffset.x, blockSize.width);
                offset.y = region.texOffset.y === 0 ? 0 : alignTo(region.texOffset.y, blockSize.height);
                extent.width = region.texExtent.width < blockSize.width ? region.texExtent.width : alignTo(region.texExtent.width, blockSize.width);
                extent.height = region.texExtent.height < blockSize.height ? region.texExtent.width : alignTo(region.texExtent.height, blockSize.height);
                stride.width = region.buffStride > 0 ? region.buffStride : extent.width;
                stride.height = region.buffTexHeight > 0 ? region.buffTexHeight : extent.height;
                var destWidth = region.texExtent.width + offset.x === gpuTexture.width >> mipLevel ? region.texExtent.width : extent.width;
                var destHeight = region.texExtent.height + offset.y === gpuTexture.height >> mipLevel ? region.texExtent.height : extent.height;
                var pixels = void 0;
                var buffer = buffers[n++];
                if (stride.width === extent.width && stride.height === extent.height) {
                  var length = FormatSize(gpuTexture.format, destWidth, destHeight, 1) / ArrayBufferCtor.BYTES_PER_ELEMENT;
                  assertID(Number.isInteger(length), 9101);
                  pixels = new ArrayBufferCtor(buffer.buffer, buffer.byteOffset + region.buffOffset, length);
                } else {
                  pixels = pixelBufferPick(buffer, gpuTexture.format, region.buffOffset, stride, extent);
                }
                if (!isCompressed) {
                  gl.texSubImage2D(gl.TEXTURE_2D, mipLevel, offset.x, offset.y, destWidth, destHeight, gpuTexture.glFormat, gpuTexture.glType, pixels);
                } else if (gpuTexture.glInternalFmt !== WebGL2EXT.COMPRESSED_RGB_ETC1_WEBGL) {
                  gl.compressedTexSubImage2D(gl.TEXTURE_2D, mipLevel, offset.x, offset.y, destWidth, destHeight, gpuTexture.glFormat, pixels);
                } else {
                  gl.compressedTexImage2D(gl.TEXTURE_2D, mipLevel, gpuTexture.glInternalFmt, destWidth, destHeight, 0, pixels);
                }
              }
              break;
            }
          case gl.TEXTURE_2D_ARRAY:
            {
              for (var _k8 = 0; _k8 < regions.length; _k8++) {
                var _region2 = regions[_k8];
                var _mipLevel = _region2.texSubres.mipLevel;
                offset.x = _region2.texOffset.x === 0 ? 0 : alignTo(_region2.texOffset.x, blockSize.width);
                offset.y = _region2.texOffset.y === 0 ? 0 : alignTo(_region2.texOffset.y, blockSize.height);
                extent.width = _region2.texExtent.width < blockSize.width ? _region2.texExtent.width : alignTo(_region2.texExtent.width, blockSize.width);
                extent.height = _region2.texExtent.height < blockSize.height ? _region2.texExtent.width : alignTo(_region2.texExtent.height, blockSize.height);
                extent.depth = 1;
                stride.width = _region2.buffStride > 0 ? _region2.buffStride : extent.width;
                stride.height = _region2.buffTexHeight > 0 ? _region2.buffTexHeight : extent.height;
                var _destWidth = _region2.texExtent.width + offset.x === gpuTexture.width >> _mipLevel ? _region2.texExtent.width : extent.width;
                var _destHeight = _region2.texExtent.height + offset.y === gpuTexture.height >> _mipLevel ? _region2.texExtent.height : extent.height;
                var fcount = _region2.texSubres.baseArrayLayer + _region2.texSubres.layerCount;
                for (f = _region2.texSubres.baseArrayLayer; f < fcount; ++f) {
                  offset.z = f;
                  var _pixels = void 0;
                  var _buffer = buffers[n++];
                  if (stride.width === extent.width && stride.height === extent.height) {
                    var _length = FormatSize(gpuTexture.format, _destWidth, _destHeight, 1) / ArrayBufferCtor.BYTES_PER_ELEMENT;
                    assertID(Number.isInteger(_length), 9101);
                    _pixels = new ArrayBufferCtor(_buffer.buffer, _buffer.byteOffset + _region2.buffOffset, _length);
                  } else {
                    _pixels = pixelBufferPick(_buffer, gpuTexture.format, _region2.buffOffset, stride, extent);
                  }
                  if (!isCompressed) {
                    gl.texSubImage3D(gl.TEXTURE_2D_ARRAY, _mipLevel, offset.x, offset.y, offset.z, _destWidth, _destHeight, extent.depth, gpuTexture.glFormat, gpuTexture.glType, _pixels);
                  } else if (gpuTexture.glInternalFmt !== WebGL2EXT.COMPRESSED_RGB_ETC1_WEBGL) {
                    gl.compressedTexSubImage3D(gl.TEXTURE_2D_ARRAY, _mipLevel, offset.x, offset.y, offset.z, _destWidth, _destHeight, extent.depth, gpuTexture.glFormat, _pixels);
                  } else {
                    gl.compressedTexImage3D(gl.TEXTURE_2D_ARRAY, _mipLevel, gpuTexture.glInternalFmt, _destWidth, _destHeight, extent.depth, 0, _pixels);
                  }
                }
              }
              break;
            }
          case gl.TEXTURE_3D:
            {
              for (var _k9 = 0; _k9 < regions.length; _k9++) {
                var _region3 = regions[_k9];
                var _mipLevel2 = _region3.texSubres.mipLevel;
                offset.x = _region3.texOffset.x === 0 ? 0 : alignTo(_region3.texOffset.x, blockSize.width);
                offset.y = _region3.texOffset.y === 0 ? 0 : alignTo(_region3.texOffset.y, blockSize.height);
                offset.z = _region3.texOffset.z;
                extent.width = _region3.texExtent.width < blockSize.width ? _region3.texExtent.width : alignTo(_region3.texExtent.width, blockSize.width);
                extent.height = _region3.texExtent.height < blockSize.height ? _region3.texExtent.width : alignTo(_region3.texExtent.height, blockSize.height);
                extent.depth = _region3.texExtent.depth;
                stride.width = _region3.buffStride > 0 ? _region3.buffStride : extent.width;
                stride.height = _region3.buffTexHeight > 0 ? _region3.buffTexHeight : extent.height;
                var _destWidth2 = _region3.texExtent.width + offset.x === gpuTexture.width >> _mipLevel2 ? _region3.texExtent.width : extent.width;
                var _destHeight2 = _region3.texExtent.height + offset.y === gpuTexture.height >> _mipLevel2 ? _region3.texExtent.height : extent.height;
                var _pixels2 = void 0;
                var _buffer2 = buffers[n++];
                if (stride.width === extent.width && stride.height === extent.height) {
                  var _length2 = FormatSize(gpuTexture.format, _destWidth2, _destHeight2, extent.depth) / ArrayBufferCtor.BYTES_PER_ELEMENT;
                  assertID(Number.isInteger(_length2), 9101);
                  _pixels2 = new ArrayBufferCtor(_buffer2.buffer, _buffer2.byteOffset + _region3.buffOffset, _length2);
                } else {
                  _pixels2 = pixelBufferPick(_buffer2, gpuTexture.format, _region3.buffOffset, stride, extent);
                }
                if (!isCompressed) {
                  gl.texSubImage3D(gl.TEXTURE_2D_ARRAY, _mipLevel2, offset.x, offset.y, offset.z, _destWidth2, _destHeight2, extent.depth, gpuTexture.glFormat, gpuTexture.glType, _pixels2);
                } else if (gpuTexture.glInternalFmt !== WebGL2EXT.COMPRESSED_RGB_ETC1_WEBGL) {
                  gl.compressedTexSubImage3D(gl.TEXTURE_2D_ARRAY, _mipLevel2, offset.x, offset.y, offset.z, _destWidth2, _destHeight2, extent.depth, gpuTexture.glFormat, _pixels2);
                } else {
                  gl.compressedTexImage3D(gl.TEXTURE_2D_ARRAY, _mipLevel2, gpuTexture.glInternalFmt, _destWidth2, _destHeight2, extent.depth, 0, _pixels2);
                }
              }
              break;
            }
          case gl.TEXTURE_CUBE_MAP:
            {
              for (var _k10 = 0; _k10 < regions.length; _k10++) {
                var _region4 = regions[_k10];
                var _mipLevel3 = _region4.texSubres.mipLevel;
                offset.x = _region4.texOffset.x === 0 ? 0 : alignTo(_region4.texOffset.x, blockSize.width);
                offset.y = _region4.texOffset.y === 0 ? 0 : alignTo(_region4.texOffset.y, blockSize.height);
                extent.width = _region4.texExtent.width < blockSize.width ? _region4.texExtent.width : alignTo(_region4.texExtent.width, blockSize.width);
                extent.height = _region4.texExtent.height < blockSize.height ? _region4.texExtent.width : alignTo(_region4.texExtent.height, blockSize.height);
                stride.width = _region4.buffStride > 0 ? _region4.buffStride : extent.width;
                stride.height = _region4.buffTexHeight > 0 ? _region4.buffTexHeight : extent.height;
                var _destWidth3 = _region4.texExtent.width + offset.x === gpuTexture.width >> _mipLevel3 ? _region4.texExtent.width : extent.width;
                var _destHeight3 = _region4.texExtent.height + offset.y === gpuTexture.height >> _mipLevel3 ? _region4.texExtent.height : extent.height;
                var _fcount = _region4.texSubres.baseArrayLayer + _region4.texSubres.layerCount;
                for (f = _region4.texSubres.baseArrayLayer; f < _fcount; ++f) {
                  var _pixels3 = void 0;
                  var _buffer3 = buffers[n++];
                  if (stride.width === extent.width && stride.height === extent.height) {
                    var _length3 = FormatSize(gpuTexture.format, _destWidth3, _destHeight3, 1) / ArrayBufferCtor.BYTES_PER_ELEMENT;
                    assertID(Number.isInteger(_length3), 9101);
                    _pixels3 = new ArrayBufferCtor(_buffer3.buffer, _buffer3.byteOffset + _region4.buffOffset, _length3);
                  } else {
                    _pixels3 = pixelBufferPick(_buffer3, gpuTexture.format, _region4.buffOffset, stride, extent);
                  }
                  if (!isCompressed) {
                    gl.texSubImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + f, _mipLevel3, offset.x, offset.y, _destWidth3, _destHeight3, gpuTexture.glFormat, gpuTexture.glType, _pixels3);
                  } else if (gpuTexture.glInternalFmt !== WebGL2EXT.COMPRESSED_RGB_ETC1_WEBGL) {
                    gl.compressedTexSubImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + f, _mipLevel3, offset.x, offset.y, _destWidth3, _destHeight3, gpuTexture.glFormat, _pixels3);
                  } else {
                    gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + f, _mipLevel3, gpuTexture.glInternalFmt, _destWidth3, _destHeight3, 0, _pixels3);
                  }
                }
              }
              break;
            }
          default:
            {
              error('Unsupported GL texture type, copy buffer to texture failed.');
            }
        }
        if (gpuTexture.flags & TextureFlagBit.GEN_MIPMAP) {
          gl.generateMipmap(gpuTexture.glTarget);
        }
      }
      function WebGL2CmdFuncCopyTextureToBuffers(device, gpuTexture, buffers, regions) {
        var gl = device.gl;
        var cache = device.stateCache;
        var framebuffer = gl.createFramebuffer();
        gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
        var x = 0;
        var y = 0;
        var w = 1;
        var h = 1;
        switch (gpuTexture.glTarget) {
          case gl.TEXTURE_2D:
            {
              for (var k = 0; k < regions.length; k++) {
                var region = regions[k];
                gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gpuTexture.glTarget, gpuTexture.glTexture, region.texSubres.mipLevel);
                x = region.texOffset.x;
                y = region.texOffset.y;
                w = region.texExtent.width;
                h = region.texExtent.height;
                gl.readPixels(x, y, w, h, gpuTexture.glFormat, gpuTexture.glType, buffers[k]);
              }
              break;
            }
          default:
            {
              error('Unsupported GL texture type, copy texture to buffers failed.');
            }
        }
        gl.bindFramebuffer(gl.FRAMEBUFFER, null);
        cache.glFramebuffer = null;
        gl.deleteFramebuffer(framebuffer);
      }
      function WebGL2CmdFuncBlitTexture(device, src, dst, regions, filter) {
        var gl = device.gl;
        var cache = device.stateCache;
        var blitManager = device.blitManager;
        if (!blitManager) {
          return;
        }
        var glFilter = filter === Filter$1.LINEAR || filter === Filter$1.ANISOTROPIC ? gl.LINEAR : gl.NEAREST;
        var srcFramebuffer = blitManager.srcFramebuffer;
        var dstFramebuffer = blitManager.dstFramebuffer;
        var origReadFBO = cache.glReadFramebuffer;
        var origDrawFBO = cache.glFramebuffer;
        var srcMip = regions[0].srcSubres.mipLevel;
        var dstMip = regions[0].dstSubres.mipLevel;
        var blitInfo = function blitInfo(formatInfo) {
          var mask = 0;
          var attachment = gl.COLOR_ATTACHMENT0;
          if (formatInfo.hasStencil) {
            attachment = gl.DEPTH_STENCIL_ATTACHMENT;
          } else if (formatInfo.hasDepth) {
            attachment = gl.DEPTH_ATTACHMENT;
          }
          if (formatInfo.hasDepth || formatInfo.hasStencil) {
            if (formatInfo.hasDepth) {
              mask |= gl.DEPTH_BUFFER_BIT;
            }
            if (formatInfo.hasStencil) {
              mask |= gl.STENCIL_BUFFER_BIT;
            }
          } else {
            mask |= gl.COLOR_BUFFER_BIT;
          }
          return {
            mask: mask,
            attachment: attachment
          };
        };
        var regionIndices = regions.map(function (_, i) {
          return i;
        });
        regionIndices.sort(function (a, b) {
          return regions[a].srcSubres.mipLevel - regions[b].srcSubres.mipLevel;
        });
        var _blitInfo = blitInfo(FormatInfos[src.format]),
          srcMask = _blitInfo.mask,
          srcAttachment = _blitInfo.attachment;
        var _blitInfo2 = blitInfo(FormatInfos[dst.format]),
          dstAttachment = _blitInfo2.attachment;
        if (cache.glReadFramebuffer !== srcFramebuffer) {
          gl.bindFramebuffer(gl.READ_FRAMEBUFFER, srcFramebuffer);
          cache.glReadFramebuffer = srcFramebuffer;
        }
        if (cache.glFramebuffer !== dstFramebuffer) {
          gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, dstFramebuffer);
          cache.glFramebuffer = dstFramebuffer;
        }
        if (src.glTexture) {
          gl.framebufferTexture2D(gl.READ_FRAMEBUFFER, srcAttachment, src.glTarget, src.glTexture, srcMip);
        } else {
          gl.framebufferRenderbuffer(gl.READ_FRAMEBUFFER, srcAttachment, gl.RENDERBUFFER, src.glRenderbuffer);
        }
        if (dst.glTexture) {
          gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, dstAttachment, dst.glTarget, dst.glTexture, dstMip);
        } else {
          gl.framebufferRenderbuffer(gl.DRAW_FRAMEBUFFER, dstAttachment, gl.RENDERBUFFER, dst.glRenderbuffer);
        }
        for (var i = 0; i < regionIndices.length; i++) {
          var region = regions[regionIndices[i]];
          if (src.glTexture && srcMip !== region.srcSubres.mipLevel) {
            srcMip = region.srcSubres.mipLevel;
            gl.framebufferTexture2D(gl.READ_FRAMEBUFFER, srcAttachment, src.glTarget, src.glTexture, srcMip);
          }
          if (dst.glTexture && dstMip !== region.dstSubres.mipLevel) {
            dstMip = region.dstSubres.mipLevel;
            gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, dstAttachment, dst.glTarget, dst.glTexture, dstMip);
          }
          gl.blitFramebuffer(region.srcOffset.x, region.srcOffset.y, region.srcOffset.x + region.srcExtent.width, region.srcOffset.y + region.srcExtent.height, region.dstOffset.x, region.dstOffset.y, region.dstOffset.x + region.dstExtent.width, region.dstOffset.y + region.dstExtent.height, srcMask, glFilter);
        }
        if (cache.glReadFramebuffer !== origReadFBO) {
          gl.bindFramebuffer(gl.READ_FRAMEBUFFER, origReadFBO);
          cache.glReadFramebuffer = origReadFBO;
        }
        if (cache.glFramebuffer !== origDrawFBO) {
          gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, origDrawFBO);
          cache.glFramebuffer = origDrawFBO;
        }
      }

      var WebGL2IndirectDrawInfos = function () {
        function WebGL2IndirectDrawInfos() {
          this.counts = void 0;
          this.offsets = void 0;
          this.instances = void 0;
          this.drawCount = 0;
          this.drawByIndex = false;
          this.instancedDraw = false;
          this.byteOffsets = void 0;
          this._capacity = 4;
          this.counts = new Int32Array(this._capacity);
          this.offsets = new Int32Array(this._capacity);
          this.instances = new Int32Array(this._capacity);
          this.byteOffsets = new Int32Array(this._capacity);
        }
        var _proto = WebGL2IndirectDrawInfos.prototype;
        _proto.clearDraws = function clearDraws() {
          this.drawCount = 0;
          this.drawByIndex = false;
          this.instancedDraw = false;
        };
        _proto.setDrawInfo = function setDrawInfo(idx, info) {
          this._ensureCapacity(idx);
          this.drawByIndex = info.indexCount > 0;
          this.instancedDraw = !!info.instanceCount;
          this.drawCount = Math.max(idx + 1, this.drawCount);
          if (this.drawByIndex) {
            this.counts[idx] = info.indexCount;
            this.offsets[idx] = info.firstIndex;
          } else {
            this.counts[idx] = info.vertexCount;
            this.offsets[idx] = info.firstVertex;
          }
          this.instances[idx] = Math.max(1, info.instanceCount);
        };
        _proto._ensureCapacity = function _ensureCapacity(target) {
          if (this._capacity > target) return;
          this._capacity = nextPow2(target);
          var counts = new Int32Array(this._capacity);
          var offsets = new Int32Array(this._capacity);
          var instances = new Int32Array(this._capacity);
          this.byteOffsets = new Int32Array(this._capacity);
          counts.set(this.counts);
          offsets.set(this.offsets);
          instances.set(this.instances);
          this.counts = counts;
          this.offsets = offsets;
          this.instances = instances;
        };
        return WebGL2IndirectDrawInfos;
      }();
      var IWebGL2BlitManager = function () {
        function IWebGL2BlitManager() {
          this._srcFramebuffer = void 0;
          this._dstFramebuffer = void 0;
          var gl = WebGL2DeviceManager.instance.gl;
          this._srcFramebuffer = gl.createFramebuffer();
          this._dstFramebuffer = gl.createFramebuffer();
        }
        var _proto2 = IWebGL2BlitManager.prototype;
        _proto2.destroy = function destroy() {
          var gl = WebGL2DeviceManager.instance.gl;
          gl.deleteFramebuffer(this._srcFramebuffer);
          gl.deleteFramebuffer(this._dstFramebuffer);
        };
        _createClass(IWebGL2BlitManager, [{
          key: "srcFramebuffer",
          get: function get() {
            return this._srcFramebuffer;
          }
        }, {
          key: "dstFramebuffer",
          get: function get() {
            return this._dstFramebuffer;
          }
        }]);
        return IWebGL2BlitManager;
      }();

      var WebGL2Buffer = function (_Buffer) {
        _inheritsLoose(WebGL2Buffer, _Buffer);
        function WebGL2Buffer() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Buffer.call.apply(_Buffer, [this].concat(args)) || this;
          _this._gpuBuffer = null;
          return _this;
        }
        var _proto = WebGL2Buffer.prototype;
        _proto.initialize = function initialize(info) {
          if ('buffer' in info) {
            this._isBufferView = true;
            var buffer = info.buffer;
            this._usage = buffer.usage;
            this._memUsage = buffer.memUsage;
            this._size = this._stride = info.range;
            this._count = 1;
            this._flags = buffer.flags;
            this._gpuBuffer = {
              usage: this._usage,
              memUsage: this._memUsage,
              size: this._size,
              stride: this._stride,
              buffer: null,
              indirects: buffer.gpuBuffer.indirects,
              glTarget: buffer.gpuBuffer.glTarget,
              glBuffer: buffer.gpuBuffer.glBuffer,
              glOffset: info.offset
            };
          } else {
            this._usage = info.usage;
            this._memUsage = info.memUsage;
            this._size = info.size;
            this._stride = Math.max(info.stride || this._size, 1);
            this._count = this._size / this._stride;
            this._flags = info.flags;
            this._gpuBuffer = {
              usage: this._usage,
              memUsage: this._memUsage,
              size: this._size,
              stride: this._stride,
              buffer: null,
              indirects: new WebGL2IndirectDrawInfos(),
              glTarget: 0,
              glBuffer: null,
              glOffset: 0
            };
            WebGL2CmdFuncCreateBuffer(WebGL2DeviceManager.instance, this._gpuBuffer);
            WebGL2DeviceManager.instance.memoryStatus.bufferSize += this._size;
          }
        };
        _proto.destroy = function destroy() {
          if (this._gpuBuffer) {
            if (!this._isBufferView) {
              WebGL2CmdFuncDestroyBuffer(WebGL2DeviceManager.instance, this._gpuBuffer);
              WebGL2DeviceManager.instance.memoryStatus.bufferSize -= this._size;
            }
            this._gpuBuffer = null;
          }
        };
        _proto.resize = function resize(size) {
          if (this._isBufferView) {
            console.warn('cannot resize buffer views!');
            return;
          }
          var oldSize = this._size;
          if (oldSize === size) {
            return;
          }
          this._size = size;
          this._count = this._size / this._stride;
          if (this._gpuBuffer) {
            this._gpuBuffer.size = size;
            if (size > 0) {
              WebGL2CmdFuncResizeBuffer(WebGL2DeviceManager.instance, this._gpuBuffer);
              WebGL2DeviceManager.instance.memoryStatus.bufferSize -= oldSize;
              WebGL2DeviceManager.instance.memoryStatus.bufferSize += size;
            }
          }
        };
        _proto.update = function update(buffer, size) {
          if (this._isBufferView) {
            console.warn('cannot update through buffer views!');
            return;
          }
          var buffSize;
          if (size !== undefined) {
            buffSize = size;
          } else if (this._usage & BufferUsageBit.INDIRECT) {
            buffSize = 0;
          } else {
            buffSize = buffer.byteLength;
          }
          WebGL2CmdFuncUpdateBuffer(WebGL2DeviceManager.instance, this._gpuBuffer, buffer, 0, buffSize);
        };
        _createClass(WebGL2Buffer, [{
          key: "gpuBuffer",
          get: function get() {
            return this._gpuBuffer;
          }
        }]);
        return WebGL2Buffer;
      }(Buffer);

      var WebGL2CommandPool = function () {
        function WebGL2CommandPool(Clazz, count) {
          this._frees = void 0;
          this._freeIdx = 0;
          this._freeCmds = void 0;
          this._frees = new Array(count);
          this._freeCmds = new CachedArray(count);
          for (var i = 0; i < count; ++i) {
            this._frees[i] = new Clazz();
          }
          this._freeIdx = count - 1;
        }
        var _proto = WebGL2CommandPool.prototype;
        _proto.alloc = function alloc(Clazz) {
          if (this._freeIdx < 0) {
            var size = this._frees.length * 2;
            var temp = this._frees;
            this._frees = new Array(size);
            var increase = size - temp.length;
            for (var i = 0; i < increase; ++i) {
              this._frees[i] = new Clazz();
            }
            for (var _i = increase, j = 0; _i < size; ++_i, ++j) {
              this._frees[_i] = temp[j];
            }
            this._freeIdx += increase;
          }
          var cmd = this._frees[this._freeIdx];
          this._frees[this._freeIdx--] = null;
          ++cmd.refCount;
          return cmd;
        };
        _proto.free = function free(cmd) {
          if (--cmd.refCount === 0) {
            this._freeCmds.push(cmd);
          }
        };
        _proto.freeCmds = function freeCmds(cmds) {
          for (var i = 0; i < cmds.length; ++i) {
            if (--cmds.array[i].refCount === 0) {
              this._freeCmds.push(cmds.array[i]);
            }
          }
        };
        _proto.release = function release() {
          for (var i = 0; i < this._freeCmds.length; ++i) {
            var cmd = this._freeCmds.array[i];
            cmd.clear();
            this._frees[++this._freeIdx] = cmd;
          }
          this._freeCmds.clear();
        };
        return WebGL2CommandPool;
      }();
      var WebGL2CommandAllocator = function () {
        function WebGL2CommandAllocator() {
          this.beginRenderPassCmdPool = void 0;
          this.bindStatesCmdPool = void 0;
          this.drawCmdPool = void 0;
          this.updateBufferCmdPool = void 0;
          this.copyBufferToTextureCmdPool = void 0;
          this.blitTextureCmdPool = void 0;
          this.beginRenderPassCmdPool = new WebGL2CommandPool(WebGL2CmdBeginRenderPass, 1);
          this.bindStatesCmdPool = new WebGL2CommandPool(WebGL2CmdBindStates, 1);
          this.drawCmdPool = new WebGL2CommandPool(WebGL2CmdDraw, 1);
          this.updateBufferCmdPool = new WebGL2CommandPool(WebGL2CmdUpdateBuffer, 1);
          this.copyBufferToTextureCmdPool = new WebGL2CommandPool(WebGL2CmdCopyBufferToTexture, 1);
          this.blitTextureCmdPool = new WebGL2CommandPool(WebGL2CmdBlitTexture, 1);
        }
        var _proto2 = WebGL2CommandAllocator.prototype;
        _proto2.clearCmds = function clearCmds(cmdPackage) {
          if (cmdPackage.beginRenderPassCmds.length) {
            this.beginRenderPassCmdPool.freeCmds(cmdPackage.beginRenderPassCmds);
            cmdPackage.beginRenderPassCmds.clear();
          }
          if (cmdPackage.bindStatesCmds.length) {
            this.bindStatesCmdPool.freeCmds(cmdPackage.bindStatesCmds);
            cmdPackage.bindStatesCmds.clear();
          }
          if (cmdPackage.drawCmds.length) {
            this.drawCmdPool.freeCmds(cmdPackage.drawCmds);
            cmdPackage.drawCmds.clear();
          }
          if (cmdPackage.updateBufferCmds.length) {
            this.updateBufferCmdPool.freeCmds(cmdPackage.updateBufferCmds);
            cmdPackage.updateBufferCmds.clear();
          }
          if (cmdPackage.copyBufferToTextureCmds.length) {
            this.copyBufferToTextureCmdPool.freeCmds(cmdPackage.copyBufferToTextureCmds);
            cmdPackage.copyBufferToTextureCmds.clear();
          }
          if (cmdPackage.blitTextureCmds.length) {
            this.blitTextureCmdPool.freeCmds(cmdPackage.blitTextureCmds);
            cmdPackage.blitTextureCmds.clear();
          }
          cmdPackage.cmds.clear();
        };
        _proto2.releaseCmds = function releaseCmds() {
          this.beginRenderPassCmdPool.release();
          this.bindStatesCmdPool.release();
          this.drawCmdPool.release();
          this.updateBufferCmdPool.release();
          this.copyBufferToTextureCmdPool.release();
          this.blitTextureCmdPool.release();
        };
        return WebGL2CommandAllocator;
      }();

      var WebGL2CommandBuffer = function (_CommandBuffer) {
        _inheritsLoose(WebGL2CommandBuffer, _CommandBuffer);
        function WebGL2CommandBuffer() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _CommandBuffer.call.apply(_CommandBuffer, [this].concat(args)) || this;
          _this.cmdPackage = new WebGL2CmdPackage();
          _this._cmdAllocator = new WebGL2CommandAllocator();
          _this._isInRenderPass = false;
          _this._curGPUPipelineState = null;
          _this._curGPUDescriptorSets = [];
          _this._curGPUInputAssembler = null;
          _this._curDynamicOffsets = Array(8).fill(0);
          _this._curDynamicStates = new DynamicStates();
          _this._isStateInvalied = false;
          return _this;
        }
        var _proto = WebGL2CommandBuffer.prototype;
        _proto.initialize = function initialize(info) {
          this._type = info.type;
          this._queue = info.queue;
          var setCount = WebGL2DeviceManager.instance.bindingMappings.blockOffsets.length;
          for (var i = 0; i < setCount; i++) {
            this._curGPUDescriptorSets.push(null);
          }
        };
        _proto.destroy = function destroy() {
          this._cmdAllocator.clearCmds(this.cmdPackage);
        };
        _proto.begin = function begin(renderPass, subpass, frameBuffer) {
          this._cmdAllocator.clearCmds(this.cmdPackage);
          this._curGPUPipelineState = null;
          this._curGPUInputAssembler = null;
          this._curGPUDescriptorSets.length = 0;
          this._numDrawCalls = 0;
          this._numInstances = 0;
          this._numTris = 0;
        };
        _proto.end = function end() {
          if (this._isStateInvalied) {
            this.bindStates();
          }
          this._isInRenderPass = false;
        };
        _proto.beginRenderPass = function beginRenderPass(renderPass, framebuffer, renderArea, clearColors, clearDepth, clearStencil) {
          var cmd = this._cmdAllocator.beginRenderPassCmdPool.alloc(WebGL2CmdBeginRenderPass);
          cmd.gpuRenderPass = renderPass.gpuRenderPass;
          cmd.gpuFramebuffer = framebuffer.gpuFramebuffer;
          cmd.renderArea.copy(renderArea);
          for (var i = 0; i < clearColors.length; ++i) {
            cmd.clearColors[i] = clearColors[i];
          }
          cmd.clearDepth = clearDepth;
          cmd.clearStencil = clearStencil;
          this.cmdPackage.beginRenderPassCmds.push(cmd);
          this.cmdPackage.cmds.push(WebGL2Cmd.BEGIN_RENDER_PASS);
          this._isInRenderPass = true;
        };
        _proto.endRenderPass = function endRenderPass() {
          this._isInRenderPass = false;
        };
        _proto.bindPipelineState = function bindPipelineState(pipelineState) {
          var gpuPipelineState = pipelineState.gpuPipelineState;
          if (gpuPipelineState !== this._curGPUPipelineState) {
            this._curGPUPipelineState = gpuPipelineState;
            this._isStateInvalied = true;
          }
        };
        _proto.bindDescriptorSet = function bindDescriptorSet(set, descriptorSet, dynamicOffsets) {
          var gpuDescriptorSets = descriptorSet.gpuDescriptorSet;
          if (gpuDescriptorSets !== this._curGPUDescriptorSets[set]) {
            this._curGPUDescriptorSets[set] = gpuDescriptorSets;
            this._isStateInvalied = true;
          }
          if (dynamicOffsets) {
            var _this$_curGPUPipeline;
            var gpuPipelineLayout = (_this$_curGPUPipeline = this._curGPUPipelineState) === null || _this$_curGPUPipeline === void 0 ? void 0 : _this$_curGPUPipeline.gpuPipelineLayout;
            if (gpuPipelineLayout) {
              var offsets = this._curDynamicOffsets;
              var idx = gpuPipelineLayout.dynamicOffsetOffsets[set];
              for (var i = 0; i < dynamicOffsets.length; i++) offsets[idx + i] = dynamicOffsets[i];
              this._isStateInvalied = true;
            }
          }
        };
        _proto.bindInputAssembler = function bindInputAssembler(inputAssembler) {
          var gpuInputAssembler = inputAssembler.gpuInputAssembler;
          this._curGPUInputAssembler = gpuInputAssembler;
          this._isStateInvalied = true;
        };
        _proto.setViewport = function setViewport(viewport) {
          var cache = this._curDynamicStates.viewport;
          if (cache.left !== viewport.left || cache.top !== viewport.top || cache.width !== viewport.width || cache.height !== viewport.height || cache.minDepth !== viewport.minDepth || cache.maxDepth !== viewport.maxDepth) {
            cache.left = viewport.left;
            cache.top = viewport.top;
            cache.width = viewport.width;
            cache.height = viewport.height;
            cache.minDepth = viewport.minDepth;
            cache.maxDepth = viewport.maxDepth;
            this._isStateInvalied = true;
          }
        };
        _proto.setScissor = function setScissor(scissor) {
          var cache = this._curDynamicStates.scissor;
          if (cache.x !== scissor.x || cache.y !== scissor.y || cache.width !== scissor.width || cache.height !== scissor.height) {
            cache.x = scissor.x;
            cache.y = scissor.y;
            cache.width = scissor.width;
            cache.height = scissor.height;
            this._isStateInvalied = true;
          }
        };
        _proto.setLineWidth = function setLineWidth(lineWidth) {
          if (this._curDynamicStates.lineWidth !== lineWidth) {
            this._curDynamicStates.lineWidth = lineWidth;
            this._isStateInvalied = true;
          }
        };
        _proto.setDepthBias = function setDepthBias(depthBiasConstantFactor, depthBiasClamp, depthBiasSlopeFactor) {
          var cache = this._curDynamicStates;
          if (cache.depthBiasConstant !== depthBiasConstantFactor || cache.depthBiasClamp !== depthBiasClamp || cache.depthBiasSlope !== depthBiasSlopeFactor) {
            cache.depthBiasConstant = depthBiasConstantFactor;
            cache.depthBiasClamp = depthBiasClamp;
            cache.depthBiasSlope = depthBiasSlopeFactor;
            this._isStateInvalied = true;
          }
        };
        _proto.setBlendConstants = function setBlendConstants(blendConstants) {
          var cache = this._curDynamicStates.blendConstant;
          if (cache.x !== blendConstants.x || cache.y !== blendConstants.y || cache.z !== blendConstants.z || cache.w !== blendConstants.w) {
            cache.copy(blendConstants);
            this._isStateInvalied = true;
          }
        };
        _proto.setDepthBound = function setDepthBound(minDepthBounds, maxDepthBounds) {
          var cache = this._curDynamicStates;
          if (cache.depthMinBounds !== minDepthBounds || cache.depthMaxBounds !== maxDepthBounds) {
            cache.depthMinBounds = minDepthBounds;
            cache.depthMaxBounds = maxDepthBounds;
            this._isStateInvalied = true;
          }
        };
        _proto.setStencilWriteMask = function setStencilWriteMask(face, writeMask) {
          var front = this._curDynamicStates.stencilStatesFront;
          var back = this._curDynamicStates.stencilStatesBack;
          if (face & StencilFace.FRONT) {
            if (front.writeMask !== writeMask) {
              front.writeMask = writeMask;
              this._isStateInvalied = true;
            }
          }
          if (face & StencilFace.BACK) {
            if (back.writeMask !== writeMask) {
              back.writeMask = writeMask;
              this._isStateInvalied = true;
            }
          }
        };
        _proto.setStencilCompareMask = function setStencilCompareMask(face, reference, compareMask) {
          var front = this._curDynamicStates.stencilStatesFront;
          var back = this._curDynamicStates.stencilStatesBack;
          if (face & StencilFace.FRONT) {
            if (front.compareMask !== compareMask || front.reference !== reference) {
              front.reference = reference;
              front.compareMask = compareMask;
              this._isStateInvalied = true;
            }
          }
          if (face & StencilFace.BACK) {
            if (back.compareMask !== compareMask || back.reference !== reference) {
              back.reference = reference;
              back.compareMask = compareMask;
              this._isStateInvalied = true;
            }
          }
        };
        _proto.draw = function draw(infoOrAssembler) {
          if (this._type === CommandBufferType.PRIMARY && this._isInRenderPass || this._type === CommandBufferType.SECONDARY) {
            if (this._isStateInvalied) {
              this.bindStates();
            }
            var info = 'drawInfo' in infoOrAssembler ? infoOrAssembler.drawInfo : infoOrAssembler;
            var cmd = this._cmdAllocator.drawCmdPool.alloc(WebGL2CmdDraw);
            cmd.drawInfo.copy(info);
            this.cmdPackage.drawCmds.push(cmd);
            this.cmdPackage.cmds.push(WebGL2Cmd.DRAW);
            ++this._numDrawCalls;
            this._numInstances += info.instanceCount;
            var indexCount = info.indexCount || info.vertexCount;
            if (this._curGPUPipelineState) {
              var glPrimitive = this._curGPUPipelineState.glPrimitive;
              switch (glPrimitive) {
                case 0x0004:
                  {
                    this._numTris += indexCount / 3 * Math.max(info.instanceCount, 1);
                    break;
                  }
                case 0x0005:
                case 0x0006:
                  {
                    this._numTris += (indexCount - 2) * Math.max(info.instanceCount, 1);
                    break;
                  }
              }
            }
          } else {
            console.error('Command \'draw\' must be recorded inside a render pass.');
          }
        };
        _proto.updateBuffer = function updateBuffer(buffer, data, size) {
          if (this._type === CommandBufferType.PRIMARY && !this._isInRenderPass || this._type === CommandBufferType.SECONDARY) {
            var gpuBuffer = buffer.gpuBuffer;
            if (gpuBuffer) {
              var cmd = this._cmdAllocator.updateBufferCmdPool.alloc(WebGL2CmdUpdateBuffer);
              var buffSize = 0;
              var buff = null;
              if (buffer.usage & BufferUsageBit.INDIRECT) {
                buff = data;
              } else {
                if (size !== undefined) {
                  buffSize = size;
                } else {
                  buffSize = data.byteLength;
                }
                buff = data;
              }
              cmd.gpuBuffer = gpuBuffer;
              cmd.buffer = buff;
              cmd.offset = 0;
              cmd.size = buffSize;
              this.cmdPackage.updateBufferCmds.push(cmd);
              this.cmdPackage.cmds.push(WebGL2Cmd.UPDATE_BUFFER);
            }
          } else {
            console.error('Command \'updateBuffer\' must be recorded outside a render pass.');
          }
        };
        _proto.copyBuffersToTexture = function copyBuffersToTexture(buffers, texture, regions) {
          if (this._type === CommandBufferType.PRIMARY && !this._isInRenderPass || this._type === CommandBufferType.SECONDARY) {
            var gpuTexture = texture.gpuTexture;
            if (gpuTexture) {
              var cmd = this._cmdAllocator.copyBufferToTextureCmdPool.alloc(WebGL2CmdCopyBufferToTexture);
              cmd.gpuTexture = gpuTexture;
              cmd.regions = regions;
              cmd.buffers = buffers;
              this.cmdPackage.copyBufferToTextureCmds.push(cmd);
              this.cmdPackage.cmds.push(WebGL2Cmd.COPY_BUFFER_TO_TEXTURE);
            }
          } else {
            console.error('Command \'copyBufferToTexture\' must be recorded outside a render pass.');
          }
        };
        _proto.execute = function execute(cmdBuffs, count) {
          for (var i = 0; i < count; ++i) {
            var webGL2CmdBuff = cmdBuffs[i];
            for (var c = 0; c < webGL2CmdBuff.cmdPackage.beginRenderPassCmds.length; ++c) {
              var cmd = webGL2CmdBuff.cmdPackage.beginRenderPassCmds.array[c];
              ++cmd.refCount;
              this.cmdPackage.beginRenderPassCmds.push(cmd);
            }
            for (var _c = 0; _c < webGL2CmdBuff.cmdPackage.bindStatesCmds.length; ++_c) {
              var _cmd = webGL2CmdBuff.cmdPackage.bindStatesCmds.array[_c];
              ++_cmd.refCount;
              this.cmdPackage.bindStatesCmds.push(_cmd);
            }
            for (var _c2 = 0; _c2 < webGL2CmdBuff.cmdPackage.drawCmds.length; ++_c2) {
              var _cmd2 = webGL2CmdBuff.cmdPackage.drawCmds.array[_c2];
              ++_cmd2.refCount;
              this.cmdPackage.drawCmds.push(_cmd2);
            }
            for (var _c3 = 0; _c3 < webGL2CmdBuff.cmdPackage.updateBufferCmds.length; ++_c3) {
              var _cmd3 = webGL2CmdBuff.cmdPackage.updateBufferCmds.array[_c3];
              ++_cmd3.refCount;
              this.cmdPackage.updateBufferCmds.push(_cmd3);
            }
            for (var _c4 = 0; _c4 < webGL2CmdBuff.cmdPackage.copyBufferToTextureCmds.length; ++_c4) {
              var _cmd4 = webGL2CmdBuff.cmdPackage.copyBufferToTextureCmds.array[_c4];
              ++_cmd4.refCount;
              this.cmdPackage.copyBufferToTextureCmds.push(_cmd4);
            }
            for (var _c5 = 0; _c5 < webGL2CmdBuff.cmdPackage.blitTextureCmds.length; ++_c5) {
              var _cmd5 = webGL2CmdBuff.cmdPackage.blitTextureCmds.array[_c5];
              ++_cmd5.refCount;
              this.cmdPackage.blitTextureCmds.push(_cmd5);
            }
            this.cmdPackage.cmds.concat(webGL2CmdBuff.cmdPackage.cmds.array);
            this._numDrawCalls += webGL2CmdBuff._numDrawCalls;
            this._numInstances += webGL2CmdBuff._numInstances;
            this._numTris += webGL2CmdBuff._numTris;
          }
        };
        _proto.pipelineBarrier = function pipelineBarrier(GeneralBarrier, bufferBarriers, buffers, textureBarriers, textures) {};
        _proto.bindStates = function bindStates() {
          var bindStatesCmd = this._cmdAllocator.bindStatesCmdPool.alloc(WebGL2CmdBindStates);
          bindStatesCmd.gpuPipelineState = this._curGPUPipelineState;
          Array.prototype.push.apply(bindStatesCmd.gpuDescriptorSets, this._curGPUDescriptorSets);
          Array.prototype.push.apply(bindStatesCmd.dynamicOffsets, this._curDynamicOffsets);
          bindStatesCmd.gpuInputAssembler = this._curGPUInputAssembler;
          bindStatesCmd.dynamicStates = this._curDynamicStates;
          this.cmdPackage.bindStatesCmds.push(bindStatesCmd);
          this.cmdPackage.cmds.push(WebGL2Cmd.BIND_STATES);
          this._isStateInvalied = false;
        };
        _proto.blitTexture = function blitTexture(srcTexture, dstTexture, regions, filter) {
          var blitTextureCmd = this._cmdAllocator.blitTextureCmdPool.alloc(WebGL2CmdBlitTexture);
          blitTextureCmd.srcTexture = srcTexture.gpuTexture;
          blitTextureCmd.dstTexture = dstTexture.gpuTexture;
          blitTextureCmd.regions = regions;
          blitTextureCmd.filter = filter;
          ++this._numDrawCalls;
          this.cmdPackage.blitTextureCmds.push(blitTextureCmd);
          this.cmdPackage.cmds.push(WebGL2Cmd.BLIT_TEXTURE);
        };
        return WebGL2CommandBuffer;
      }(CommandBuffer);

      var WebGL2Framebuffer = function (_Framebuffer) {
        _inheritsLoose(WebGL2Framebuffer, _Framebuffer);
        function WebGL2Framebuffer() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Framebuffer.call.apply(_Framebuffer, [this].concat(args)) || this;
          _this._gpuFramebuffer = null;
          return _this;
        }
        var _proto = WebGL2Framebuffer.prototype;
        _proto.initialize = function initialize(info) {
          this._renderPass = info.renderPass;
          this._colorTextures = info.colorTextures || [];
          this._depthStencilTexture = info.depthStencilTexture || null;
          var gpuColorViews = [];
          for (var i = 0; i < info.colorTextures.length; i++) {
            var colorTexture = info.colorTextures[i];
            if (colorTexture) {
              gpuColorViews.push(colorTexture.gpuTextureView);
            }
          }
          var gpuDepthStencilView = null;
          if (info.depthStencilTexture) {
            gpuDepthStencilView = info.depthStencilTexture.gpuTextureView;
          }
          var width = Number.MAX_SAFE_INTEGER;
          var height = Number.MAX_SAFE_INTEGER;
          this._gpuFramebuffer = {
            gpuRenderPass: info.renderPass.gpuRenderPass,
            gpuColorViews: gpuColorViews,
            gpuDepthStencilView: gpuDepthStencilView,
            glFramebuffer: null,
            isOffscreen: true,
            get width() {
              if (this.isOffscreen) {
                return width;
              } else if (this.gpuColorViews.length > 0) {
                return this.gpuColorViews[0].gpuTexture.width;
              } else {
                return this.gpuDepthStencilView.gpuTexture.width;
              }
            },
            set width(val) {
              width = val;
            },
            get height() {
              if (this.isOffscreen) {
                return height;
              } else if (this.gpuColorViews.length > 0) {
                return this.gpuColorViews[0].gpuTexture.height;
              } else {
                return this.gpuDepthStencilView.gpuTexture.height;
              }
            },
            set height(val) {
              height = val;
            }
          };
          WebGL2CmdFuncCreateFramebuffer(WebGL2DeviceManager.instance, this._gpuFramebuffer);
          this._width = this._gpuFramebuffer.width;
          this._height = this._gpuFramebuffer.height;
        };
        _proto.destroy = function destroy() {
          if (this._gpuFramebuffer) {
            WebGL2CmdFuncDestroyFramebuffer(WebGL2DeviceManager.instance, this._gpuFramebuffer);
            this._gpuFramebuffer = null;
          }
        };
        _createClass(WebGL2Framebuffer, [{
          key: "gpuFramebuffer",
          get: function get() {
            return this._gpuFramebuffer;
          }
        }]);
        return WebGL2Framebuffer;
      }(Framebuffer);

      var WebGL2InputAssembler = function (_InputAssembler) {
        _inheritsLoose(WebGL2InputAssembler, _InputAssembler);
        function WebGL2InputAssembler() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _InputAssembler.call.apply(_InputAssembler, [this].concat(args)) || this;
          _this._gpuInputAssembler = null;
          return _this;
        }
        var _proto = WebGL2InputAssembler.prototype;
        _proto.initialize = function initialize(info) {
          if (info.vertexBuffers.length === 0) {
            console.error('InputAssemblerInfo.vertexBuffers is null.');
            return;
          }
          this._attributes = info.attributes;
          this._attributesHash = this.computeAttributesHash();
          this._vertexBuffers = info.vertexBuffers;
          if (info.indexBuffer) {
            this._indexBuffer = info.indexBuffer;
            this._drawInfo.indexCount = this._indexBuffer.size / this._indexBuffer.stride;
            this._drawInfo.firstIndex = 0;
          } else {
            var vertBuff = this._vertexBuffers[0];
            this._drawInfo.vertexCount = vertBuff.size / vertBuff.stride;
            this._drawInfo.firstVertex = 0;
            this._drawInfo.vertexOffset = 0;
          }
          this._drawInfo.instanceCount = 0;
          this._drawInfo.firstInstance = 0;
          this._indirectBuffer = info.indirectBuffer || null;
          var gpuVertexBuffers = new Array(info.vertexBuffers.length);
          for (var i = 0; i < info.vertexBuffers.length; ++i) {
            var vb = info.vertexBuffers[i];
            if (vb.gpuBuffer) {
              gpuVertexBuffers[i] = vb.gpuBuffer;
            }
          }
          var gpuIndexBuffer = null;
          var glIndexType = 0;
          if (info.indexBuffer) {
            gpuIndexBuffer = info.indexBuffer.gpuBuffer;
            if (gpuIndexBuffer) {
              switch (gpuIndexBuffer.stride) {
                case 1:
                  glIndexType = 0x1401;
                  break;
                case 2:
                  glIndexType = 0x1403;
                  break;
                case 4:
                  glIndexType = 0x1405;
                  break;
                default:
                  {
                    console.error('Illegal index buffer stride.');
                  }
              }
            }
          }
          var gpuIndirectBuffer = null;
          if (info.indirectBuffer) {
            gpuIndirectBuffer = info.indirectBuffer.gpuBuffer;
          }
          this._gpuInputAssembler = {
            attributes: info.attributes,
            gpuVertexBuffers: gpuVertexBuffers,
            gpuIndexBuffer: gpuIndexBuffer,
            gpuIndirectBuffer: gpuIndirectBuffer,
            glAttribs: [],
            glIndexType: glIndexType,
            glVAOs: new Map()
          };
          WebGL2CmdFuncCreateInputAssember(WebGL2DeviceManager.instance, this._gpuInputAssembler);
        };
        _proto.destroy = function destroy() {
          var device = WebGL2DeviceManager.instance;
          if (this._gpuInputAssembler && device.extensions.useVAO) {
            WebGL2CmdFuncDestroyInputAssembler(device, this._gpuInputAssembler);
          }
          this._gpuInputAssembler = null;
        };
        _createClass(WebGL2InputAssembler, [{
          key: "gpuInputAssembler",
          get: function get() {
            return this._gpuInputAssembler;
          }
        }]);
        return WebGL2InputAssembler;
      }(InputAssembler);

      var WebGL2DescriptorSetLayout = function (_DescriptorSetLayout) {
        _inheritsLoose(WebGL2DescriptorSetLayout, _DescriptorSetLayout);
        function WebGL2DescriptorSetLayout() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _DescriptorSetLayout.call.apply(_DescriptorSetLayout, [this].concat(args)) || this;
          _this._gpuDescriptorSetLayout = null;
          return _this;
        }
        var _proto = WebGL2DescriptorSetLayout.prototype;
        _proto.initialize = function initialize(info) {
          Array.prototype.push.apply(this._bindings, info.bindings);
          var descriptorCount = 0;
          var maxBinding = -1;
          var flattenedIndices = [];
          for (var i = 0; i < this._bindings.length; i++) {
            var binding = this._bindings[i];
            flattenedIndices.push(descriptorCount);
            descriptorCount += binding.count;
            if (binding.binding > maxBinding) maxBinding = binding.binding;
          }
          this._bindingIndices = Array(maxBinding + 1).fill(-1);
          var descriptorIndices = this._descriptorIndices = Array(maxBinding + 1).fill(-1);
          for (var _i = 0; _i < this._bindings.length; _i++) {
            var _binding = this._bindings[_i];
            this._bindingIndices[_binding.binding] = _i;
            descriptorIndices[_binding.binding] = flattenedIndices[_i];
          }
          var dynamicBindings = [];
          for (var _i2 = 0; _i2 < this._bindings.length; _i2++) {
            var _binding2 = this._bindings[_i2];
            if (_binding2.descriptorType & DESCRIPTOR_DYNAMIC_TYPE) {
              for (var j = 0; j < _binding2.count; j++) {
                dynamicBindings.push(_binding2.binding);
              }
            }
          }
          this._gpuDescriptorSetLayout = {
            bindings: this._bindings,
            dynamicBindings: dynamicBindings,
            descriptorIndices: descriptorIndices,
            descriptorCount: descriptorCount
          };
        };
        _proto.destroy = function destroy() {
          this._bindings.length = 0;
        };
        _createClass(WebGL2DescriptorSetLayout, [{
          key: "gpuDescriptorSetLayout",
          get: function get() {
            return this._gpuDescriptorSetLayout;
          }
        }]);
        return WebGL2DescriptorSetLayout;
      }(DescriptorSetLayout);

      var WebGL2PipelineLayout = function (_PipelineLayout) {
        _inheritsLoose(WebGL2PipelineLayout, _PipelineLayout);
        function WebGL2PipelineLayout() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _PipelineLayout.call.apply(_PipelineLayout, [this].concat(args)) || this;
          _this._gpuPipelineLayout = null;
          return _this;
        }
        var _proto = WebGL2PipelineLayout.prototype;
        _proto.initialize = function initialize(info) {
          Array.prototype.push.apply(this._setLayouts, info.setLayouts);
          var dynamicOffsetIndices = [];
          var gpuSetLayouts = [];
          var dynamicOffsetCount = 0;
          var dynamicOffsetOffsets = [];
          for (var i = 0; i < this._setLayouts.length; i++) {
            var setLayout = this._setLayouts[i];
            var dynamicBindings = setLayout.gpuDescriptorSetLayout.dynamicBindings;
            var indices = Array(setLayout.bindingIndices.length).fill(-1);
            for (var j = 0; j < dynamicBindings.length; j++) {
              var binding = dynamicBindings[j];
              if (indices[binding] < 0) indices[binding] = dynamicOffsetCount + j;
            }
            gpuSetLayouts.push(setLayout.gpuDescriptorSetLayout);
            dynamicOffsetIndices.push(indices);
            dynamicOffsetOffsets.push(dynamicOffsetCount);
            dynamicOffsetCount += dynamicBindings.length;
          }
          this._gpuPipelineLayout = {
            gpuSetLayouts: gpuSetLayouts,
            dynamicOffsetIndices: dynamicOffsetIndices,
            dynamicOffsetCount: dynamicOffsetCount,
            dynamicOffsetOffsets: dynamicOffsetOffsets
          };
        };
        _proto.destroy = function destroy() {
          this._setLayouts.length = 0;
        };
        _createClass(WebGL2PipelineLayout, [{
          key: "gpuPipelineLayout",
          get: function get() {
            return this._gpuPipelineLayout;
          }
        }]);
        return WebGL2PipelineLayout;
      }(PipelineLayout);

      var WebGLPrimitives = [0x0000, 0x0001, 0x0003, 0x0002, 0x0000, 0x0000, 0x0000, 0x0004, 0x0005, 0x0006, 0x0000, 0x0000, 0x0000, 0x0000];
      var WebGL2PipelineState = function (_PipelineState) {
        _inheritsLoose(WebGL2PipelineState, _PipelineState);
        function WebGL2PipelineState() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _PipelineState.call.apply(_PipelineState, [this].concat(args)) || this;
          _this._gpuPipelineState = null;
          return _this;
        }
        var _proto = WebGL2PipelineState.prototype;
        _proto.initialize = function initialize(info) {
          this._primitive = info.primitive;
          this._shader = info.shader;
          this._pipelineLayout = info.pipelineLayout;
          var bs = this._bs;
          if (info.blendState) {
            var bsInfo = info.blendState;
            var targets = bsInfo.targets;
            if (targets) {
              targets.forEach(function (t, i) {
                bs.setTarget(i, t);
              });
            }
            if (bsInfo.isA2C !== undefined) {
              bs.isA2C = bsInfo.isA2C;
            }
            if (bsInfo.isIndepend !== undefined) {
              bs.isIndepend = bsInfo.isIndepend;
            }
            if (bsInfo.blendColor !== undefined) {
              bs.blendColor = bsInfo.blendColor;
            }
          }
          Object.assign(this._rs, info.rasterizerState);
          Object.assign(this._dss, info.depthStencilState);
          this._is = info.inputState;
          this._renderPass = info.renderPass;
          this._dynamicStates = info.dynamicStates;
          var dynamicStates = [];
          for (var i = 0; i < 31; i++) {
            if (this._dynamicStates & 1 << i) {
              dynamicStates.push(1 << i);
            }
          }
          this._gpuPipelineState = {
            glPrimitive: WebGLPrimitives[info.primitive],
            gpuShader: info.shader.gpuShader,
            gpuPipelineLayout: info.pipelineLayout.gpuPipelineLayout,
            rs: info.rasterizerState,
            dss: info.depthStencilState,
            bs: info.blendState,
            gpuRenderPass: info.renderPass.gpuRenderPass,
            dynamicStates: dynamicStates
          };
        };
        _proto.destroy = function destroy() {
          this._gpuPipelineState = null;
        };
        _createClass(WebGL2PipelineState, [{
          key: "gpuPipelineState",
          get: function get() {
            return this._gpuPipelineState;
          }
        }]);
        return WebGL2PipelineState;
      }(PipelineState);

      var WebGL2PrimaryCommandBuffer = function (_WebGL2CommandBuffer) {
        _inheritsLoose(WebGL2PrimaryCommandBuffer, _WebGL2CommandBuffer);
        function WebGL2PrimaryCommandBuffer() {
          return _WebGL2CommandBuffer.apply(this, arguments) || this;
        }
        var _proto = WebGL2PrimaryCommandBuffer.prototype;
        _proto.beginRenderPass = function beginRenderPass(renderPass, framebuffer, renderArea, clearColors, clearDepth, clearStencil) {
          WebGL2CmdFuncBeginRenderPass(WebGL2DeviceManager.instance, renderPass.gpuRenderPass, framebuffer.gpuFramebuffer, renderArea, clearColors, clearDepth, clearStencil);
          this._isInRenderPass = true;
        };
        _proto.draw = function draw(infoOrAssembler) {
          if (this._isInRenderPass) {
            if (this._isStateInvalied) {
              this.bindStates();
            }
            var info = 'drawInfo' in infoOrAssembler ? infoOrAssembler.drawInfo : infoOrAssembler;
            WebGL2CmdFuncDraw(WebGL2DeviceManager.instance, info);
            ++this._numDrawCalls;
            this._numInstances += info.instanceCount;
            var indexCount = info.indexCount || info.vertexCount;
            if (this._curGPUPipelineState) {
              var glPrimitive = this._curGPUPipelineState.glPrimitive;
              switch (glPrimitive) {
                case 0x0004:
                  {
                    this._numTris += indexCount / 3 * Math.max(info.instanceCount, 1);
                    break;
                  }
                case 0x0005:
                case 0x0006:
                  {
                    this._numTris += (indexCount - 2) * Math.max(info.instanceCount, 1);
                    break;
                  }
              }
            }
          } else {
            console.error('Command \'draw\' must be recorded inside a render pass.');
          }
        };
        _proto.setViewport = function setViewport(viewport) {
          var _WebGL2DeviceManager$ = WebGL2DeviceManager.instance,
            cache = _WebGL2DeviceManager$.stateCache,
            gl = _WebGL2DeviceManager$.gl;
          if (cache.viewport.left !== viewport.left || cache.viewport.top !== viewport.top || cache.viewport.width !== viewport.width || cache.viewport.height !== viewport.height) {
            gl.viewport(viewport.left, viewport.top, viewport.width, viewport.height);
            cache.viewport.left = viewport.left;
            cache.viewport.top = viewport.top;
            cache.viewport.width = viewport.width;
            cache.viewport.height = viewport.height;
          }
        };
        _proto.setScissor = function setScissor(scissor) {
          var _WebGL2DeviceManager$2 = WebGL2DeviceManager.instance,
            cache = _WebGL2DeviceManager$2.stateCache,
            gl = _WebGL2DeviceManager$2.gl;
          if (cache.scissorRect.x !== scissor.x || cache.scissorRect.y !== scissor.y || cache.scissorRect.width !== scissor.width || cache.scissorRect.height !== scissor.height) {
            gl.scissor(scissor.x, scissor.y, scissor.width, scissor.height);
            cache.scissorRect.x = scissor.x;
            cache.scissorRect.y = scissor.y;
            cache.scissorRect.width = scissor.width;
            cache.scissorRect.height = scissor.height;
          }
        };
        _proto.updateBuffer = function updateBuffer(buffer, data, size) {
          if (!this._isInRenderPass) {
            var gpuBuffer = buffer.gpuBuffer;
            if (gpuBuffer) {
              var buffSize;
              if (size !== undefined) {
                buffSize = size;
              } else if (buffer.usage & BufferUsageBit.INDIRECT) {
                buffSize = 0;
              } else {
                buffSize = data.byteLength;
              }
              WebGL2CmdFuncUpdateBuffer(WebGL2DeviceManager.instance, gpuBuffer, data, 0, buffSize);
            }
          } else {
            console.error('Command \'updateBuffer\' must be recorded outside a render pass.');
          }
        };
        _proto.copyBuffersToTexture = function copyBuffersToTexture(buffers, texture, regions) {
          if (!this._isInRenderPass) {
            var gpuTexture = texture.gpuTexture;
            if (gpuTexture) {
              WebGL2CmdFuncCopyBuffersToTexture(WebGL2DeviceManager.instance, buffers, gpuTexture, regions);
            }
          } else {
            console.error('Command \'copyBufferToTexture\' must be recorded outside a render pass.');
          }
        };
        _proto.execute = function execute(cmdBuffs, count) {
          for (var i = 0; i < count; ++i) {
            var webGL2CmdBuff = cmdBuffs[i];
            WebGL2CmdFuncExecuteCmds(WebGL2DeviceManager.instance, webGL2CmdBuff.cmdPackage);
            this._numDrawCalls += webGL2CmdBuff._numDrawCalls;
            this._numInstances += webGL2CmdBuff._numInstances;
            this._numTris += webGL2CmdBuff._numTris;
          }
        };
        _proto.bindStates = function bindStates() {
          WebGL2CmdFuncBindStates(WebGL2DeviceManager.instance, this._curGPUPipelineState, this._curGPUInputAssembler, this._curGPUDescriptorSets, this._curDynamicOffsets, this._curDynamicStates);
          this._isStateInvalied = false;
        };
        _proto.blitTexture = function blitTexture(srcTexture, dstTexture, regions, filter) {
          var gpuTextureSrc = srcTexture.gpuTexture;
          var gpuTextureDst = dstTexture.gpuTexture;
          WebGL2CmdFuncBlitTexture(WebGL2DeviceManager.instance, gpuTextureSrc, gpuTextureDst, regions, filter);
        };
        return WebGL2PrimaryCommandBuffer;
      }(WebGL2CommandBuffer);

      var WebGL2Queue = function (_Queue) {
        _inheritsLoose(WebGL2Queue, _Queue);
        function WebGL2Queue() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Queue.call.apply(_Queue, [this].concat(args)) || this;
          _this.numDrawCalls = 0;
          _this.numInstances = 0;
          _this.numTris = 0;
          return _this;
        }
        var _proto = WebGL2Queue.prototype;
        _proto.initialize = function initialize(info) {
          this._type = info.type;
        };
        _proto.destroy = function destroy() {};
        _proto.submit = function submit(cmdBuffs) {
          for (var i = 0; i < cmdBuffs.length; i++) {
            var cmdBuff = cmdBuffs[i];
            this.numDrawCalls += cmdBuff.numDrawCalls;
            this.numInstances += cmdBuff.numInstances;
            this.numTris += cmdBuff.numTris;
          }
        };
        _proto.clear = function clear() {
          this.numDrawCalls = 0;
          this.numInstances = 0;
          this.numTris = 0;
        };
        return WebGL2Queue;
      }(Queue);

      var WebGL2RenderPass = function (_RenderPass) {
        _inheritsLoose(WebGL2RenderPass, _RenderPass);
        function WebGL2RenderPass() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _RenderPass.call.apply(_RenderPass, [this].concat(args)) || this;
          _this._gpuRenderPass = null;
          return _this;
        }
        var _proto = WebGL2RenderPass.prototype;
        _proto.initialize = function initialize(info) {
          this._colorInfos = info.colorAttachments;
          this._depthStencilInfo = info.depthStencilAttachment;
          this._subpasses = info.subpasses;
          this._gpuRenderPass = {
            colorAttachments: this._colorInfos,
            depthStencilAttachment: this._depthStencilInfo
          };
          this._hash = this.computeHash();
        };
        _proto.destroy = function destroy() {
          this._gpuRenderPass = null;
        };
        _createClass(WebGL2RenderPass, [{
          key: "gpuRenderPass",
          get: function get() {
            return this._gpuRenderPass;
          }
        }]);
        return WebGL2RenderPass;
      }(RenderPass);

      var WebGL2Sampler = function (_Sampler) {
        _inheritsLoose(WebGL2Sampler, _Sampler);
        function WebGL2Sampler(info, hash) {
          var _this;
          _this = _Sampler.call(this, info, hash) || this;
          _this._gpuSampler = null;
          _this._gpuSampler = {
            glSamplers: new Map(),
            minFilter: _this._info.minFilter,
            magFilter: _this._info.magFilter,
            mipFilter: _this._info.mipFilter,
            addressU: _this._info.addressU,
            addressV: _this._info.addressV,
            addressW: _this._info.addressW,
            glMinFilter: 0,
            glMagFilter: 0,
            glWrapS: 0,
            glWrapT: 0,
            glWrapR: 0,
            getGLSampler: function getGLSampler(device, minLod, maxLod) {
              var gl = device.gl;
              var samplerHash = minLod << 16 | maxLod;
              if (!this.glSamplers.has(samplerHash)) {
                var glSampler = gl.createSampler();
                if (glSampler) {
                  this.glSamplers.set(samplerHash, glSampler);
                  gl.samplerParameteri(glSampler, gl.TEXTURE_MIN_FILTER, this.glMinFilter);
                  gl.samplerParameteri(glSampler, gl.TEXTURE_MAG_FILTER, this.glMagFilter);
                  gl.samplerParameteri(glSampler, gl.TEXTURE_WRAP_S, this.glWrapS);
                  gl.samplerParameteri(glSampler, gl.TEXTURE_WRAP_T, this.glWrapT);
                  gl.samplerParameteri(glSampler, gl.TEXTURE_WRAP_R, this.glWrapR);
                  gl.samplerParameterf(glSampler, gl.TEXTURE_MIN_LOD, minLod);
                  gl.samplerParameterf(glSampler, gl.TEXTURE_MAX_LOD, maxLod);
                }
              }
              var sampler = this.glSamplers.get(samplerHash);
              return sampler;
            }
          };
          WebGL2CmdFuncPrepareSamplerInfo(WebGL2DeviceManager.instance, _this._gpuSampler);
          return _this;
        }
        var _proto = WebGL2Sampler.prototype;
        _proto.destroy = function destroy() {
          if (this._gpuSampler) {
            WebGL2CmdFuncDestroySampler(WebGL2DeviceManager.instance, this._gpuSampler);
            this._gpuSampler = null;
          }
        };
        _createClass(WebGL2Sampler, [{
          key: "gpuSampler",
          get: function get() {
            return this._gpuSampler;
          }
        }]);
        return WebGL2Sampler;
      }(Sampler);

      var WebGL2Shader = function (_Shader) {
        _inheritsLoose(WebGL2Shader, _Shader);
        function WebGL2Shader() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Shader.call.apply(_Shader, [this].concat(args)) || this;
          _this._gpuShader = null;
          return _this;
        }
        var _proto = WebGL2Shader.prototype;
        _proto.initialize = function initialize(info) {
          this._name = info.name;
          this._stages = info.stages;
          this._attributes = info.attributes;
          this._blocks = info.blocks;
          this._samplers = info.samplers;
          this._gpuShader = {
            name: info.name,
            blocks: info.blocks.slice(),
            samplerTextures: info.samplerTextures.slice(),
            subpassInputs: info.subpassInputs.slice(),
            gpuStages: new Array(info.stages.length),
            glProgram: null,
            glInputs: [],
            glUniforms: [],
            glBlocks: [],
            glSamplerTextures: []
          };
          for (var i = 0; i < info.stages.length; ++i) {
            var stage = info.stages[i];
            this._gpuShader.gpuStages[i] = {
              type: stage.stage,
              source: stage.source,
              glShader: null
            };
          }
        };
        _proto.destroy = function destroy() {
          if (this._gpuShader) {
            WebGL2CmdFuncDestroyShader(WebGL2DeviceManager.instance, this._gpuShader);
            this._gpuShader = null;
          }
        };
        _createClass(WebGL2Shader, [{
          key: "gpuShader",
          get: function get() {
            if (this._gpuShader.glProgram === null) {
              WebGL2CmdFuncCreateShader(WebGL2DeviceManager.instance, this._gpuShader);
            }
            return this._gpuShader;
          }
        }]);
        return WebGL2Shader;
      }(Shader);

      var WebGL2StateCache = function () {
        function WebGL2StateCache() {
          this.glArrayBuffer = null;
          this.glElementArrayBuffer = null;
          this.glUniformBuffer = null;
          this.glBindUBOs = [];
          this.glBindUBOOffsets = [];
          this.glVAO = null;
          this.texUnit = 0;
          this.glTexUnits = [];
          this.glSamplerUnits = [];
          this.glRenderbuffer = null;
          this.glFramebuffer = null;
          this.glReadFramebuffer = null;
          this.viewport = new Viewport();
          this.scissorRect = new Rect(0, 0, 0, 0);
          this.rs = new RasterizerState();
          this.dss = new DepthStencilState();
          this.bs = new BlendState();
          this.glProgram = null;
          this.glEnabledAttribLocs = [];
          this.glCurrentAttribLocs = [];
          this.texUnitCacheMap = {};
        }
        var _proto = WebGL2StateCache.prototype;
        _proto.initialize = function initialize(texUnit, bufferBindings, vertexAttributes) {
          for (var i = 0; i < texUnit; ++i) this.glTexUnits.push({
            glTexture: null
          });
          this.glSamplerUnits.length = texUnit;
          this.glSamplerUnits.fill(null);
          this.glBindUBOs.length = bufferBindings;
          this.glBindUBOs.fill(null);
          this.glBindUBOOffsets.length = bufferBindings;
          this.glBindUBOOffsets.fill(0);
          this.glEnabledAttribLocs.length = vertexAttributes;
          this.glEnabledAttribLocs.fill(false);
          this.glCurrentAttribLocs.length = vertexAttributes;
          this.glCurrentAttribLocs.fill(false);
        };
        return WebGL2StateCache;
      }();

      var WebGL2Texture = function (_Texture) {
        _inheritsLoose(WebGL2Texture, _Texture);
        function WebGL2Texture() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Texture.call.apply(_Texture, [this].concat(args)) || this;
          _this._gpuTexture = null;
          _this._gpuTextureView = null;
          return _this;
        }
        var _proto = WebGL2Texture.prototype;
        _proto.initialize = function initialize(info, isSwapchainTexture) {
          var texInfo = info;
          var viewInfo = info;
          if ('texture' in info) {
            texInfo = viewInfo.texture.info;
            this._isTextureView = true;
          }
          this._info.copy(texInfo);
          this._isPowerOf2 = IsPowerOf2(this._info.width) && IsPowerOf2(this._info.height);
          this._size = FormatSurfaceSize(this._info.format, this.width, this.height, this.depth, this._info.levelCount) * this._info.layerCount;
          if (!this._isTextureView) {
            this._gpuTexture = {
              type: texInfo.type,
              format: texInfo.format,
              usage: texInfo.usage,
              width: texInfo.width,
              height: texInfo.height,
              depth: texInfo.depth,
              size: this._size,
              arrayLayer: texInfo.layerCount,
              mipLevel: texInfo.levelCount,
              samples: texInfo.samples,
              flags: texInfo.flags,
              isPowerOf2: this._isPowerOf2,
              glTarget: 0,
              glInternalFmt: 0,
              glFormat: 0,
              glType: 0,
              glUsage: 0,
              glTexture: null,
              glRenderbuffer: null,
              glWrapS: 0,
              glWrapT: 0,
              glMinFilter: 0,
              glMagFilter: 0,
              isSwapchainTexture: isSwapchainTexture || false
            };
            if (!this._gpuTexture.isSwapchainTexture && this._gpuTexture) {
              WebGL2CmdFuncCreateTexture(WebGL2DeviceManager.instance, this._gpuTexture);
              WebGL2DeviceManager.instance.memoryStatus.textureSize += this._size;
            }
            this._viewInfo.texture = this;
            this._viewInfo.type = info.type;
            this._viewInfo.format = info.format;
            this._viewInfo.baseLevel = 0;
            this._viewInfo.levelCount = info.levelCount;
            this._viewInfo.baseLayer = 0;
            this._viewInfo.layerCount = info.layerCount;
            this._gpuTextureView = {
              gpuTexture: this._gpuTexture,
              type: this._viewInfo.type,
              format: this._viewInfo.format,
              baseLevel: this._viewInfo.baseLevel,
              levelCount: this._viewInfo.levelCount
            };
          } else {
            var _this$_gpuTexture;
            this._viewInfo.copy(viewInfo);
            this._gpuTexture = viewInfo.texture._gpuTexture;
            if (((_this$_gpuTexture = this._gpuTexture) === null || _this$_gpuTexture === void 0 ? void 0 : _this$_gpuTexture.format) !== texInfo.format) {
              console.log('GPU memory alias is not supported');
              return;
            }
            this._gpuTextureView = {
              gpuTexture: this._gpuTexture,
              type: viewInfo.type,
              format: viewInfo.format,
              baseLevel: viewInfo.baseLevel,
              levelCount: viewInfo.levelCount
            };
          }
        };
        _proto.destroy = function destroy() {
          if (!this._isTextureView && this._gpuTexture) {
            WebGL2CmdFuncDestroyTexture(WebGL2DeviceManager.instance, this._gpuTexture);
            WebGL2DeviceManager.instance.memoryStatus.textureSize -= this._size;
            this._gpuTexture = null;
          }
        };
        _proto.getGLTextureHandle = function getGLTextureHandle() {
          var gpuTexture = this._gpuTexture;
          if (!gpuTexture) {
            return 0;
          }
          if (gpuTexture.glTexture) {
            return gpuTexture.glTexture;
          } else if (gpuTexture.glRenderbuffer) {
            return gpuTexture.glRenderbuffer;
          }
          return 0;
        };
        _proto.resize = function resize(width, height) {
          if (this._info.width === width && this._info.height === height) {
            return;
          }
          if (this._info.levelCount === WebGL2Texture.getLevelCount(this._info.width, this._info.height)) {
            this._info.levelCount = WebGL2Texture.getLevelCount(width, height);
          } else if (this._info.levelCount > 1) {
            this._info.levelCount = Math.min(this._info.levelCount, WebGL2Texture.getLevelCount(width, height));
          }
          var oldSize = this._size;
          this._info.width = width;
          this._info.height = height;
          this._size = FormatSurfaceSize(this._info.format, this.width, this.height, this.depth, this._info.levelCount) * this._info.layerCount;
          if (!this._isTextureView && this._gpuTexture) {
            this._gpuTexture.width = width;
            this._gpuTexture.height = height;
            this._gpuTexture.size = this._size;
            if (!this._gpuTexture.isSwapchainTexture) {
              WebGL2CmdFuncResizeTexture(WebGL2DeviceManager.instance, this._gpuTexture);
              WebGL2DeviceManager.instance.memoryStatus.textureSize -= oldSize;
              WebGL2DeviceManager.instance.memoryStatus.textureSize += this._size;
            }
          }
        };
        _proto.initAsSwapchainTexture = function initAsSwapchainTexture(info) {
          var texInfo = new TextureInfo();
          texInfo.format = info.format;
          texInfo.usage = FormatInfos[info.format].hasDepth ? TextureUsageBit.DEPTH_STENCIL_ATTACHMENT : TextureUsageBit.COLOR_ATTACHMENT;
          texInfo.width = info.width;
          texInfo.height = info.height;
          this.initialize(texInfo, true);
        };
        _createClass(WebGL2Texture, [{
          key: "gpuTexture",
          get: function get() {
            return this._gpuTexture;
          }
        }, {
          key: "gpuTextureView",
          get: function get() {
            return this._gpuTextureView;
          }
        }]);
        return WebGL2Texture;
      }(Texture);

      var eventWebGLContextLost = 'webglcontextlost';
      function initStates(gl) {
        gl.activeTexture(gl.TEXTURE0);
        gl.pixelStorei(gl.PACK_ALIGNMENT, 1);
        gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
        gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false);
        gl.bindFramebuffer(gl.FRAMEBUFFER, null);
        gl.enable(gl.SCISSOR_TEST);
        gl.enable(gl.CULL_FACE);
        gl.cullFace(gl.BACK);
        gl.frontFace(gl.CCW);
        gl.polygonOffset(0.0, 0.0);
        gl.enable(gl.DEPTH_TEST);
        gl.depthMask(true);
        gl.depthFunc(gl.LESS);
        gl.stencilFuncSeparate(gl.FRONT, gl.ALWAYS, 1, 0xffff);
        gl.stencilOpSeparate(gl.FRONT, gl.KEEP, gl.KEEP, gl.KEEP);
        gl.stencilMaskSeparate(gl.FRONT, 0xffff);
        gl.stencilFuncSeparate(gl.BACK, gl.ALWAYS, 1, 0xffff);
        gl.stencilOpSeparate(gl.BACK, gl.KEEP, gl.KEEP, gl.KEEP);
        gl.stencilMaskSeparate(gl.BACK, 0xffff);
        gl.disable(gl.STENCIL_TEST);
        gl.disable(gl.SAMPLE_ALPHA_TO_COVERAGE);
        gl.disable(gl.BLEND);
        gl.blendEquationSeparate(gl.FUNC_ADD, gl.FUNC_ADD);
        gl.blendFuncSeparate(gl.ONE, gl.ZERO, gl.ONE, gl.ZERO);
        gl.colorMask(true, true, true, true);
        gl.blendColor(0.0, 0.0, 0.0, 0.0);
      }
      function getExtension(gl, ext) {
        var prefixes = ['', 'WEBKIT_', 'MOZ_'];
        for (var i = 0; i < prefixes.length; ++i) {
          var _ext = gl.getExtension(prefixes[i] + ext);
          if (_ext) {
            return _ext;
          }
        }
        return null;
      }
      function getExtensions(gl) {
        var res = {
          EXT_texture_filter_anisotropic: getExtension(gl, 'EXT_texture_filter_anisotropic'),
          EXT_color_buffer_half_float: getExtension(gl, 'EXT_color_buffer_half_float'),
          EXT_color_buffer_float: getExtension(gl, 'EXT_color_buffer_float'),
          WEBGL_compressed_texture_etc1: getExtension(gl, 'WEBGL_compressed_texture_etc1'),
          WEBGL_compressed_texture_etc: getExtension(gl, 'WEBGL_compressed_texture_etc'),
          WEBGL_compressed_texture_pvrtc: getExtension(gl, 'WEBGL_compressed_texture_pvrtc'),
          WEBGL_compressed_texture_astc: getExtension(gl, 'WEBGL_compressed_texture_astc'),
          WEBGL_compressed_texture_s3tc: getExtension(gl, 'WEBGL_compressed_texture_s3tc'),
          WEBGL_compressed_texture_s3tc_srgb: getExtension(gl, 'WEBGL_compressed_texture_s3tc_srgb'),
          WEBGL_debug_shaders: getExtension(gl, 'WEBGL_debug_shaders'),
          WEBGL_lose_context: getExtension(gl, 'WEBGL_lose_context'),
          WEBGL_debug_renderer_info: getExtension(gl, 'WEBGL_debug_renderer_info'),
          OES_texture_half_float_linear: getExtension(gl, 'OES_texture_half_float_linear'),
          OES_texture_float_linear: getExtension(gl, 'OES_texture_float_linear'),
          WEBGL_multi_draw: null,
          useVAO: true
        };
        {
          if (systemInfo.os !== OS.ANDROID && systemInfo.os !== OS.IOS) {
            res.WEBGL_multi_draw = getExtension(gl, 'WEBGL_multi_draw');
          }
        }
        return res;
      }
      function getContext(canvas) {
        var context = null;
        try {
          var _globalThis$__globalX;
          if ((_globalThis$__globalX = globalThis.__globalXR) !== null && _globalThis$__globalX !== void 0 && _globalThis$__globalX.webxrCompatible) {
            var glAttribs = {
              alpha: macro.ENABLE_TRANSPARENT_CANVAS,
              antialias: EDITOR || macro.ENABLE_WEBGL_ANTIALIAS,
              depth: true,
              stencil: true,
              premultipliedAlpha: false,
              preserveDrawingBuffer: false,
              powerPreference: 'default',
              failIfMajorPerformanceCaveat: false,
              xrCompatible: true
            };
            context = canvas.getContext('webgl2', glAttribs);
            return context;
          }
          var webGLCtxAttribs = {
            alpha: macro.ENABLE_TRANSPARENT_CANVAS,
            antialias: EDITOR || macro.ENABLE_WEBGL_ANTIALIAS,
            depth: true,
            stencil: true,
            premultipliedAlpha: false,
            preserveDrawingBuffer: false,
            powerPreference: 'default',
            failIfMajorPerformanceCaveat: false
          };
          context = canvas.getContext('webgl2', webGLCtxAttribs);
        } catch (err) {
          return null;
        }
        return context;
      }
      var WebGL2Swapchain = function (_Swapchain) {
        _inheritsLoose(WebGL2Swapchain, _Swapchain);
        function WebGL2Swapchain() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Swapchain.call.apply(_Swapchain, [this].concat(args)) || this;
          _this.stateCache = new WebGL2StateCache();
          _this.nullTex2D = null;
          _this.nullTexCube = null;
          _this._canvas = null;
          _this._webGL2ContextLostHandler = null;
          _this._extensions = null;
          _this._blitManager = null;
          return _this;
        }
        var _proto = WebGL2Swapchain.prototype;
        _proto.initialize = function initialize(info) {
          this._canvas = info.windowHandle;
          this._webGL2ContextLostHandler = this._onWebGLContextLost.bind(this);
          this._canvas.addEventListener(eventWebGLContextLost, this._onWebGLContextLost);
          var gl = WebGL2DeviceManager.instance.gl;
          this.stateCache.initialize(WebGL2DeviceManager.instance.capabilities.maxTextureUnits, WebGL2DeviceManager.instance.capabilities.maxUniformBufferBindings, WebGL2DeviceManager.instance.capabilities.maxVertexAttributes);
          this._extensions = getExtensions(gl);
          initStates(gl);
          var colorFmt = Format.RGBA8;
          var depthStencilFmt = Format.DEPTH_STENCIL;
          var depthBits = gl.getParameter(gl.DEPTH_BITS);
          var stencilBits = gl.getParameter(gl.STENCIL_BITS);
          if (depthBits && stencilBits) depthStencilFmt = Format.DEPTH_STENCIL;else if (depthBits) depthStencilFmt = Format.DEPTH;
          this._colorTexture = new WebGL2Texture();
          this._colorTexture.initAsSwapchainTexture({
            swapchain: this,
            format: colorFmt,
            width: info.width,
            height: info.height
          });
          this._depthStencilTexture = new WebGL2Texture();
          this._depthStencilTexture.initAsSwapchainTexture({
            swapchain: this,
            format: depthStencilFmt,
            width: info.width,
            height: info.height
          });
          this.nullTex2D = WebGL2DeviceManager.instance.createTexture(new TextureInfo(TextureType.TEX2D, TextureUsageBit.SAMPLED, Format.RGBA8, 2, 2, TextureFlagBit.NONE));
          this.nullTexCube = WebGL2DeviceManager.instance.createTexture(new TextureInfo(TextureType.CUBE, TextureUsageBit.SAMPLED, Format.RGBA8, 2, 2, TextureFlagBit.NONE, 6));
          var nullTexRegion = new BufferTextureCopy();
          nullTexRegion.texExtent.width = 2;
          nullTexRegion.texExtent.height = 2;
          var nullTexBuff = new Uint8Array(this.nullTex2D.size);
          nullTexBuff.fill(0);
          WebGL2DeviceManager.instance.copyBuffersToTexture([nullTexBuff], this.nullTex2D, [nullTexRegion]);
          nullTexRegion.texSubres.layerCount = 6;
          WebGL2DeviceManager.instance.copyBuffersToTexture([nullTexBuff, nullTexBuff, nullTexBuff, nullTexBuff, nullTexBuff, nullTexBuff], this.nullTexCube, [nullTexRegion]);
          this._blitManager = new IWebGL2BlitManager();
        };
        _proto.destroy = function destroy() {
          if (this._canvas && this._webGL2ContextLostHandler) {
            this._canvas.removeEventListener(eventWebGLContextLost, this._webGL2ContextLostHandler);
            this._webGL2ContextLostHandler = null;
          }
          if (this.nullTex2D) {
            this.nullTex2D.destroy();
            this.nullTex2D = null;
          }
          if (this.nullTexCube) {
            this.nullTexCube.destroy();
            this.nullTexCube = null;
          }
          if (this._blitManager) {
            this._blitManager.destroy();
            this._blitManager = null;
          }
          this._extensions = null;
          this._canvas = null;
        };
        _proto.resize = function resize(width, height, surfaceTransform) {
          if (this._colorTexture.width !== width || this._colorTexture.height !== height) {
            debug("Resizing swapchain: " + width + "x" + height);
            this._canvas.width = width;
            this._canvas.height = height;
            this._colorTexture.resize(width, height);
            this._depthStencilTexture.resize(width, height);
          }
        };
        _proto._onWebGLContextLost = function _onWebGLContextLost(event) {
          warnID(11000);
          warn(event);
        };
        _createClass(WebGL2Swapchain, [{
          key: "extensions",
          get: function get() {
            return this._extensions;
          }
        }, {
          key: "blitManager",
          get: function get() {
            return this._blitManager;
          }
        }]);
        return WebGL2Swapchain;
      }(Swapchain);

      var WebGL2Device = exports('eG', function (_Device) {
        _inheritsLoose(WebGL2Device, _Device);
        function WebGL2Device() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Device.call.apply(_Device, [this].concat(args)) || this;
          _this._swapchain = null;
          _this._context = null;
          _this._bindingMappings = null;
          _this._textureExclusive = new Array(Format.COUNT);
          return _this;
        }
        var _proto = WebGL2Device.prototype;
        _proto.initialize = function initialize(info) {
          WebGL2DeviceManager.setInstance(this);
          this._gfxAPI = API.WEBGL2;
          var mapping = this._bindingMappingInfo = info.bindingMappingInfo;
          var blockOffsets = [];
          var samplerTextureOffsets = [];
          var firstSet = mapping.setIndices[0];
          blockOffsets[firstSet] = 0;
          samplerTextureOffsets[firstSet] = 0;
          for (var i = 1; i < mapping.setIndices.length; ++i) {
            var curSet = mapping.setIndices[i];
            var prevSet = mapping.setIndices[i - 1];
            blockOffsets[curSet] = mapping.maxBlockCounts[prevSet] + blockOffsets[prevSet];
            samplerTextureOffsets[curSet] = mapping.maxSamplerTextureCounts[prevSet] + samplerTextureOffsets[prevSet];
          }
          for (var _i = 0; _i < mapping.setIndices.length; ++_i) {
            var _curSet = mapping.setIndices[_i];
            samplerTextureOffsets[_curSet] -= mapping.maxBlockCounts[_curSet];
          }
          this._bindingMappings = {
            blockOffsets: blockOffsets,
            samplerTextureOffsets: samplerTextureOffsets,
            flexibleSet: mapping.setIndices[mapping.setIndices.length - 1]
          };
          var gl = this._context = getContext(Device.canvas);
          if (!gl) {
            console.error('This device does not support WebGL2.');
            return false;
          }
          this._queue = this.createQueue(new QueueInfo(QueueType.GRAPHICS));
          this._cmdBuff = this.createCommandBuffer(new CommandBufferInfo(this._queue));
          this._caps.maxVertexAttributes = gl.getParameter(gl.MAX_VERTEX_ATTRIBS);
          this._caps.maxVertexUniformVectors = gl.getParameter(gl.MAX_VERTEX_UNIFORM_VECTORS);
          if (systemInfo.os === OS.IOS) {
            var maxVertexUniformVectors = this._caps.maxVertexUniformVectors;
            if (sys.browserType === BrowserType.WECHAT) {
              this._caps.maxVertexUniformVectors = maxVertexUniformVectors < 256 ? maxVertexUniformVectors : 256;
            } else if (sys.browserType === BrowserType.SAFARI) {
              this._caps.maxVertexUniformVectors = maxVertexUniformVectors < 512 ? maxVertexUniformVectors : 512;
            }
          }
          this._caps.maxFragmentUniformVectors = gl.getParameter(gl.MAX_FRAGMENT_UNIFORM_VECTORS);
          this._caps.maxTextureUnits = gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS);
          this._caps.maxVertexTextureUnits = gl.getParameter(gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
          this._caps.maxUniformBufferBindings = gl.getParameter(gl.MAX_UNIFORM_BUFFER_BINDINGS);
          this._caps.maxUniformBlockSize = gl.getParameter(gl.MAX_UNIFORM_BLOCK_SIZE);
          this._caps.maxTextureSize = gl.getParameter(gl.MAX_TEXTURE_SIZE);
          this._caps.maxCubeMapTextureSize = gl.getParameter(gl.MAX_CUBE_MAP_TEXTURE_SIZE);
          this._caps.maxArrayTextureLayers = gl.getParameter(gl.MAX_ARRAY_TEXTURE_LAYERS);
          this._caps.max3DTextureSize = gl.getParameter(gl.MAX_3D_TEXTURE_SIZE);
          this._caps.uboOffsetAlignment = gl.getParameter(gl.UNIFORM_BUFFER_OFFSET_ALIGNMENT);
          var extensions = gl.getSupportedExtensions();
          var extStr = '';
          if (extensions) {
            for (var _iterator = _createForOfIteratorHelperLoose(extensions), _step; !(_step = _iterator()).done;) {
              var ext = _step.value;
              extStr += ext + " ";
            }
          }
          var exts = getExtensions(gl);
          if (exts.WEBGL_debug_renderer_info) {
            this._renderer = gl.getParameter(exts.WEBGL_debug_renderer_info.UNMASKED_RENDERER_WEBGL);
            this._vendor = gl.getParameter(exts.WEBGL_debug_renderer_info.UNMASKED_VENDOR_WEBGL);
          } else {
            this._renderer = gl.getParameter(gl.RENDERER);
            this._vendor = gl.getParameter(gl.VENDOR);
          }
          var version = gl.getParameter(gl.VERSION);
          this._features.fill(false);
          this.initFormatFeatures(exts);
          this._features[Feature.ELEMENT_INDEX_UINT] = true;
          this._features[Feature.INSTANCED_ARRAYS] = true;
          this._features[Feature.MULTIPLE_RENDER_TARGETS] = true;
          this._features[Feature.BLEND_MINMAX] = true;
          var compressedFormat = '';
          if (this.getFormatFeatures(Format.ETC_RGB8)) {
            compressedFormat += 'etc1 ';
          }
          if (this.getFormatFeatures(Format.ETC2_RGB8)) {
            compressedFormat += 'etc2 ';
          }
          if (this.getFormatFeatures(Format.BC1)) {
            compressedFormat += 'dxt ';
          }
          if (this.getFormatFeatures(Format.PVRTC_RGB2)) {
            compressedFormat += 'pvrtc ';
          }
          if (this.getFormatFeatures(Format.ASTC_RGBA_4X4)) {
            compressedFormat += 'astc ';
          }
          debug('WebGL2 device initialized.');
          debug("RENDERER: " + this._renderer);
          debug("VENDOR: " + this._vendor);
          debug("VERSION: " + version);
          debug("COMPRESSED_FORMAT: " + compressedFormat);
          debug("EXTENSIONS: " + extStr);
          return true;
        };
        _proto.destroy = function destroy() {
          if (this._queue) {
            this._queue.destroy();
            this._queue = null;
          }
          if (this._cmdBuff) {
            this._cmdBuff.destroy();
            this._cmdBuff = null;
          }
          var it = this._samplers.values();
          var res = it.next();
          while (!res.done) {
            res.value.destroy();
            res = it.next();
          }
          this._swapchain = null;
        };
        _proto.flushCommands = function flushCommands(cmdBuffs) {};
        _proto.acquire = function acquire(swapchains) {};
        _proto.present = function present() {
          var queue = this._queue;
          this._numDrawCalls = queue.numDrawCalls;
          this._numInstances = queue.numInstances;
          this._numTris = queue.numTris;
          queue.clear();
        };
        _proto.initFormatFeatures = function initFormatFeatures(exts) {
          this._formatFeatures.fill(FormatFeatureBit.NONE);
          this._textureExclusive.fill(true);
          var tempFeature = FormatFeatureBit.RENDER_TARGET | FormatFeatureBit.SAMPLED_TEXTURE | FormatFeatureBit.STORAGE_TEXTURE | FormatFeatureBit.LINEAR_FILTER | FormatFeatureBit.VERTEX_ATTRIBUTE;
          this._formatFeatures[Format.R8] = tempFeature;
          this._formatFeatures[Format.RG8] = tempFeature;
          this._formatFeatures[Format.RGB8] = tempFeature;
          this._formatFeatures[Format.RGBA8] = tempFeature;
          tempFeature = FormatFeatureBit.RENDER_TARGET | FormatFeatureBit.SAMPLED_TEXTURE | FormatFeatureBit.STORAGE_TEXTURE | FormatFeatureBit.LINEAR_FILTER;
          this._formatFeatures[Format.R8SN] = tempFeature;
          this._formatFeatures[Format.RG8SN] = tempFeature;
          this._formatFeatures[Format.RGB8SN] = tempFeature;
          this._formatFeatures[Format.RGBA8SN] = tempFeature;
          this._formatFeatures[Format.R5G6B5] = tempFeature;
          this._formatFeatures[Format.RGBA4] = tempFeature;
          this._formatFeatures[Format.RGB5A1] = tempFeature;
          this._formatFeatures[Format.RGB10A2] = tempFeature;
          this._formatFeatures[Format.SRGB8] = tempFeature;
          this._formatFeatures[Format.SRGB8_A8] = tempFeature;
          this._formatFeatures[Format.R11G11B10F] = tempFeature;
          this._formatFeatures[Format.RGB9E5] = tempFeature;
          this._formatFeatures[Format.DEPTH] = tempFeature;
          this._formatFeatures[Format.DEPTH_STENCIL] = tempFeature;
          this._formatFeatures[Format.RGB10A2UI] = FormatFeatureBit.RENDER_TARGET | FormatFeatureBit.STORAGE_TEXTURE | FormatFeatureBit.SAMPLED_TEXTURE | FormatFeatureBit.LINEAR_FILTER;
          tempFeature = FormatFeatureBit.RENDER_TARGET | FormatFeatureBit.SAMPLED_TEXTURE | FormatFeatureBit.STORAGE_TEXTURE | FormatFeatureBit.VERTEX_ATTRIBUTE;
          this._formatFeatures[Format.R16F] = tempFeature;
          this._formatFeatures[Format.RG16F] = tempFeature;
          this._formatFeatures[Format.RGB16F] = tempFeature;
          this._formatFeatures[Format.RGBA16F] = tempFeature;
          tempFeature = FormatFeatureBit.STORAGE_TEXTURE | FormatFeatureBit.SAMPLED_TEXTURE | FormatFeatureBit.VERTEX_ATTRIBUTE;
          this._formatFeatures[Format.R32F] = tempFeature;
          this._formatFeatures[Format.RG32F] = tempFeature;
          this._formatFeatures[Format.RGB32F] = tempFeature;
          this._formatFeatures[Format.RGBA32F] = tempFeature;
          this._formatFeatures[Format.RGB10A2UI] = FormatFeatureBit.RENDER_TARGET | FormatFeatureBit.STORAGE_TEXTURE | FormatFeatureBit.SAMPLED_TEXTURE | FormatFeatureBit.LINEAR_FILTER;
          tempFeature = FormatFeatureBit.RENDER_TARGET | FormatFeatureBit.STORAGE_TEXTURE | FormatFeatureBit.SAMPLED_TEXTURE | FormatFeatureBit.LINEAR_FILTER | FormatFeatureBit.VERTEX_ATTRIBUTE;
          this._formatFeatures[Format.R8I] = tempFeature;
          this._formatFeatures[Format.R8UI] = tempFeature;
          this._formatFeatures[Format.R16I] = tempFeature;
          this._formatFeatures[Format.R16UI] = tempFeature;
          this._formatFeatures[Format.R32I] = tempFeature;
          this._formatFeatures[Format.R32UI] = tempFeature;
          this._formatFeatures[Format.RG8I] = tempFeature;
          this._formatFeatures[Format.RG8UI] = tempFeature;
          this._formatFeatures[Format.RG16I] = tempFeature;
          this._formatFeatures[Format.RG16UI] = tempFeature;
          this._formatFeatures[Format.RG32I] = tempFeature;
          this._formatFeatures[Format.RG32UI] = tempFeature;
          this._formatFeatures[Format.RGB8I] = tempFeature;
          this._formatFeatures[Format.RGB8UI] = tempFeature;
          this._formatFeatures[Format.RGB16I] = tempFeature;
          this._formatFeatures[Format.RGB16UI] = tempFeature;
          this._formatFeatures[Format.RGB32I] = tempFeature;
          this._formatFeatures[Format.RGB32UI] = tempFeature;
          this._formatFeatures[Format.RGBA8I] = tempFeature;
          this._formatFeatures[Format.RGBA8UI] = tempFeature;
          this._formatFeatures[Format.RGBA16I] = tempFeature;
          this._formatFeatures[Format.RGBA16UI] = tempFeature;
          this._formatFeatures[Format.RGBA32I] = tempFeature;
          this._formatFeatures[Format.RGBA32UI] = tempFeature;
          this._textureExclusive[Format.R8] = false;
          this._textureExclusive[Format.RG8] = false;
          this._textureExclusive[Format.RGB8] = false;
          this._textureExclusive[Format.R5G6B5] = false;
          this._textureExclusive[Format.RGBA4] = false;
          this._textureExclusive[Format.RGB5A1] = false;
          this._textureExclusive[Format.RGBA8] = false;
          this._textureExclusive[Format.RGB10A2] = false;
          this._textureExclusive[Format.RGB10A2UI] = false;
          this._textureExclusive[Format.SRGB8_A8] = false;
          this._textureExclusive[Format.R8I] = false;
          this._textureExclusive[Format.R8UI] = false;
          this._textureExclusive[Format.R16I] = false;
          this._textureExclusive[Format.R16UI] = false;
          this._textureExclusive[Format.R32I] = false;
          this._textureExclusive[Format.R32UI] = false;
          this._textureExclusive[Format.RG8I] = false;
          this._textureExclusive[Format.RG8UI] = false;
          this._textureExclusive[Format.RG16I] = false;
          this._textureExclusive[Format.RG16UI] = false;
          this._textureExclusive[Format.RG32I] = false;
          this._textureExclusive[Format.RG32UI] = false;
          this._textureExclusive[Format.RGBA8I] = false;
          this._textureExclusive[Format.RGBA8UI] = false;
          this._textureExclusive[Format.RGBA16I] = false;
          this._textureExclusive[Format.RGBA16UI] = false;
          this._textureExclusive[Format.RGBA32I] = false;
          this._textureExclusive[Format.RGBA32UI] = false;
          this._textureExclusive[Format.DEPTH] = false;
          this._textureExclusive[Format.DEPTH_STENCIL] = false;
          if (exts.EXT_color_buffer_float) {
            this._formatFeatures[Format.R32F] |= FormatFeatureBit.RENDER_TARGET;
            this._formatFeatures[Format.RG32F] |= FormatFeatureBit.RENDER_TARGET;
            this._formatFeatures[Format.RGBA32F] |= FormatFeatureBit.RENDER_TARGET;
            this._textureExclusive[Format.R32F] = false;
            this._textureExclusive[Format.RG32F] = false;
            this._textureExclusive[Format.RGBA32F] = false;
          }
          if (exts.EXT_color_buffer_half_float) {
            this._textureExclusive[Format.R16F] = false;
            this._textureExclusive[Format.RG16F] = false;
            this._textureExclusive[Format.RGBA16F] = false;
          }
          if (exts.OES_texture_float_linear) {
            this._formatFeatures[Format.RGB32F] |= FormatFeatureBit.LINEAR_FILTER;
            this._formatFeatures[Format.RGBA32F] |= FormatFeatureBit.LINEAR_FILTER;
            this._formatFeatures[Format.R32F] |= FormatFeatureBit.LINEAR_FILTER;
            this._formatFeatures[Format.RG32F] |= FormatFeatureBit.LINEAR_FILTER;
          }
          if (exts.OES_texture_half_float_linear) {
            this._formatFeatures[Format.RGB16F] |= FormatFeatureBit.LINEAR_FILTER;
            this._formatFeatures[Format.RGBA16F] |= FormatFeatureBit.LINEAR_FILTER;
            this._formatFeatures[Format.R16F] |= FormatFeatureBit.LINEAR_FILTER;
            this._formatFeatures[Format.RG16F] |= FormatFeatureBit.LINEAR_FILTER;
          }
          var compressedFeature = FormatFeatureBit.SAMPLED_TEXTURE | FormatFeatureBit.LINEAR_FILTER;
          if (exts.WEBGL_compressed_texture_etc1) {
            this._formatFeatures[Format.ETC_RGB8] = compressedFeature;
          }
          if (exts.WEBGL_compressed_texture_etc) {
            this._formatFeatures[Format.ETC2_RGB8] = compressedFeature;
            this._formatFeatures[Format.ETC2_RGBA8] = compressedFeature;
            this._formatFeatures[Format.ETC2_SRGB8] = compressedFeature;
            this._formatFeatures[Format.ETC2_SRGB8_A8] = compressedFeature;
            this._formatFeatures[Format.ETC2_RGB8_A1] = compressedFeature;
            this._formatFeatures[Format.ETC2_SRGB8_A1] = compressedFeature;
          }
          if (exts.WEBGL_compressed_texture_s3tc) {
            this._formatFeatures[Format.BC1] = compressedFeature;
            this._formatFeatures[Format.BC1_ALPHA] = compressedFeature;
            this._formatFeatures[Format.BC1_SRGB] = compressedFeature;
            this._formatFeatures[Format.BC1_SRGB_ALPHA] = compressedFeature;
            this._formatFeatures[Format.BC2] = compressedFeature;
            this._formatFeatures[Format.BC2_SRGB] = compressedFeature;
            this._formatFeatures[Format.BC3] = compressedFeature;
            this._formatFeatures[Format.BC3_SRGB] = compressedFeature;
          }
          if (exts.WEBGL_compressed_texture_pvrtc) {
            this._formatFeatures[Format.PVRTC_RGB2] = compressedFeature;
            this._formatFeatures[Format.PVRTC_RGBA2] = compressedFeature;
            this._formatFeatures[Format.PVRTC_RGB4] = compressedFeature;
            this._formatFeatures[Format.PVRTC_RGBA4] = compressedFeature;
          }
          if (exts.WEBGL_compressed_texture_astc) {
            this._formatFeatures[Format.ASTC_RGBA_4X4] = compressedFeature;
            this._formatFeatures[Format.ASTC_RGBA_5X4] = compressedFeature;
            this._formatFeatures[Format.ASTC_RGBA_5X5] = compressedFeature;
            this._formatFeatures[Format.ASTC_RGBA_6X5] = compressedFeature;
            this._formatFeatures[Format.ASTC_RGBA_6X6] = compressedFeature;
            this._formatFeatures[Format.ASTC_RGBA_8X5] = compressedFeature;
            this._formatFeatures[Format.ASTC_RGBA_8X6] = compressedFeature;
            this._formatFeatures[Format.ASTC_RGBA_8X8] = compressedFeature;
            this._formatFeatures[Format.ASTC_RGBA_10X5] = compressedFeature;
            this._formatFeatures[Format.ASTC_RGBA_10X6] = compressedFeature;
            this._formatFeatures[Format.ASTC_RGBA_10X8] = compressedFeature;
            this._formatFeatures[Format.ASTC_RGBA_10X10] = compressedFeature;
            this._formatFeatures[Format.ASTC_RGBA_12X10] = compressedFeature;
            this._formatFeatures[Format.ASTC_RGBA_12X12] = compressedFeature;
            this._formatFeatures[Format.ASTC_SRGBA_4X4] = compressedFeature;
            this._formatFeatures[Format.ASTC_SRGBA_5X4] = compressedFeature;
            this._formatFeatures[Format.ASTC_SRGBA_5X5] = compressedFeature;
            this._formatFeatures[Format.ASTC_SRGBA_6X5] = compressedFeature;
            this._formatFeatures[Format.ASTC_SRGBA_6X6] = compressedFeature;
            this._formatFeatures[Format.ASTC_SRGBA_8X5] = compressedFeature;
            this._formatFeatures[Format.ASTC_SRGBA_8X6] = compressedFeature;
            this._formatFeatures[Format.ASTC_SRGBA_8X8] = compressedFeature;
            this._formatFeatures[Format.ASTC_SRGBA_10X5] = compressedFeature;
            this._formatFeatures[Format.ASTC_SRGBA_10X6] = compressedFeature;
            this._formatFeatures[Format.ASTC_SRGBA_10X8] = compressedFeature;
            this._formatFeatures[Format.ASTC_SRGBA_10X10] = compressedFeature;
            this._formatFeatures[Format.ASTC_SRGBA_12X10] = compressedFeature;
            this._formatFeatures[Format.ASTC_SRGBA_12X12] = compressedFeature;
          }
        };
        _proto.createCommandBuffer = function createCommandBuffer(info) {
          var Ctor = info.type === CommandBufferType.PRIMARY ? WebGL2PrimaryCommandBuffer : WebGL2CommandBuffer;
          var cmdBuff = new Ctor();
          cmdBuff.initialize(info);
          return cmdBuff;
        };
        _proto.createSwapchain = function createSwapchain(info) {
          var swapchain = new WebGL2Swapchain();
          this._swapchain = swapchain;
          swapchain.initialize(info);
          return swapchain;
        };
        _proto.createBuffer = function createBuffer(info) {
          var buffer = new WebGL2Buffer();
          buffer.initialize(info);
          return buffer;
        };
        _proto.createTexture = function createTexture(info) {
          var texture = new WebGL2Texture();
          texture.initialize(info);
          return texture;
        };
        _proto.createDescriptorSet = function createDescriptorSet(info) {
          var descriptorSet = new WebGL2DescriptorSet();
          descriptorSet.initialize(info);
          return descriptorSet;
        };
        _proto.createShader = function createShader(info) {
          var shader = new WebGL2Shader();
          shader.initialize(info);
          return shader;
        };
        _proto.createInputAssembler = function createInputAssembler(info) {
          var inputAssembler = new WebGL2InputAssembler();
          inputAssembler.initialize(info);
          return inputAssembler;
        };
        _proto.createRenderPass = function createRenderPass(info) {
          var renderPass = new WebGL2RenderPass();
          renderPass.initialize(info);
          return renderPass;
        };
        _proto.createFramebuffer = function createFramebuffer(info) {
          var framebuffer = new WebGL2Framebuffer();
          framebuffer.initialize(info);
          return framebuffer;
        };
        _proto.createDescriptorSetLayout = function createDescriptorSetLayout(info) {
          var descriptorSetLayout = new WebGL2DescriptorSetLayout();
          descriptorSetLayout.initialize(info);
          return descriptorSetLayout;
        };
        _proto.createPipelineLayout = function createPipelineLayout(info) {
          var pipelineLayout = new WebGL2PipelineLayout();
          pipelineLayout.initialize(info);
          return pipelineLayout;
        };
        _proto.createPipelineState = function createPipelineState(info) {
          var pipelineState = new WebGL2PipelineState();
          pipelineState.initialize(info);
          return pipelineState;
        };
        _proto.createQueue = function createQueue(info) {
          var queue = new WebGL2Queue();
          queue.initialize(info);
          return queue;
        };
        _proto.getSampler = function getSampler(info) {
          var hash = Sampler.computeHash(info);
          if (!this._samplers.has(hash)) {
            this._samplers.set(hash, new WebGL2Sampler(info, hash));
          }
          return this._samplers.get(hash);
        };
        _proto.getSwapchains = function getSwapchains() {
          return [this._swapchain];
        };
        _proto.getGeneralBarrier = function getGeneralBarrier(info) {
          var hash = GeneralBarrier.computeHash(info);
          if (!this._generalBarrierss.has(hash)) {
            this._generalBarrierss.set(hash, new GeneralBarrier(info, hash));
          }
          return this._generalBarrierss.get(hash);
        };
        _proto.getTextureBarrier = function getTextureBarrier(info) {
          var hash = TextureBarrier.computeHash(info);
          if (!this._textureBarriers.has(hash)) {
            this._textureBarriers.set(hash, new TextureBarrier(info, hash));
          }
          return this._textureBarriers.get(hash);
        };
        _proto.getBufferBarrier = function getBufferBarrier(info) {
          var hash = BufferBarrier.computeHash(info);
          if (!this._bufferBarriers.has(hash)) {
            this._bufferBarriers.set(hash, new BufferBarrier(info, hash));
          }
          return this._bufferBarriers.get(hash);
        };
        _proto.copyBuffersToTexture = function copyBuffersToTexture(buffers, texture, regions) {
          WebGL2CmdFuncCopyBuffersToTexture(this, buffers, texture.gpuTexture, regions);
        };
        _proto.copyTextureToBuffers = function copyTextureToBuffers(texture, buffers, regions) {
          WebGL2CmdFuncCopyTextureToBuffers(this, texture.gpuTexture, buffers, regions);
        };
        _proto.copyTexImagesToTexture = function copyTexImagesToTexture(texImages, texture, regions) {
          WebGL2CmdFuncCopyTexImagesToTexture(this, texImages, texture.gpuTexture, regions);
        };
        _createClass(WebGL2Device, [{
          key: "gl",
          get: function get() {
            return this._context;
          }
        }, {
          key: "extensions",
          get: function get() {
            return this._swapchain.extensions;
          }
        }, {
          key: "stateCache",
          get: function get() {
            return this._swapchain.stateCache;
          }
        }, {
          key: "nullTex2D",
          get: function get() {
            return this._swapchain.nullTex2D;
          }
        }, {
          key: "nullTexCube",
          get: function get() {
            return this._swapchain.nullTexCube;
          }
        }, {
          key: "textureExclusive",
          get: function get() {
            return this._textureExclusive;
          }
        }, {
          key: "bindingMappings",
          get: function get() {
            return this._bindingMappings;
          }
        }, {
          key: "blitManager",
          get: function get() {
            return this._swapchain.blitManager;
          }
        }]);
        return WebGL2Device;
      }(Device));

      legacyCC.WebGL2Device = WebGL2Device;

      function createCommonjsModule(fn, module) {
      	return module = { exports: {} }, fn(module, module.exports), module.exports;
      }

      function commonjsRequire () {
      	throw new Error('Dynamic requires are not currently supported by @rollup/plugin-commonjs');
      }

      var cannon = createCommonjsModule(function (module, exports) {
      // Tue, 20 Jul 2021 10:46:34 GMT

      /*
       * Copyright (c) 2015 cannon.js Authors
       *
       * Permission is hereby granted, free of charge, to any person
       * obtaining a copy of this software and associated documentation
       * files (the "Software"), to deal in the Software without
       * restriction, including without limitation the rights to use, copy,
       * modify, merge, publish, distribute, sublicense, and/or sell copies
       * of the Software, and to permit persons to whom the Software is
       * furnished to do so, subject to the following conditions:
       *
       * The above copyright notice and this permission notice shall be
       * included in all copies or substantial portions of the Software.
       *
       * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
       * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
       * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
       * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
       * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
       * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
       * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
       */

      !function(e){module.exports=e();}(function(){return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof commonjsRequire=="function"&&commonjsRequire;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r);}return n[o].exports}var i=typeof commonjsRequire=="function"&&commonjsRequire;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){
      module.exports={
        "name": "@cocos/cannon",
        "version": "1.2.8",
        "description": "A lightweight 3D physics engine written in JavaScript.",
        "homepage": "https://github.com/cocos-creator/cannon.js",
        "author": "Stefan Hedman <schteppe@gmail.com> (http://steffe.se), JayceLai",
        "keywords": [
          "cannon.js",
          "cocos",
          "creator",
          "physics",
          "engine",
          "3d"
        ],
        "scripts": {
          "build":"grunt && npm run preprocess && grunt addLicense && grunt addDate",
          "preprocess":"node node_modules/uglify-js/bin/uglifyjs build/cannon.js -o build/cannon.min.js -c -m",
          "postpublish": "cnpm sync @cocos/cannon"
        },
        "main": "./build/cannon.js",
        "engines": {
          "node": "*"
        },
        "repository": {
          "type": "git",
          "url": "https://github.com/cocos-creator/cannon.js.git"
        },
        "bugs": {
          "url": "https://github.com/cocos-creator/cannon.js/issues"
        },
        "licenses": [
          {
            "type": "MIT"
          }
        ],
        "devDependencies": {
          "jshint": "latest",
          "uglify-js": "latest",
          "nodeunit": "^0.9.0",
          "grunt": "~0.4.0",
          "grunt-contrib-jshint": "~0.1.1",
          "grunt-contrib-nodeunit": "^0.4.1",
          "grunt-contrib-concat": "~0.1.3",
          "grunt-contrib-uglify": "^0.5.1",
          "grunt-browserify": "^2.1.4",
          "grunt-contrib-yuidoc": "^0.5.2",
          "browserify": "*"
        },
        "dependencies": {}
      };

      },{}],2:[function(_dereq_,module,exports){
      // Export classes
      module.exports = {
          version :                       _dereq_('../package.json').version,

          AABB :                          _dereq_('./collision/AABB'),
          ArrayCollisionMatrix :          _dereq_('./collision/ArrayCollisionMatrix'),
          Body :                          _dereq_('./objects/Body'),
          Box :                           _dereq_('./shapes/Box'),
          Broadphase :                    _dereq_('./collision/Broadphase'),
          Constraint :                    _dereq_('./constraints/Constraint'),
          ContactEquation :               _dereq_('./equations/ContactEquation'),
          Narrowphase :                   _dereq_('./world/Narrowphase'),
          ConeTwistConstraint :           _dereq_('./constraints/ConeTwistConstraint'),
          ContactMaterial :               _dereq_('./material/ContactMaterial'),
          ConvexPolyhedron :              _dereq_('./shapes/ConvexPolyhedron'),
          Cylinder :                      _dereq_('./shapes/Cylinder'),
          DistanceConstraint :            _dereq_('./constraints/DistanceConstraint'),
          Equation :                      _dereq_('./equations/Equation'),
          EventTarget :                   _dereq_('./utils/EventTarget'),
          FrictionEquation :              _dereq_('./equations/FrictionEquation'),
          GSSolver :                      _dereq_('./solver/GSSolver'),
          GridBroadphase :                _dereq_('./collision/GridBroadphase'),
          Heightfield :                   _dereq_('./shapes/Heightfield'),
          HingeConstraint :               _dereq_('./constraints/HingeConstraint'),
          LockConstraint :                _dereq_('./constraints/LockConstraint'),
          Mat3 :                          _dereq_('./math/Mat3'),
          Material :                      _dereq_('./material/Material'),
          NaiveBroadphase :               _dereq_('./collision/NaiveBroadphase'),
          ObjectCollisionMatrix :         _dereq_('./collision/ObjectCollisionMatrix'),
          Pool :                          _dereq_('./utils/Pool'),
          Particle :                      _dereq_('./shapes/Particle'),
          Plane :                         _dereq_('./shapes/Plane'),
          PointToPointConstraint :        _dereq_('./constraints/PointToPointConstraint'),
          Quaternion :                    _dereq_('./math/Quaternion'),
          Ray :                           _dereq_('./collision/Ray'),
          RaycastVehicle :                _dereq_('./objects/RaycastVehicle'),
          RaycastResult :                 _dereq_('./collision/RaycastResult'),
          RigidVehicle :                  _dereq_('./objects/RigidVehicle'),
          RotationalEquation :            _dereq_('./equations/RotationalEquation'),
          RotationalMotorEquation :       _dereq_('./equations/RotationalMotorEquation'),
          SAPBroadphase :                 _dereq_('./collision/SAPBroadphase'),
          SPHSystem :                     _dereq_('./objects/SPHSystem'),
          Shape :                         _dereq_('./shapes/Shape'),
          Solver :                        _dereq_('./solver/Solver'),
          Sphere :                        _dereq_('./shapes/Sphere'),
          SplitSolver :                   _dereq_('./solver/SplitSolver'),
          Spring :                        _dereq_('./objects/Spring'),
          Transform :                     _dereq_('./math/Transform'),
          Trimesh :                       _dereq_('./shapes/Trimesh'),
          Vec3 :                          _dereq_('./math/Vec3'),
          Vec3Pool :                      _dereq_('./utils/Vec3Pool'),
          World :                         _dereq_('./world/World'),
          Octree :                        _dereq_('./utils/Octree'),
      };

      },{"../package.json":1,"./collision/AABB":3,"./collision/ArrayCollisionMatrix":4,"./collision/Broadphase":5,"./collision/GridBroadphase":6,"./collision/NaiveBroadphase":7,"./collision/ObjectCollisionMatrix":8,"./collision/Ray":10,"./collision/RaycastResult":11,"./collision/SAPBroadphase":12,"./constraints/ConeTwistConstraint":13,"./constraints/Constraint":14,"./constraints/DistanceConstraint":15,"./constraints/HingeConstraint":16,"./constraints/LockConstraint":17,"./constraints/PointToPointConstraint":18,"./equations/ContactEquation":20,"./equations/Equation":21,"./equations/FrictionEquation":22,"./equations/RotationalEquation":23,"./equations/RotationalMotorEquation":24,"./material/ContactMaterial":25,"./material/Material":26,"./math/Mat3":28,"./math/Quaternion":29,"./math/Transform":30,"./math/Vec3":31,"./objects/Body":32,"./objects/RaycastVehicle":33,"./objects/RigidVehicle":34,"./objects/SPHSystem":35,"./objects/Spring":36,"./shapes/Box":38,"./shapes/ConvexPolyhedron":39,"./shapes/Cylinder":40,"./shapes/Heightfield":41,"./shapes/Particle":42,"./shapes/Plane":43,"./shapes/Shape":44,"./shapes/Sphere":45,"./shapes/Trimesh":46,"./solver/GSSolver":47,"./solver/Solver":48,"./solver/SplitSolver":49,"./utils/EventTarget":50,"./utils/Octree":51,"./utils/Pool":52,"./utils/Vec3Pool":55,"./world/Narrowphase":56,"./world/World":57}],3:[function(_dereq_,module,exports){
      var Vec3 = _dereq_('../math/Vec3');
      _dereq_('../utils/Utils');

      module.exports = AABB;

      /**
       * Axis aligned bounding box class.
       * @class AABB
       * @constructor
       * @param {Object} [options]
       * @param {Vec3}   [options.upperBound]
       * @param {Vec3}   [options.lowerBound]
       */
      function AABB(options){
          options = options || {};

          /**
           * The lower bound of the bounding box.
           * @property lowerBound
           * @type {Vec3}
           */
          this.lowerBound = new Vec3();
          if(options.lowerBound){
              this.lowerBound.copy(options.lowerBound);
          }

          /**
           * The upper bound of the bounding box.
           * @property upperBound
           * @type {Vec3}
           */
          this.upperBound = new Vec3();
          if(options.upperBound){
              this.upperBound.copy(options.upperBound);
          }
      }

      var tmp = new Vec3();

      /**
       * Set the AABB bounds from a set of points.
       * @method setFromPoints
       * @param {Array} points An array of Vec3's.
       * @param {Vec3} position
       * @param {Quaternion} quaternion
       * @param {number} skinSize
       * @return {AABB} The self object
       */
      AABB.prototype.setFromPoints = function(points, position, quaternion, skinSize){
          var l = this.lowerBound,
              u = this.upperBound,
              q = quaternion;

          // Set to the first point
          l.copy(points[0]);
          if(q){
              q.vmult(l, l);
          }
          u.copy(l);

          for(var i = 1; i<points.length; i++){
              var p = points[i];

              if(q){
                  q.vmult(p, tmp);
                  p = tmp;
              }

              if(p.x > u.x){ u.x = p.x; }
              if(p.x < l.x){ l.x = p.x; }
              if(p.y > u.y){ u.y = p.y; }
              if(p.y < l.y){ l.y = p.y; }
              if(p.z > u.z){ u.z = p.z; }
              if(p.z < l.z){ l.z = p.z; }
          }

          // Add offset
          if (position) {
              position.vadd(l, l);
              position.vadd(u, u);
          }

          if(skinSize){
              l.x -= skinSize;
              l.y -= skinSize;
              l.z -= skinSize;
              u.x += skinSize;
              u.y += skinSize;
              u.z += skinSize;
          }

          return this;
      };

      /**
       * Copy bounds from an AABB to this AABB
       * @method copy
       * @param  {AABB} aabb Source to copy from
       * @return {AABB} The this object, for chainability
       */
      AABB.prototype.copy = function(aabb){
          this.lowerBound.copy(aabb.lowerBound);
          this.upperBound.copy(aabb.upperBound);
          return this;
      };

      /**
       * Clone an AABB
       * @method clone
       */
      AABB.prototype.clone = function(){
          return new AABB().copy(this);
      };

      /**
       * Extend this AABB so that it covers the given AABB too.
       * @method extend
       * @param  {AABB} aabb
       */
      AABB.prototype.extend = function(aabb){
          this.lowerBound.x = Math.min(this.lowerBound.x, aabb.lowerBound.x);
          this.upperBound.x = Math.max(this.upperBound.x, aabb.upperBound.x);
          this.lowerBound.y = Math.min(this.lowerBound.y, aabb.lowerBound.y);
          this.upperBound.y = Math.max(this.upperBound.y, aabb.upperBound.y);
          this.lowerBound.z = Math.min(this.lowerBound.z, aabb.lowerBound.z);
          this.upperBound.z = Math.max(this.upperBound.z, aabb.upperBound.z);
      };

      /**
       * Returns true if the given AABB overlaps this AABB.
       * @method overlaps
       * @param  {AABB} aabb
       * @return {Boolean}
       */
      AABB.prototype.overlaps = function(aabb){
          var l1 = this.lowerBound,
              u1 = this.upperBound,
              l2 = aabb.lowerBound,
              u2 = aabb.upperBound;

          //      l2        u2
          //      |---------|
          // |--------|
          // l1       u1

          var overlapsX = ((l2.x <= u1.x && u1.x <= u2.x) || (l1.x <= u2.x && u2.x <= u1.x));
          var overlapsY = ((l2.y <= u1.y && u1.y <= u2.y) || (l1.y <= u2.y && u2.y <= u1.y));
          var overlapsZ = ((l2.z <= u1.z && u1.z <= u2.z) || (l1.z <= u2.z && u2.z <= u1.z));

          return overlapsX && overlapsY && overlapsZ;
      };

      // Mostly for debugging
      AABB.prototype.volume = function(){
          var l = this.lowerBound,
              u = this.upperBound;
          return (u.x - l.x) * (u.y - l.y) * (u.z - l.z);
      };


      /**
       * Returns true if the given AABB is fully contained in this AABB.
       * @method contains
       * @param {AABB} aabb
       * @return {Boolean}
       */
      AABB.prototype.contains = function(aabb){
          var l1 = this.lowerBound,
              u1 = this.upperBound,
              l2 = aabb.lowerBound,
              u2 = aabb.upperBound;

          //      l2        u2
          //      |---------|
          // |---------------|
          // l1              u1

          return (
              (l1.x <= l2.x && u1.x >= u2.x) &&
              (l1.y <= l2.y && u1.y >= u2.y) &&
              (l1.z <= l2.z && u1.z >= u2.z)
          );
      };

      /**
       * @method getCorners
       * @param {Vec3} a
       * @param {Vec3} b
       * @param {Vec3} c
       * @param {Vec3} d
       * @param {Vec3} e
       * @param {Vec3} f
       * @param {Vec3} g
       * @param {Vec3} h
       */
      AABB.prototype.getCorners = function(a, b, c, d, e, f, g, h){
          var l = this.lowerBound,
              u = this.upperBound;

          a.copy(l);
          b.set( u.x, l.y, l.z );
          c.set( u.x, u.y, l.z );
          d.set( l.x, u.y, u.z );
          e.set( u.x, l.y, u.z );
          f.set( l.x, u.y, l.z );
          g.set( l.x, l.y, u.z );
          h.copy(u);
      };

      var transformIntoFrame_corners = [
          new Vec3(),
          new Vec3(),
          new Vec3(),
          new Vec3(),
          new Vec3(),
          new Vec3(),
          new Vec3(),
          new Vec3()
      ];

      /**
       * Get the representation of an AABB in another frame.
       * @method toLocalFrame
       * @param  {Transform} frame
       * @param  {AABB} target
       * @return {AABB} The "target" AABB object.
       */
      AABB.prototype.toLocalFrame = function(frame, target){

          var corners = transformIntoFrame_corners;
          var a = corners[0];
          var b = corners[1];
          var c = corners[2];
          var d = corners[3];
          var e = corners[4];
          var f = corners[5];
          var g = corners[6];
          var h = corners[7];

          // Get corners in current frame
          this.getCorners(a, b, c, d, e, f, g, h);

          // Transform them to new local frame
          for(var i=0; i !== 8; i++){
              var corner = corners[i];
              frame.pointToLocal(corner, corner);
          }

          return target.setFromPoints(corners);
      };

      /**
       * Get the representation of an AABB in the global frame.
       * @method toWorldFrame
       * @param  {Transform} frame
       * @param  {AABB} target
       * @return {AABB} The "target" AABB object.
       */
      AABB.prototype.toWorldFrame = function(frame, target){

          var corners = transformIntoFrame_corners;
          var a = corners[0];
          var b = corners[1];
          var c = corners[2];
          var d = corners[3];
          var e = corners[4];
          var f = corners[5];
          var g = corners[6];
          var h = corners[7];

          // Get corners in current frame
          this.getCorners(a, b, c, d, e, f, g, h);

          // Transform them to new local frame
          for(var i=0; i !== 8; i++){
              var corner = corners[i];
              frame.pointToWorld(corner, corner);
          }

          return target.setFromPoints(corners);
      };

      /**
       * Check if the AABB is hit by a ray.
       * @param  {Ray} ray
       * @return {number}
       */
      AABB.prototype.overlapsRay = function(ray){

          // ray.direction is unit direction vector of ray
          var dirFracX = 1 / ray._direction.x;
          var dirFracY = 1 / ray._direction.y;
          var dirFracZ = 1 / ray._direction.z;

          // this.lowerBound is the corner of AABB with minimal coordinates - left bottom, rt is maximal corner
          var t1 = (this.lowerBound.x - ray.from.x) * dirFracX;
          var t2 = (this.upperBound.x - ray.from.x) * dirFracX;
          var t3 = (this.lowerBound.y - ray.from.y) * dirFracY;
          var t4 = (this.upperBound.y - ray.from.y) * dirFracY;
          var t5 = (this.lowerBound.z - ray.from.z) * dirFracZ;
          var t6 = (this.upperBound.z - ray.from.z) * dirFracZ;

          // var tmin = Math.max(Math.max(Math.min(t1, t2), Math.min(t3, t4)));
          // var tmax = Math.min(Math.min(Math.max(t1, t2), Math.max(t3, t4)));
          var tmin = Math.max(Math.max(Math.min(t1, t2), Math.min(t3, t4)), Math.min(t5, t6));
          var tmax = Math.min(Math.min(Math.max(t1, t2), Math.max(t3, t4)), Math.max(t5, t6));

          // if tmax < 0, ray (line) is intersecting AABB, but whole AABB is behing us
          if (tmax < 0){
              //t = tmax;
              return false;
          }

          // if tmin > tmax, ray doesn't intersect AABB
          if (tmin > tmax){
              //t = tmax;
              return false;
          }

          return true;
      };
      },{"../math/Vec3":31,"../utils/Utils":54}],4:[function(_dereq_,module,exports){
      module.exports = ArrayCollisionMatrix;

      /**
       * Collision "matrix". It's actually a triangular-shaped array of whether two bodies are touching this step, for reference next step
       * @class ArrayCollisionMatrix
       * @constructor
       */
      function ArrayCollisionMatrix() {

          /**
           * The matrix storage
           * @property matrix
           * @type {Array}
           */
          this.matrix = [];
      }

      /**
       * Get an element
       * @method get
       * @param  {Number} i
       * @param  {Number} j
       * @return {Number}
       */
      ArrayCollisionMatrix.prototype.get = function(i, j) {
          i = i.index;
          j = j.index;
          if (j > i) {
              var temp = j;
              j = i;
              i = temp;
          }
          return this.matrix[(i*(i + 1)>>1) + j-1];
      };

      /**
       * Set an element
       * @method set
       * @param {Number} i
       * @param {Number} j
       * @param {Number} value
       */
      ArrayCollisionMatrix.prototype.set = function(i, j, value) {
          i = i.index;
          j = j.index;
          if (j > i) {
              var temp = j;
              j = i;
              i = temp;
          }
          this.matrix[(i*(i + 1)>>1) + j-1] = value ? 1 : 0;
      };

      /**
       * Sets all elements to zero
       * @method reset
       */
      ArrayCollisionMatrix.prototype.reset = function() {
          for (var i=0, l=this.matrix.length; i!==l; i++) {
              this.matrix[i]=0;
          }
      };

      /**
       * Sets the max number of objects
       * @method setNumObjects
       * @param {Number} n
       */
      ArrayCollisionMatrix.prototype.setNumObjects = function(n) {
          this.matrix.length = n*(n-1)>>1;
      };

      },{}],5:[function(_dereq_,module,exports){
      var Body = _dereq_('../objects/Body');
      var Vec3 = _dereq_('../math/Vec3');
      var Quaternion = _dereq_('../math/Quaternion');
      _dereq_('../shapes/Shape');
      _dereq_('../shapes/Plane');

      module.exports = Broadphase;

      /**
       * Base class for broadphase implementations
       * @class Broadphase
       * @constructor
       * @author schteppe
       */
      function Broadphase(){
          /**
          * The world to search for collisions in.
          * @property world
          * @type {World}
          */
          this.world = null;

          /**
           * If set to true, the broadphase uses bounding boxes for intersection test, else it uses bounding spheres.
           * @property useBoundingBoxes
           * @type {Boolean}
           */
          this.useBoundingBoxes = false;

          /**
           * Set to true if the objects in the world moved.
           * @property {Boolean} dirty
           */
          this.dirty = true;
      }

      /**
       * Get the collision pairs from the world
       * @method collisionPairs
       * @param {World} world The world to search in
       * @param {Array} p1 Empty array to be filled with body objects
       * @param {Array} p2 Empty array to be filled with body objects
       */
      Broadphase.prototype.collisionPairs = function(world,p1,p2){
          throw new Error("collisionPairs not implemented for this BroadPhase class!");
      };

      /**
       * Check if a body pair needs to be intersection tested at all.
       * @method needBroadphaseCollision
       * @param {Body} bodyA
       * @param {Body} bodyB
       * @return {bool}
       */
      Broadphase.prototype.needBroadphaseCollision = function(bodyA,bodyB){

          // Check collision filter masks
          if( (bodyA.collisionFilterGroup & bodyB.collisionFilterMask)===0 || (bodyB.collisionFilterGroup & bodyA.collisionFilterMask)===0){
              return false;
          }

          var isSA = (bodyA.type & Body.STATIC)!==0;
          var isSB = (bodyB.type & Body.STATIC)!==0;

          // s - s
          if(isSA && isSB) return false;

          // Check has trigger
          if(bodyA.hasTrigger || bodyB.hasTrigger){
              return true;
          } else {
              // Check sleep state
              if((bodyA.sleepState === Body.SLEEPING) &&
                 (bodyB.sleepState === Body.SLEEPING)) {
                  // Both bodies are static or sleeping. Skip.
                  return false;
              }
          }

          return true;
      };

      /**
       * Check if the bounding volumes of two bodies intersect.
       * @method intersectionTest
       * @param {Body} bodyA
       * @param {Body} bodyB
       * @param {array} pairs1
       * @param {array} pairs2
        */
      Broadphase.prototype.intersectionTest = function(bodyA, bodyB, pairs1, pairs2){
          if(this.useBoundingBoxes){
              this.doBoundingBoxBroadphase(bodyA,bodyB,pairs1,pairs2);
          } else {
              this.doBoundingSphereBroadphase(bodyA,bodyB,pairs1,pairs2);
          }
      };

      /**
       * Check if the bounding spheres of two bodies are intersecting.
       * @method doBoundingSphereBroadphase
       * @param {Body} bodyA
       * @param {Body} bodyB
       * @param {Array} pairs1 bodyA is appended to this array if intersection
       * @param {Array} pairs2 bodyB is appended to this array if intersection
       */
      var Broadphase_collisionPairs_r = new Vec3(); // Temp objects
          new Vec3();
          new Quaternion();
          new Vec3();
      Broadphase.prototype.doBoundingSphereBroadphase = function(bodyA,bodyB,pairs1,pairs2){
          var r = Broadphase_collisionPairs_r;
          bodyB.position.vsub(bodyA.position,r);
          var boundingRadiusSum2 = Math.pow(bodyA.boundingRadius + bodyB.boundingRadius, 2);
          var norm2 = r.norm2();
          if(norm2 < boundingRadiusSum2){
              pairs1.push(bodyA);
              pairs2.push(bodyB);
          }
      };

      /**
       * Check if the bounding boxes of two bodies are intersecting.
       * @method doBoundingBoxBroadphase
       * @param {Body} bodyA
       * @param {Body} bodyB
       * @param {Array} pairs1
       * @param {Array} pairs2
       */
      Broadphase.prototype.doBoundingBoxBroadphase = function(bodyA,bodyB,pairs1,pairs2){
          if(bodyA.aabbNeedsUpdate){
              bodyA.computeAABB();
          }
          if(bodyB.aabbNeedsUpdate){
              bodyB.computeAABB();
          }

          // Check AABB / AABB
          if(bodyA.aabb.overlaps(bodyB.aabb)){
              pairs1.push(bodyA);
              pairs2.push(bodyB);
          }
      };

      /**
       * Removes duplicate pairs from the pair arrays.
       * @method makePairsUnique
       * @param {Array} pairs1
       * @param {Array} pairs2
       */
      var Broadphase_makePairsUnique_temp = { keys:[] },
          Broadphase_makePairsUnique_p1 = [],
          Broadphase_makePairsUnique_p2 = [];
      Broadphase.prototype.makePairsUnique = function(pairs1,pairs2){
          var t = Broadphase_makePairsUnique_temp,
              p1 = Broadphase_makePairsUnique_p1,
              p2 = Broadphase_makePairsUnique_p2,
              N = pairs1.length;

          for(var i=0; i!==N; i++){
              p1[i] = pairs1[i];
              p2[i] = pairs2[i];
          }

          pairs1.length = 0;
          pairs2.length = 0;

          for(var i=0; i!==N; i++){
              var id1 = p1[i].id,
                  id2 = p2[i].id;
              var key = id1 < id2 ? id1+","+id2 :  id2+","+id1;
              t[key] = i;
              t.keys.push(key);
          }

          for(var i=0; i!==t.keys.length; i++){
              var key = t.keys.pop(),
                  pairIndex = t[key];
              pairs1.push(p1[pairIndex]);
              pairs2.push(p2[pairIndex]);
              delete t[key];
          }
      };

      /**
       * To be implemented by subcasses
       * @method setWorld
       * @param {World} world
       */
      Broadphase.prototype.setWorld = function(world){
      };

      /**
       * Check if the bounding spheres of two bodies overlap.
       * @method boundingSphereCheck
       * @param {Body} bodyA
       * @param {Body} bodyB
       * @return {boolean}
       */
      var bsc_dist = new Vec3();
      Broadphase.boundingSphereCheck = function(bodyA,bodyB){
          var dist = bsc_dist;
          bodyA.position.vsub(bodyB.position,dist);
          return Math.pow(bodyA.shape.boundingSphereRadius + bodyB.shape.boundingSphereRadius,2) > dist.norm2();
      };

      /**
       * Returns all the bodies within the AABB.
       * @method aabbQuery
       * @param  {World} world
       * @param  {AABB} aabb
       * @param  {array} result An array to store resulting bodies in.
       * @return {array}
       */
      Broadphase.prototype.aabbQuery = function(world, aabb, result){
          console.warn('.aabbQuery is not implemented in this Broadphase subclass.');
          return [];
      };
      },{"../math/Quaternion":29,"../math/Vec3":31,"../objects/Body":32,"../shapes/Plane":43,"../shapes/Shape":44}],6:[function(_dereq_,module,exports){
      module.exports = GridBroadphase;

      var Broadphase = _dereq_('./Broadphase');
      var Vec3 = _dereq_('../math/Vec3');
      var Shape = _dereq_('../shapes/Shape');

      /**
       * Axis aligned uniform grid broadphase.
       * @class GridBroadphase
       * @constructor
       * @extends Broadphase
       * @todo Needs support for more than just planes and spheres.
       * @param {Vec3} aabbMin
       * @param {Vec3} aabbMax
       * @param {Number} nx Number of boxes along x
       * @param {Number} ny Number of boxes along y
       * @param {Number} nz Number of boxes along z
       */
      function GridBroadphase(aabbMin,aabbMax,nx,ny,nz){
          Broadphase.apply(this);
          this.nx = nx || 10;
          this.ny = ny || 10;
          this.nz = nz || 10;
          this.aabbMin = aabbMin || new Vec3(100,100,100);
          this.aabbMax = aabbMax || new Vec3(-100,-100,-100);
      	var nbins = this.nx * this.ny * this.nz;
      	if (nbins <= 0) {
      		throw "GridBroadphase: Each dimension's n must be >0";
      	}
          this.bins = [];
      	this.binLengths = []; //Rather than continually resizing arrays (thrashing the memory), just record length and allow them to grow
      	this.bins.length = nbins;
      	this.binLengths.length = nbins;
      	for (var i=0;i<nbins;i++) {
      		this.bins[i]=[];
      		this.binLengths[i]=0;
      	}
      }
      GridBroadphase.prototype = new Broadphase();
      GridBroadphase.prototype.constructor = GridBroadphase;

      /**
       * Get all the collision pairs in the physics world
       * @method collisionPairs
       * @param {World} world
       * @param {Array} pairs1
       * @param {Array} pairs2
       */
      var GridBroadphase_collisionPairs_d = new Vec3();
      new Vec3();
      GridBroadphase.prototype.collisionPairs = function(world,pairs1,pairs2){
          var N = world.numObjects(),
              bodies = world.bodies;

          var max = this.aabbMax,
              min = this.aabbMin,
              nx = this.nx,
              ny = this.ny,
              nz = this.nz;

      	var xstep = ny*nz;
      	var ystep = nz;
      	var zstep = 1;

          var xmax = max.x,
              ymax = max.y,
              zmax = max.z,
              xmin = min.x,
              ymin = min.y,
              zmin = min.z;

          var xmult = nx / (xmax-xmin),
              ymult = ny / (ymax-ymin),
              zmult = nz / (zmax-zmin);

          var binsizeX = (xmax - xmin) / nx,
              binsizeY = (ymax - ymin) / ny,
              binsizeZ = (zmax - zmin) / nz;

      	var binRadius = Math.sqrt(binsizeX*binsizeX + binsizeY*binsizeY + binsizeZ*binsizeZ) * 0.5;

          var types = Shape.types;
          var SPHERE =            types.SPHERE,
              PLANE =             types.PLANE;
              types.BOX;
              types.COMPOUND;
              types.CONVEXPOLYHEDRON;

          var bins=this.bins,
      		binLengths=this.binLengths,
              Nbins=this.bins.length;

          // Reset bins
          for(var i=0; i!==Nbins; i++){
              binLengths[i] = 0;
          }

          var ceil = Math.ceil;
      	var min = Math.min;
      	var max = Math.max;

      	function addBoxToBins(x0,y0,z0,x1,y1,z1,bi) {
      		var xoff0 = ((x0 - xmin) * xmult)|0,
      			yoff0 = ((y0 - ymin) * ymult)|0,
      			zoff0 = ((z0 - zmin) * zmult)|0,
      			xoff1 = ceil((x1 - xmin) * xmult),
      			yoff1 = ceil((y1 - ymin) * ymult),
      			zoff1 = ceil((z1 - zmin) * zmult);

      		if (xoff0 < 0) { xoff0 = 0; } else if (xoff0 >= nx) { xoff0 = nx - 1; }
      		if (yoff0 < 0) { yoff0 = 0; } else if (yoff0 >= ny) { yoff0 = ny - 1; }
      		if (zoff0 < 0) { zoff0 = 0; } else if (zoff0 >= nz) { zoff0 = nz - 1; }
      		if (xoff1 < 0) { xoff1 = 0; } else if (xoff1 >= nx) { xoff1 = nx - 1; }
      		if (yoff1 < 0) { yoff1 = 0; } else if (yoff1 >= ny) { yoff1 = ny - 1; }
      		if (zoff1 < 0) { zoff1 = 0; } else if (zoff1 >= nz) { zoff1 = nz - 1; }

      		xoff0 *= xstep;
      		yoff0 *= ystep;
      		zoff0 *= zstep;
      		xoff1 *= xstep;
      		yoff1 *= ystep;
      		zoff1 *= zstep;

      		for (var xoff = xoff0; xoff <= xoff1; xoff += xstep) {
      			for (var yoff = yoff0; yoff <= yoff1; yoff += ystep) {
      				for (var zoff = zoff0; zoff <= zoff1; zoff += zstep) {
      					var idx = xoff+yoff+zoff;
      					bins[idx][binLengths[idx]++] = bi;
      				}
      			}
      		}
      	}

          // Put all bodies into the bins
          for(var i=0; i!==N; i++){
              var bi = bodies[i];
              var si = bi.shape;

              switch(si.type){
              case SPHERE:
                  // Put in bin
                  // check if overlap with other bins
                  var x = bi.position.x,
                      y = bi.position.y,
                      z = bi.position.z;
                  var r = si.radius;

      			addBoxToBins(x-r, y-r, z-r, x+r, y+r, z+r, bi);
                  break;

              case PLANE:
                  if(si.worldNormalNeedsUpdate){
                      si.computeWorldNormal(bi.quaternion);
                  }
                  var planeNormal = si.worldNormal;

      			//Relative position from origin of plane object to the first bin
      			//Incremented as we iterate through the bins
      			var xreset = xmin + binsizeX*0.5 - bi.position.x,
      				yreset = ymin + binsizeY*0.5 - bi.position.y,
      				zreset = zmin + binsizeZ*0.5 - bi.position.z;

                  var d = GridBroadphase_collisionPairs_d;
      			d.set(xreset, yreset, zreset);

      			for (var xi = 0, xoff = 0; xi !== nx; xi++, xoff += xstep, d.y = yreset, d.x += binsizeX) {
      				for (var yi = 0, yoff = 0; yi !== ny; yi++, yoff += ystep, d.z = zreset, d.y += binsizeY) {
      					for (var zi = 0, zoff = 0; zi !== nz; zi++, zoff += zstep, d.z += binsizeZ) {
      						if (d.dot(planeNormal) < binRadius) {
      							var idx = xoff + yoff + zoff;
      							bins[idx][binLengths[idx]++] = bi;
      						}
      					}
      				}
      			}
                  break;

              default:
      			if (bi.aabbNeedsUpdate) {
      				bi.computeAABB();
      			}

      			addBoxToBins(
      				bi.aabb.lowerBound.x,
      				bi.aabb.lowerBound.y,
      				bi.aabb.lowerBound.z,
      				bi.aabb.upperBound.x,
      				bi.aabb.upperBound.y,
      				bi.aabb.upperBound.z,
      				bi);
                  break;
              }
          }

          // Check each bin
          for(var i=0; i!==Nbins; i++){
      		var binLength = binLengths[i];
      		//Skip bins with no potential collisions
      		if (binLength > 1) {
      			var bin = bins[i];

      			// Do N^2 broadphase inside
      			for(var xi=0; xi!==binLength; xi++){
      				var bi = bin[xi];
      				for(var yi=0; yi!==xi; yi++){
      					var bj = bin[yi];
      					if(this.needBroadphaseCollision(bi,bj)){
      						this.intersectionTest(bi,bj,pairs1,pairs2);
      					}
      				}
      			}
      		}
          }

      //	for (var zi = 0, zoff=0; zi < nz; zi++, zoff+= zstep) {
      //		console.log("layer "+zi);
      //		for (var yi = 0, yoff=0; yi < ny; yi++, yoff += ystep) {
      //			var row = '';
      //			for (var xi = 0, xoff=0; xi < nx; xi++, xoff += xstep) {
      //				var idx = xoff + yoff + zoff;
      //				row += ' ' + binLengths[idx];
      //			}
      //			console.log(row);
      //		}
      //	}

          this.makePairsUnique(pairs1,pairs2);
      };

      },{"../math/Vec3":31,"../shapes/Shape":44,"./Broadphase":5}],7:[function(_dereq_,module,exports){
      module.exports = NaiveBroadphase;

      var Broadphase = _dereq_('./Broadphase');
      var AABB = _dereq_('./AABB');

      /**
       * Naive broadphase implementation, used in lack of better ones.
       * @class NaiveBroadphase
       * @constructor
       * @description The naive broadphase looks at all possible pairs without restriction, therefore it has complexity N^2 (which is bad)
       * @extends Broadphase
       */
      function NaiveBroadphase(){
          Broadphase.apply(this);
      }
      NaiveBroadphase.prototype = new Broadphase();
      NaiveBroadphase.prototype.constructor = NaiveBroadphase;

      /**
       * Get all the collision pairs in the physics world
       * @method collisionPairs
       * @param {World} world
       * @param {Array} pairs1
       * @param {Array} pairs2
       */
      NaiveBroadphase.prototype.collisionPairs = function(world,pairs1,pairs2){
          var bodies = world.bodies,
              n = bodies.length,
              i,j,bi,bj;

          // Naive N^2 ftw!
          for(i=0; i!==n; i++){
              for(j=0; j!==i; j++){

                  bi = bodies[i];
                  bj = bodies[j];

                  if(!this.needBroadphaseCollision(bi,bj)){
                      continue;
                  }

                  this.intersectionTest(bi,bj,pairs1,pairs2);
              }
          }
      };

      new AABB();

      /**
       * Returns all the bodies within an AABB.
       * @method aabbQuery
       * @param  {World} world
       * @param  {AABB} aabb
       * @param {array} result An array to store resulting bodies in.
       * @return {array}
       */
      NaiveBroadphase.prototype.aabbQuery = function(world, aabb, result){
          result = result || [];

          for(var i = 0; i < world.bodies.length; i++){
              var b = world.bodies[i];

              if(b.aabbNeedsUpdate){
                  b.computeAABB();
              }

              // Ugly hack until Body gets aabb
              if(b.aabb.overlaps(aabb)){
                  result.push(b);
              }
          }

          return result;
      };
      },{"./AABB":3,"./Broadphase":5}],8:[function(_dereq_,module,exports){
      module.exports = ObjectCollisionMatrix;

      /**
       * Records what objects are colliding with each other
       * @class ObjectCollisionMatrix
       * @constructor
       */
      function ObjectCollisionMatrix() {

          /**
           * The matrix storage
           * @property matrix
           * @type {Object}
           */
      	this.matrix = {};
      }

      /**
       * @method get
       * @param  {Number} i
       * @param  {Number} j
       * @return {Number}
       */
      ObjectCollisionMatrix.prototype.get = function(i, j) {
      	i = i.id;
      	j = j.id;
          if (j > i) {
              var temp = j;
              j = i;
              i = temp;
          }
      	return i+'-'+j in this.matrix;
      };

      /**
       * @method set
       * @param  {Number} i
       * @param  {Number} j
       * @param {Number} value
       */
      ObjectCollisionMatrix.prototype.set = function(i, j, value) {
      	i = i.id;
      	j = j.id;
          if (j > i) {
              var temp = j;
              j = i;
              i = temp;
      	}
      	if (value) {
      		this.matrix[i+'-'+j] = true;
      	}
      	else {
      		delete this.matrix[i+'-'+j];
      	}
      };

      /**
       * Empty the matrix
       * @method reset
       */
      ObjectCollisionMatrix.prototype.reset = function() {
      	this.matrix = {};
      };

      /**
       * Set max number of objects
       * @method setNumObjects
       * @param {Number} n
       */
      ObjectCollisionMatrix.prototype.setNumObjects = function(n) {
      };

      },{}],9:[function(_dereq_,module,exports){
      module.exports = OverlapKeeper;

      /**
       * @class OverlapKeeper
       * @constructor
       */
      function OverlapKeeper() {
          this.current = [];
          this.previous = [];
      }

      OverlapKeeper.prototype.getKey = function(i, j) {
          if (j < i) {
              var temp = j;
              j = i;
              i = temp;
          }
          return (i << 16) | j;
      };


      /**
       * @method set
       * @param {Number} i
       * @param {Number} j
       */
      OverlapKeeper.prototype.set = function(i, j) {
          // Insertion sort. This way the diff will have linear complexity.
          var key = this.getKey(i, j);
          var current = this.current;
          var index = 0;
          while(key > current[index]){
              index++;
          }
          if(key === current[index]){
              return; // Pair was already added
          }
          for(var j=current.length-1; j>=index; j--){
              current[j + 1] = current[j];
          }
          current[index] = key;
      };

      /**
       * @method tick
       */
      OverlapKeeper.prototype.tick = function() {
          var tmp = this.current;
          this.current = this.previous;
          this.previous = tmp;
          this.current.length = 0;
      };

      function unpackAndPush(array, key){
          array.push((key & 0xFFFF0000) >> 16, key & 0x0000FFFF);
      }

      /**
       * @method getDiff
       * @param  {array} additions
       * @param  {array} removals
       */
      OverlapKeeper.prototype.getDiff = function(additions, removals) {
          var a = this.current;
          var b = this.previous;
          var al = a.length;
          var bl = b.length;

          var j=0;
          for (var i = 0; i < al; i++) {
              var found = false;
              var keyA = a[i];
              while(keyA > b[j]){
                  j++;
              }
              found = keyA === b[j];

              if(!found){
                  unpackAndPush(additions, keyA);
              }
          }
          j = 0;
          for (var i = 0; i < bl; i++) {
              var found = false;
              var keyB = b[i];
              while(keyB > a[j]){
                  j++;
              }
              found = a[j] === keyB;

              if(!found){
                  unpackAndPush(removals, keyB);
              }
          }
      };
      },{}],10:[function(_dereq_,module,exports){
      module.exports = Ray;

      var Vec3 = _dereq_('../math/Vec3');
      var Quaternion = _dereq_('../math/Quaternion');
      var Transform = _dereq_('../math/Transform');
      _dereq_('../shapes/ConvexPolyhedron');
      _dereq_('../shapes/Box');
      var RaycastResult = _dereq_('../collision/RaycastResult');
      var Shape = _dereq_('../shapes/Shape');
      var AABB = _dereq_('../collision/AABB');

      /**
       * A line in 3D space that intersects bodies and return points.
       * @class Ray
       * @constructor
       * @param {Vec3} from
       * @param {Vec3} to
       */
      function Ray(from, to){
          /**
           * @property {Vec3} from
           */
          this.from = from ? from.clone() : new Vec3();

          /**
           * @property {Vec3} to
           */
          this.to = to ? to.clone() : new Vec3();

          /**
           * @private
           * @property {Vec3} _direction
           */
          this._direction = new Vec3();

          /**
           * The precision of the ray. Used when checking parallelity etc.
           * @property {Number} precision
           */
          this.precision = 0.0001;

          /**
           * Set to true if you want the Ray to take .collisionResponse flags into account on bodies and shapes.
           * @property {Boolean} checkCollisionResponse
           */
          this.checkCollisionResponse = true;

          /**
           * If set to true, the ray skips any hits with normal.dot(rayDirection) < 0.
           * @property {Boolean} skipBackfaces
           */
          this.skipBackfaces = false;

          /**
           * @property {number} collisionFilterMask
           * @default -1
           */
          this.collisionFilterMask = -1;

          /**
           * @property {number} collisionFilterGroup
           * @default -1
           */
          this.collisionFilterGroup = -1;

          /**
           * The intersection mode. Should be Ray.ANY, Ray.ALL or Ray.CLOSEST.
           * @property {number} mode
           */
          this.mode = Ray.ANY;

          /**
           * Current result object.
           * @property {RaycastResult} result
           */
          this.result = new RaycastResult();

          /**
           * Will be set to true during intersectWorld() if the ray hit anything.
           * @property {Boolean} hasHit
           */
          this.hasHit = false;

          /**
           * Current, user-provided result callback. Will be used if mode is Ray.ALL.
           * @property {Function} callback
           */
          this.callback = function(result){};
      }
      Ray.prototype.constructor = Ray;

      Ray.CLOSEST = 1;
      Ray.ANY = 2;
      Ray.ALL = 4;

      var tmpAABB = new AABB();
      var tmpArray = [];

      /**
       * Do itersection against all bodies in the given World.
       * @method intersectWorld
       * @param  {World} world
       * @param  {object} options
       * @return {Boolean} True if the ray hit anything, otherwise false.
       */
      Ray.prototype.intersectWorld = function (world, options) {
          this.mode = options.mode || Ray.ANY;
          this.result = options.result || new RaycastResult();
          this.skipBackfaces = !!options.skipBackfaces;
          this.checkCollisionResponse = !!options.checkCollisionResponse;
          this.collisionFilterMask = typeof(options.collisionFilterMask) !== 'undefined' ? options.collisionFilterMask : -1;
          this.collisionFilterGroup = typeof(options.collisionFilterGroup) !== 'undefined' ? options.collisionFilterGroup : -1;
          if(options.from){
              this.from.copy(options.from);
          }
          if(options.to){
              this.to.copy(options.to);
          }
          this.callback = options.callback || function(){};
          this.hasHit = false;

          this.result.reset();
          this._updateDirection();

          this.getAABB(tmpAABB);
          tmpArray.length = 0;
          world.broadphase.aabbQuery(world, tmpAABB, tmpArray);
          this.intersectBodies(tmpArray);

          return this.hasHit;
      };

      var v1 = new Vec3(),
          v2 = new Vec3();

      /*
       * As per "Barycentric Technique" as named here http://www.blackpawn.com/texts/pointinpoly/default.html But without the division
       */
      Ray.pointInTriangle = pointInTriangle;
      function pointInTriangle(p, a, b, c) {
          c.vsub(a,v0);
          b.vsub(a,v1);
          p.vsub(a,v2);

          var dot00 = v0.dot( v0 );
          var dot01 = v0.dot( v1 );
          var dot02 = v0.dot( v2 );
          var dot11 = v1.dot( v1 );
          var dot12 = v1.dot( v2 );

          var u,v;

          return  ( (u = dot11 * dot02 - dot01 * dot12) >= 0 ) &&
                  ( (v = dot00 * dot12 - dot01 * dot02) >= 0 ) &&
                  ( u + v < ( dot00 * dot11 - dot01 * dot01 ) );
      }

      /**
       * Shoot a ray at a body, get back information about the hit.
       * @method intersectBody
       * @private
       * @param {Body} body
       * @param {RaycastResult} [result] Deprecated - set the result property of the Ray instead.
       */
      var intersectBody_xi = new Vec3();
      var intersectBody_qi = new Quaternion();
      Ray.prototype.intersectBody = function (body, result) {
          if(result){
              this.result = result;
              this._updateDirection();
          }
          var checkCollisionResponse = this.checkCollisionResponse;

          if(checkCollisionResponse && !body.collisionResponse){
              return;
          }

          if (!Ray.perBodyFilter(this, body)) return;

          var xi = intersectBody_xi;
          var qi = intersectBody_qi;

          for (var i = 0, N = body.shapes.length; i < N; i++) {
              var shape = body.shapes[i];

              if (!Ray.perShapeFilter(this, shape)) continue;

              body.quaternion.mult(body.shapeOrientations[i], qi);
              body.quaternion.vmult(body.shapeOffsets[i], xi);
              xi.vadd(body.position, xi);

              this.intersectShape(
                  shape,
                  qi,
                  xi,
                  body
              );

              if(this.result._shouldStop){
                  break;
              }
          }
      };

      /**
       * @method intersectBodies
       * @param {Array} bodies An array of Body objects.
       * @param {RaycastResult} [result] Deprecated
       */
      Ray.prototype.intersectBodies = function (bodies, result) {
          if(result){
              this.result = result;
              this._updateDirection();
          }

          for ( var i = 0, l = bodies.length; !this.result._shouldStop && i < l; i ++ ) {
              this.intersectBody(bodies[i]);
          }
      };

      /**
       * Updates the _direction vector.
       * @private
       * @method _updateDirection
       */
      Ray.prototype._updateDirection = function(){
          this.to.vsub(this.from, this._direction);
          this._direction.normalize();
      };

      /**
       * @method intersectShape
       * @private
       * @param {Shape} shape
       * @param {Quaternion} quat
       * @param {Vec3} position
       * @param {Body} body
       */
      Ray.prototype.intersectShape = function(shape, quat, position, body){
          var from = this.from;


          // Checking boundingSphere
          var distance = distanceFromIntersection(from, this._direction, position);
          if ( distance > shape.boundingSphereRadius ) {
              return;
          }

          var intersectMethod = this[shape.type];
          if(intersectMethod){
              intersectMethod.call(this, shape, quat, position, body, shape);
          }
      };

      new Vec3();
      new Vec3();
      var intersectPoint = new Vec3();

      var a = new Vec3();
      var b = new Vec3();
      var c = new Vec3();
      new Vec3();

      new RaycastResult();

      /**
       * @method intersectBox
       * @private
       * @param  {Shape} shape
       * @param  {Quaternion} quat
       * @param  {Vec3} position
       * @param  {Body} body
       */
      Ray.prototype.intersectBox = function(shape, quat, position, body, reportedShape){
          return this.intersectConvex(shape.convexPolyhedronRepresentation, quat, position, body, reportedShape);
      };
      Ray.prototype[Shape.types.BOX] = Ray.prototype.intersectBox;

      /**
       * @method intersectPlane
       * @private
       * @param  {Shape} shape
       * @param  {Quaternion} quat
       * @param  {Vec3} position
       * @param  {Body} body
       */
      Ray.prototype.intersectPlane = function(shape, quat, position, body, reportedShape){
          var from = this.from;
          var to = this.to;
          var direction = this._direction;

          // Get plane normal
          var worldNormal = new Vec3(0, 0, 1);
          quat.vmult(worldNormal, worldNormal);

          var len = new Vec3();
          from.vsub(position, len);
          var planeToFrom = len.dot(worldNormal);
          to.vsub(position, len);
          var planeToTo = len.dot(worldNormal);

          if(planeToFrom * planeToTo > 0){
              // "from" and "to" are on the same side of the plane... bail out
              return;
          }

          if(from.distanceTo(to) < planeToFrom){
              return;
          }

          var n_dot_dir = worldNormal.dot(direction);

          if (Math.abs(n_dot_dir) < this.precision) {
              // No intersection
              return;
          }

          var planePointToFrom = new Vec3();
          var dir_scaled_with_t = new Vec3();
          var hitPointWorld = new Vec3();

          from.vsub(position, planePointToFrom);
          var t = -worldNormal.dot(planePointToFrom) / n_dot_dir;
          direction.scale(t, dir_scaled_with_t);
          from.vadd(dir_scaled_with_t, hitPointWorld);

          this.reportIntersection(worldNormal, hitPointWorld, reportedShape, body, -1);
      };
      Ray.prototype[Shape.types.PLANE] = Ray.prototype.intersectPlane;

      /**
       * Get the world AABB of the ray.
       * @method getAABB
       * @param  {AABB} aabb
       */
      Ray.prototype.getAABB = function(result){
          var to = this.to;
          var from = this.from;
          result.lowerBound.x = Math.min(to.x, from.x);
          result.lowerBound.y = Math.min(to.y, from.y);
          result.lowerBound.z = Math.min(to.z, from.z);
          result.upperBound.x = Math.max(to.x, from.x);
          result.upperBound.y = Math.max(to.y, from.y);
          result.upperBound.z = Math.max(to.z, from.z);
      };

      var intersectConvexOptions = {
          faceList: [0]
      };
      var worldPillarOffset = new Vec3();
      var intersectHeightfield_localRay = new Ray();
      var intersectHeightfield_index = [];

      /**
       * @method intersectHeightfield
       * @private
       * @param  {Shape} shape
       * @param  {Quaternion} quat
       * @param  {Vec3} position
       * @param  {Body} body
       */
      Ray.prototype.intersectHeightfield = function(shape, quat, position, body, reportedShape){
          shape.data;
              shape.elementSize;

          // Convert the ray to local heightfield coordinates
          var localRay = intersectHeightfield_localRay; //new Ray(this.from, this.to);
          localRay.from.copy(this.from);
          localRay.to.copy(this.to);
          Transform.pointToLocalFrame(position, quat, localRay.from, localRay.from);
          Transform.pointToLocalFrame(position, quat, localRay.to, localRay.to);
          localRay._updateDirection();

          // Get the index of the data points to test against
          var index = intersectHeightfield_index;
          var iMinX, iMinY, iMaxX, iMaxY;

          // Set to max
          iMinX = iMinY = 0;
          iMaxX = iMaxY = shape.data.length - 1;

          var aabb = new AABB();
          localRay.getAABB(aabb);

          shape.getIndexOfPosition(aabb.lowerBound.x, aabb.lowerBound.y, index, true);
          iMinX = Math.max(iMinX, index[0]);
          iMinY = Math.max(iMinY, index[1]);
          shape.getIndexOfPosition(aabb.upperBound.x, aabb.upperBound.y, index, true);
          iMaxX = Math.min(iMaxX, index[0] + 1);
          iMaxY = Math.min(iMaxY, index[1] + 1);

          for(var i = iMinX; i < iMaxX; i++){
              for(var j = iMinY; j < iMaxY; j++){

                  if(this.result._shouldStop){
                      return;
                  }

                  shape.getAabbAtIndex(i, j, aabb);
                  if(!aabb.overlapsRay(localRay)){
                      continue;
                  }

                  // Lower triangle
                  shape.getConvexTrianglePillar(i, j, false);
                  Transform.pointToWorldFrame(position, quat, shape.pillarOffset, worldPillarOffset);
                  this.intersectConvex(shape.pillarConvex, quat, worldPillarOffset, body, reportedShape, intersectConvexOptions);

                  if(this.result._shouldStop){
                      return;
                  }

                  // Upper triangle
                  shape.getConvexTrianglePillar(i, j, true);
                  Transform.pointToWorldFrame(position, quat, shape.pillarOffset, worldPillarOffset);
                  this.intersectConvex(shape.pillarConvex, quat, worldPillarOffset, body, reportedShape, intersectConvexOptions);
              }
          }
      };
      Ray.prototype[Shape.types.HEIGHTFIELD] = Ray.prototype.intersectHeightfield;

      var Ray_intersectSphere_intersectionPoint = new Vec3();
      var Ray_intersectSphere_normal = new Vec3();

      /**
       * @method intersectSphere
       * @private
       * @param  {Shape} shape
       * @param  {Quaternion} quat
       * @param  {Vec3} position
       * @param  {Body} body
       */
      Ray.prototype.intersectSphere = function(shape, quat, position, body, reportedShape){
          var from = this.from,
              to = this.to,
              r = shape.radius;

          var a = Math.pow(to.x - from.x, 2) + Math.pow(to.y - from.y, 2) + Math.pow(to.z - from.z, 2);
          var b = 2 * ((to.x - from.x) * (from.x - position.x) + (to.y - from.y) * (from.y - position.y) + (to.z - from.z) * (from.z - position.z));
          var c = Math.pow(from.x - position.x, 2) + Math.pow(from.y - position.y, 2) + Math.pow(from.z - position.z, 2) - Math.pow(r, 2);

          var delta = Math.pow(b, 2) - 4 * a * c;

          var intersectionPoint = Ray_intersectSphere_intersectionPoint;
          var normal = Ray_intersectSphere_normal;

          if(delta < 0){
              // No intersection
              return;

          } else if(delta === 0){
              // single intersection point
              from.lerp(to, delta, intersectionPoint);

              intersectionPoint.vsub(position, normal);
              normal.normalize();

              this.reportIntersection(normal, intersectionPoint, reportedShape, body, -1);

          } else {
              var d1 = (- b - Math.sqrt(delta)) / (2 * a);
              var d2 = (- b + Math.sqrt(delta)) / (2 * a);

              if(d1 >= 0 && d1 <= 1){
                  from.lerp(to, d1, intersectionPoint);
                  intersectionPoint.vsub(position, normal);
                  normal.normalize();
                  this.reportIntersection(normal, intersectionPoint, reportedShape, body, -1);
              }

              if(this.result._shouldStop){
                  return;
              }

              if(d2 >= 0 && d2 <= 1){
                  from.lerp(to, d2, intersectionPoint);
                  intersectionPoint.vsub(position, normal);
                  normal.normalize();
                  this.reportIntersection(normal, intersectionPoint, reportedShape, body, -1);
              }
          }
      };
      Ray.prototype[Shape.types.SPHERE] = Ray.prototype.intersectSphere;


      var intersectConvex_normal = new Vec3();
      new Vec3();
      new Vec3();
      var intersectConvex_vector = new Vec3();

      /**
       * @method intersectConvex
       * @private
       * @param  {Shape} shape
       * @param  {Quaternion} quat
       * @param  {Vec3} position
       * @param  {Body} body
       * @param {object} [options]
       * @param {array} [options.faceList]
       */
      Ray.prototype.intersectConvex = function intersectConvex(
          shape,
          quat,
          position,
          body,
          reportedShape,
          options
      ){
          var normal = intersectConvex_normal;
          var vector = intersectConvex_vector;
          var faceList = (options && options.faceList) || null;

          // Checking faces
          var faces = shape.faces,
              vertices = shape.vertices,
              normals = shape.faceNormals;
          var direction = this._direction;

          var from = this.from;
          var to = this.to;
          var fromToDistance = from.distanceTo(to);
          var Nfaces = faceList ? faceList.length : faces.length;
          var result = this.result;

          for (var j = 0; !result._shouldStop && j < Nfaces; j++) {
              var fi = faceList ? faceList[j] : j;

              var face = faces[fi];
              var faceNormal = normals[fi];
              var q = quat;
              var x = position;

              // determine if ray intersects the plane of the face
              // note: this works regardless of the direction of the face normal

              // Get plane point in world coordinates...
              vector.copy(vertices[face[0]]);
              q.vmult(vector,vector);
              vector.vadd(x,vector);

              // ...but make it relative to the ray from. We'll fix this later.
              vector.vsub(from,vector);

              // Get plane normal
              q.vmult(faceNormal,normal);

              // If this dot product is negative, we have something interesting
              var dot = direction.dot(normal);

              // Bail out if ray and plane are parallel
              if ( Math.abs( dot ) < this.precision ){
                  continue;
              }

              // calc distance to plane
              var scalar = normal.dot(vector) / dot;

              // if negative distance, then plane is behind ray
              if (scalar < 0){
                  continue;
              }

              // if (dot < 0) {

              // Intersection point is from + direction * scalar
              direction.mult(scalar,intersectPoint);
              intersectPoint.vadd(from,intersectPoint);

              // a is the point we compare points b and c with.
              a.copy(vertices[face[0]]);
              q.vmult(a,a);
              x.vadd(a,a);

              for(var i = 1; !result._shouldStop && i < face.length - 1; i++){
                  // Transform 3 vertices to world coords
                  b.copy(vertices[face[i]]);
                  c.copy(vertices[face[i+1]]);
                  q.vmult(b,b);
                  q.vmult(c,c);
                  x.vadd(b,b);
                  x.vadd(c,c);

                  var distance = intersectPoint.distanceTo(from);

                  if(!(pointInTriangle(intersectPoint, a, b, c) || pointInTriangle(intersectPoint, b, a, c)) || distance > fromToDistance){
                      continue;
                  }

                  this.reportIntersection(normal, intersectPoint, reportedShape, body, fi);
              }
              // }
          }
      };
      Ray.prototype[Shape.types.CONVEXPOLYHEDRON] = Ray.prototype.intersectConvex;

      var intersectTrimesh_normal = new Vec3();
      var intersectTrimesh_localDirection = new Vec3();
      var intersectTrimesh_localFrom = new Vec3();
      var intersectTrimesh_localTo = new Vec3();
      var intersectTrimesh_worldNormal = new Vec3();
      var intersectTrimesh_worldIntersectPoint = new Vec3();
      new AABB();
      var intersectTrimesh_triangles = [];
      var intersectTrimesh_treeTransform = new Transform();

      /**
       * @method intersectTrimesh
       * @private
       * @param  {Shape} shape
       * @param  {Quaternion} quat
       * @param  {Vec3} position
       * @param  {Body} body
       * @param {object} [options]
       * @todo Optimize by transforming the world to local space first.
       * @todo Use Octree lookup
       */
      Ray.prototype.intersectTrimesh = function intersectTrimesh(
          mesh,
          quat,
          position,
          body,
          reportedShape,
          options
      ){
          var normal = intersectTrimesh_normal;
          var triangles = intersectTrimesh_triangles;
          var treeTransform = intersectTrimesh_treeTransform;
          var vector = intersectConvex_vector;
          var localDirection = intersectTrimesh_localDirection;
          var localFrom = intersectTrimesh_localFrom;
          var localTo = intersectTrimesh_localTo;
          var worldIntersectPoint = intersectTrimesh_worldIntersectPoint;
          var worldNormal = intersectTrimesh_worldNormal;
          (options && options.faceList) || null;

          // Checking faces
          var indices = mesh.indices;
              mesh.vertices;
              mesh.faceNormals;

          var from = this.from;
          var to = this.to;
          var direction = this._direction;
          treeTransform.position.copy(position);
          treeTransform.quaternion.copy(quat);

          // Transform ray to local space!
          Transform.vectorToLocalFrame(position, quat, direction, localDirection);
          Transform.pointToLocalFrame(position, quat, from, localFrom);
          Transform.pointToLocalFrame(position, quat, to, localTo);

          localTo.x *= mesh.scale.x;
          localTo.y *= mesh.scale.y;
          localTo.z *= mesh.scale.z;
          localFrom.x *= mesh.scale.x;
          localFrom.y *= mesh.scale.y;
          localFrom.z *= mesh.scale.z;

          localTo.vsub(localFrom, localDirection);
          localDirection.normalize();

          var fromToDistanceSquared = localFrom.distanceSquared(localTo);

          mesh.tree.rayQuery(this, treeTransform, triangles);

          for (var i = 0, N = triangles.length; !this.result._shouldStop && i !== N; i++) {
              var trianglesIndex = triangles[i];

              mesh.getNormal(trianglesIndex, normal);

              // determine if ray intersects the plane of the face
              // note: this works regardless of the direction of the face normal

              // Get plane point in world coordinates...
              mesh.getVertex(indices[trianglesIndex * 3], a);

              // ...but make it relative to the ray from. We'll fix this later.
              a.vsub(localFrom,vector);

              // If this dot product is negative, we have something interesting
              var dot = localDirection.dot(normal);

              // Bail out if ray and plane are parallel
              // if (Math.abs( dot ) < this.precision){
              //     continue;
              // }

              // calc distance to plane
              var scalar = normal.dot(vector) / dot;

              // if negative distance, then plane is behind ray
              if (scalar < 0){
                  continue;
              }

              // Intersection point is from + direction * scalar
              localDirection.scale(scalar,intersectPoint);
              intersectPoint.vadd(localFrom,intersectPoint);

              // Get triangle vertices
              mesh.getVertex(indices[trianglesIndex * 3 + 1], b);
              mesh.getVertex(indices[trianglesIndex * 3 + 2], c);

              var squaredDistance = intersectPoint.distanceSquared(localFrom);

              if(!(pointInTriangle(intersectPoint, b, a, c) || pointInTriangle(intersectPoint, a, b, c)) || squaredDistance > fromToDistanceSquared){
                  continue;
              }

              // transform intersectpoint and normal to world
              Transform.vectorToWorldFrame(quat, normal, worldNormal);
              Transform.pointToWorldFrame(position, quat, intersectPoint, worldIntersectPoint);
              this.reportIntersection(worldNormal, worldIntersectPoint, reportedShape, body, trianglesIndex);
          }
          triangles.length = 0;
      };
      Ray.prototype[Shape.types.TRIMESH] = Ray.prototype.intersectTrimesh;


      /**
       * @method reportIntersection
       * @private
       * @param  {Vec3} normal
       * @param  {Vec3} hitPointWorld
       * @param  {Shape} shape
       * @param  {Body} body
       * @return {boolean} True if the intersections should continue
       */
      Ray.prototype.reportIntersection = function(normal, hitPointWorld, shape, body, hitFaceIndex){
          var from = this.from;
          var to = this.to;
          var distance = from.distanceTo(hitPointWorld);
          var result = this.result;

          // Skip back faces?
          if(this.skipBackfaces && normal.dot(this._direction) > 0){
              return;
          }

          result.hitFaceIndex = typeof(hitFaceIndex) !== 'undefined' ? hitFaceIndex : -1;

          switch(this.mode){
          case Ray.ALL:
              this.hasHit = true;
              result.set(
                  from,
                  to,
                  normal,
                  hitPointWorld,
                  shape,
                  body,
                  distance
              );
              result.hasHit = true;
              this.callback(result);
              break;

          case Ray.CLOSEST:

              // Store if closer than current closest
              if(distance < result.distance || !result.hasHit){
                  this.hasHit = true;
                  result.hasHit = true;
                  result.set(
                      from,
                      to,
                      normal,
                      hitPointWorld,
                      shape,
                      body,
                      distance
                  );
              }
              break;

          case Ray.ANY:

              // Report and stop.
              this.hasHit = true;
              result.hasHit = true;
              result.set(
                  from,
                  to,
                  normal,
                  hitPointWorld,
                  shape,
                  body,
                  distance
              );
              result._shouldStop = true;
              break;
          }
      };

      var v0 = new Vec3(),
          intersect = new Vec3();
      function distanceFromIntersection(from, direction, position) {

          // v0 is vector from from to position
          position.vsub(from,v0);
          var dot = v0.dot(direction);

          // intersect = direction*dot + from
          direction.mult(dot,intersect);
          intersect.vadd(from,intersect);

          var distance = position.distanceTo(intersect);

          return distance;
      }


      /**
       * per ray / body filter, return false if skip
       */
      Ray.perBodyFilter = function(ray, body) {
          if((ray.collisionFilterGroup & body.collisionFilterMask)===0 || (body.collisionFilterGroup & ray.collisionFilterMask)===0){
              return false;
          }
          return true;
      };

      /**
       * per ray / shape filter, return false if skip
       */
      Ray.perShapeFilter = function(ray, shape) {    
          if(ray.checkCollisionResponse && !shape.collisionResponse){
              return false; // Skip
          }
          return true;
      };

      },{"../collision/AABB":3,"../collision/RaycastResult":11,"../math/Quaternion":29,"../math/Transform":30,"../math/Vec3":31,"../shapes/Box":38,"../shapes/ConvexPolyhedron":39,"../shapes/Shape":44}],11:[function(_dereq_,module,exports){
      var Vec3 = _dereq_('../math/Vec3');

      module.exports = RaycastResult;

      /**
       * Storage for Ray casting data.
       * @class RaycastResult
       * @constructor
       */
      function RaycastResult(){

      	/**
      	 * @property {Vec3} rayFromWorld
      	 */
      	this.rayFromWorld = new Vec3();

      	/**
      	 * @property {Vec3} rayToWorld
      	 */
      	this.rayToWorld = new Vec3();

      	/**
      	 * @property {Vec3} hitNormalWorld
      	 */
      	this.hitNormalWorld = new Vec3();

      	/**
      	 * @property {Vec3} hitPointWorld
      	 */
      	this.hitPointWorld = new Vec3();

      	/**
      	 * @property {boolean} hasHit
      	 */
      	this.hasHit = false;

      	/**
      	 * The hit shape, or null.
      	 * @property {Shape} shape
      	 */
      	this.shape = null;

      	/**
      	 * The hit body, or null.
      	 * @property {Body} body
      	 */
      	this.body = null;

      	/**
      	 * The index of the hit triangle, if the hit shape was a trimesh.
      	 * @property {number} hitFaceIndex
      	 * @default -1
      	 */
      	this.hitFaceIndex = -1;

      	/**
      	 * Distance to the hit. Will be set to -1 if there was no hit.
      	 * @property {number} distance
      	 * @default -1
      	 */
      	this.distance = -1;

      	/**
      	 * If the ray should stop traversing the bodies.
      	 * @private
      	 * @property {Boolean} _shouldStop
      	 * @default false
      	 */
      	this._shouldStop = false;
      }

      /**
       * Reset all result data.
       * @method reset
       */
      RaycastResult.prototype.reset = function () {
      	this.rayFromWorld.setZero();
      	this.rayToWorld.setZero();
      	this.hitNormalWorld.setZero();
      	this.hitPointWorld.setZero();
      	this.hasHit = false;
      	this.shape = null;
      	this.body = null;
      	this.hitFaceIndex = -1;
      	this.distance = -1;
      	this._shouldStop = false;
      };

      /**
       * @method abort
       */
      RaycastResult.prototype.abort = function(){
      	this._shouldStop = true;
      };

      /**
       * @method set
       * @param {Vec3} rayFromWorld
       * @param {Vec3} rayToWorld
       * @param {Vec3} hitNormalWorld
       * @param {Vec3} hitPointWorld
       * @param {Shape} shape
       * @param {Body} body
       * @param {number} distance
       */
      RaycastResult.prototype.set = function(
      	rayFromWorld,
      	rayToWorld,
      	hitNormalWorld,
      	hitPointWorld,
      	shape,
      	body,
      	distance
      ){
      	this.rayFromWorld.copy(rayFromWorld);
      	this.rayToWorld.copy(rayToWorld);
      	this.hitNormalWorld.copy(hitNormalWorld);
      	this.hitPointWorld.copy(hitPointWorld);
      	this.shape = shape;
      	this.body = body;
      	this.distance = distance;
      };
      },{"../math/Vec3":31}],12:[function(_dereq_,module,exports){
      _dereq_('../shapes/Shape');
      var Broadphase = _dereq_('../collision/Broadphase');

      module.exports = SAPBroadphase;

      /**
       * Sweep and prune broadphase along one axis.
       *
       * @class SAPBroadphase
       * @constructor
       * @param {World} [world]
       * @extends Broadphase
       */
      function SAPBroadphase(world){
          Broadphase.apply(this);

          /**
           * List of bodies currently in the broadphase.
           * @property axisList
           * @type {Array}
           */
          this.axisList = [];

          /**
           * The world to search in.
           * @property world
           * @type {World}
           */
          this.world = null;

          /**
           * Axis to sort the bodies along. Set to 0 for x axis, and 1 for y axis. For best performance, choose an axis that the bodies are spread out more on.
           * @property axisIndex
           * @type {Number}
           */
          this.axisIndex = 0;

          var axisList = this.axisList;

          this._addBodyHandler = function(e){
              axisList.push(e.body);
          };

          this._removeBodyHandler = function(e){
              var idx = axisList.indexOf(e.body);
              if(idx !== -1){
                  axisList.splice(idx,1);
              }
          };

          if(world){
              this.setWorld(world);
          }
      }
      SAPBroadphase.prototype = new Broadphase();

      /**
       * Change the world
       * @method setWorld
       * @param  {World} world
       */
      SAPBroadphase.prototype.setWorld = function(world){
          // Clear the old axis array
          this.axisList.length = 0;

          // Add all bodies from the new world
          for(var i=0; i<world.bodies.length; i++){
              this.axisList.push(world.bodies[i]);
          }

          // Remove old handlers, if any
          world.removeEventListener("addBody", this._addBodyHandler);
          world.removeEventListener("removeBody", this._removeBodyHandler);

          // Add handlers to update the list of bodies.
          world.addEventListener("addBody", this._addBodyHandler);
          world.addEventListener("removeBody", this._removeBodyHandler);

          this.world = world;
          this.dirty = true;
      };

      /**
       * @static
       * @method insertionSortX
       * @param  {Array} a
       * @return {Array}
       */
      SAPBroadphase.insertionSortX = function(a) {
          for(var i=1,l=a.length;i<l;i++) {
              var v = a[i];
              for(var j=i - 1;j>=0;j--) {
                  if(a[j].aabb.lowerBound.x <= v.aabb.lowerBound.x){
                      break;
                  }
                  a[j+1] = a[j];
              }
              a[j+1] = v;
          }
          return a;
      };

      /**
       * @static
       * @method insertionSortY
       * @param  {Array} a
       * @return {Array}
       */
      SAPBroadphase.insertionSortY = function(a) {
          for(var i=1,l=a.length;i<l;i++) {
              var v = a[i];
              for(var j=i - 1;j>=0;j--) {
                  if(a[j].aabb.lowerBound.y <= v.aabb.lowerBound.y){
                      break;
                  }
                  a[j+1] = a[j];
              }
              a[j+1] = v;
          }
          return a;
      };

      /**
       * @static
       * @method insertionSortZ
       * @param  {Array} a
       * @return {Array}
       */
      SAPBroadphase.insertionSortZ = function(a) {
          for(var i=1,l=a.length;i<l;i++) {
              var v = a[i];
              for(var j=i - 1;j>=0;j--) {
                  if(a[j].aabb.lowerBound.z <= v.aabb.lowerBound.z){
                      break;
                  }
                  a[j+1] = a[j];
              }
              a[j+1] = v;
          }
          return a;
      };

      /**
       * Collect all collision pairs
       * @method collisionPairs
       * @param  {World} world
       * @param  {Array} p1
       * @param  {Array} p2
       */
      SAPBroadphase.prototype.collisionPairs = function(world,p1,p2){
          var bodies = this.axisList,
              N = bodies.length,
              axisIndex = this.axisIndex,
              i, j;

          if(this.dirty){
              this.sortList();
              this.dirty = false;
          }

          // Look through the list
          for(i=0; i !== N; i++){
              var bi = bodies[i];

              for(j=i+1; j < N; j++){
                  var bj = bodies[j];

                  if(!this.needBroadphaseCollision(bi,bj)){
                      continue;
                  }

                  if(!SAPBroadphase.checkBounds(bi,bj,axisIndex)){
                      break;
                  }

                  this.intersectionTest(bi,bj,p1,p2);
              }
          }
      };

      SAPBroadphase.prototype.sortList = function(){
          var axisList = this.axisList;
          var axisIndex = this.axisIndex;
          var N = axisList.length;

          // Update AABBs
          for(var i = 0; i!==N; i++){
              var bi = axisList[i];
              if(bi.aabbNeedsUpdate){
                  bi.computeAABB();
              }
          }

          // Sort the list
          if(axisIndex === 0){
              SAPBroadphase.insertionSortX(axisList);
          } else if(axisIndex === 1){
              SAPBroadphase.insertionSortY(axisList);
          } else if(axisIndex === 2){
              SAPBroadphase.insertionSortZ(axisList);
          }
      };

      /**
       * Check if the bounds of two bodies overlap, along the given SAP axis.
       * @static
       * @method checkBounds
       * @param  {Body} bi
       * @param  {Body} bj
       * @param  {Number} axisIndex
       * @return {Boolean}
       */
      SAPBroadphase.checkBounds = function(bi, bj, axisIndex){
          var biPos;
          var bjPos;

          if(axisIndex === 0){
              biPos = bi.position.x;
              bjPos = bj.position.x;
          } else if(axisIndex === 1){
              biPos = bi.position.y;
              bjPos = bj.position.y;
          } else if(axisIndex === 2){
              biPos = bi.position.z;
              bjPos = bj.position.z;
          }

          var ri = bi.boundingRadius,
              rj = bj.boundingRadius,
              boundA2 = biPos + ri,
              boundB1 = bjPos - rj;


          return boundB1 < boundA2;
      };

      /**
       * Computes the variance of the body positions and estimates the best
       * axis to use. Will automatically set property .axisIndex.
       * @method autoDetectAxis
       */
      SAPBroadphase.prototype.autoDetectAxis = function(){
          var sumX=0,
              sumX2=0,
              sumY=0,
              sumY2=0,
              sumZ=0,
              sumZ2=0,
              bodies = this.axisList,
              N = bodies.length,
              invN=1/N;

          for(var i=0; i!==N; i++){
              var b = bodies[i];

              var centerX = b.position.x;
              sumX += centerX;
              sumX2 += centerX*centerX;

              var centerY = b.position.y;
              sumY += centerY;
              sumY2 += centerY*centerY;

              var centerZ = b.position.z;
              sumZ += centerZ;
              sumZ2 += centerZ*centerZ;
          }

          var varianceX = sumX2 - sumX*sumX*invN,
              varianceY = sumY2 - sumY*sumY*invN,
              varianceZ = sumZ2 - sumZ*sumZ*invN;

          if(varianceX > varianceY){
              if(varianceX > varianceZ){
                  this.axisIndex = 0;
              } else {
                  this.axisIndex = 2;
              }
          } else if(varianceY > varianceZ){
              this.axisIndex = 1;
          } else {
              this.axisIndex = 2;
          }
      };

      /**
       * Returns all the bodies within an AABB.
       * @method aabbQuery
       * @param  {World} world
       * @param  {AABB} aabb
       * @param {array} result An array to store resulting bodies in.
       * @return {array}
       */
      SAPBroadphase.prototype.aabbQuery = function(world, aabb, result){
          result = result || [];

          if(this.dirty){
              this.sortList();
              this.dirty = false;
          }

          var axisIndex = this.axisIndex, axis = 'x';
          if(axisIndex === 1){ axis = 'y'; }
          if(axisIndex === 2){ axis = 'z'; }

          var axisList = this.axisList;
          aabb.lowerBound[axis];
          aabb.upperBound[axis];
          for(var i = 0; i < axisList.length; i++){
              var b = axisList[i];

              if(b.aabbNeedsUpdate){
                  b.computeAABB();
              }

              if(b.aabb.overlaps(aabb)){
                  result.push(b);
              }
          }

          return result;
      };
      },{"../collision/Broadphase":5,"../shapes/Shape":44}],13:[function(_dereq_,module,exports){
      module.exports = ConeTwistConstraint;

      _dereq_('./Constraint');
      var PointToPointConstraint = _dereq_('./PointToPointConstraint');
      var ConeEquation = _dereq_('../equations/ConeEquation');
      var RotationalEquation = _dereq_('../equations/RotationalEquation');
      _dereq_('../equations/ContactEquation');
      var Vec3 = _dereq_('../math/Vec3');

      /**
       * @class ConeTwistConstraint
       * @constructor
       * @author schteppe
       * @param {Body} bodyA
       * @param {Body} bodyB
       * @param {object} [options]
       * @param {Vec3} [options.pivotA]
       * @param {Vec3} [options.pivotB]
       * @param {Vec3} [options.axisA]
       * @param {Vec3} [options.axisB]
       * @param {Number} [options.maxForce=1e6]
       * @extends PointToPointConstraint
       */
      function ConeTwistConstraint(bodyA, bodyB, options){
          options = options || {};
          var maxForce = typeof(options.maxForce) !== 'undefined' ? options.maxForce : 1e6;

          // Set pivot point in between
          var pivotA = options.pivotA ? options.pivotA.clone() : new Vec3();
          var pivotB = options.pivotB ? options.pivotB.clone() : new Vec3();
          this.axisA = options.axisA ? options.axisA.clone() : new Vec3();
          this.axisB = options.axisB ? options.axisB.clone() : new Vec3();

          PointToPointConstraint.call(this, bodyA, pivotA, bodyB, pivotB, maxForce);

          this.collideConnected = !!options.collideConnected;

          this.angle = typeof(options.angle) !== 'undefined' ? options.angle : 0;

          /**
           * @property {ConeEquation} coneEquation
           */
          var c = this.coneEquation = new ConeEquation(bodyA,bodyB,options);

          /**
           * @property {RotationalEquation} twistEquation
           */
          var t = this.twistEquation = new RotationalEquation(bodyA,bodyB,options);
          this.twistAngle = typeof(options.twistAngle) !== 'undefined' ? options.twistAngle : 0;

          // Make the cone equation push the bodies toward the cone axis, not outward
          c.maxForce = 0;
          c.minForce = -maxForce;

          // Make the twist equation add torque toward the initial position
          t.maxForce = 0;
          t.minForce = -maxForce;

          this.equations.push(c, t);
      }
      ConeTwistConstraint.prototype = new PointToPointConstraint();
      ConeTwistConstraint.constructor = ConeTwistConstraint;

      new Vec3();
      new Vec3();

      ConeTwistConstraint.prototype.update = function(){
          var bodyA = this.bodyA,
              bodyB = this.bodyB,
              cone = this.coneEquation,
              twist = this.twistEquation;

          PointToPointConstraint.prototype.update.call(this);

          // Update the axes to the cone constraint
          bodyA.vectorToWorldFrame(this.axisA, cone.axisA);
          bodyB.vectorToWorldFrame(this.axisB, cone.axisB);

          // Update the world axes in the twist constraint
          this.axisA.tangents(twist.axisA, twist.axisA);
          bodyA.vectorToWorldFrame(twist.axisA, twist.axisA);

          this.axisB.tangents(twist.axisB, twist.axisB);
          bodyB.vectorToWorldFrame(twist.axisB, twist.axisB);

          cone.angle = this.angle;
          twist.maxAngle = this.twistAngle;
      };


      },{"../equations/ConeEquation":19,"../equations/ContactEquation":20,"../equations/RotationalEquation":23,"../math/Vec3":31,"./Constraint":14,"./PointToPointConstraint":18}],14:[function(_dereq_,module,exports){
      module.exports = Constraint;

      var Utils = _dereq_('../utils/Utils');

      /**
       * Constraint base class
       * @class Constraint
       * @author schteppe
       * @constructor
       * @param {Body} bodyA
       * @param {Body} bodyB
       * @param {object} [options]
       * @param {boolean} [options.collideConnected=true]
       * @param {boolean} [options.wakeUpBodies=true]
       */
      function Constraint(bodyA, bodyB, options){
          options = Utils.defaults(options,{
              collideConnected : true,
              wakeUpBodies : true,
          });

          /**
           * Equations to be solved in this constraint
           * @property equations
           * @type {Array}
           */
          this.equations = [];

          /**
           * @property {Body} bodyA
           */
          this.bodyA = bodyA;

          /**
           * @property {Body} bodyB
           */
          this.bodyB = bodyB;

          /**
           * @property {Number} id
           */
          this.id = Constraint.idCounter++;

          /**
           * Set to true if you want the bodies to collide when they are connected.
           * @property collideConnected
           * @type {boolean}
           */
          this.collideConnected = options.collideConnected;

          if(options.wakeUpBodies){
              if(bodyA){
                  bodyA.wakeUp();
              }
              if(bodyB){
                  bodyB.wakeUp();
              }
          }
      }

      /**
       * Update all the equations with data.
       * @method update
       */
      Constraint.prototype.update = function(){
          throw new Error("method update() not implmemented in this Constraint subclass!");
      };

      /**
       * Enables all equations in the constraint.
       * @method enable
       */
      Constraint.prototype.enable = function(){
          var eqs = this.equations;
          for(var i=0; i<eqs.length; i++){
              eqs[i].enabled = true;
          }
      };

      /**
       * Disables all equations in the constraint.
       * @method disable
       */
      Constraint.prototype.disable = function(){
          var eqs = this.equations;
          for(var i=0; i<eqs.length; i++){
              eqs[i].enabled = false;
          }
      };

      Constraint.idCounter = 0;

      },{"../utils/Utils":54}],15:[function(_dereq_,module,exports){
      module.exports = DistanceConstraint;

      var Constraint = _dereq_('./Constraint');
      var ContactEquation = _dereq_('../equations/ContactEquation');

      /**
       * Constrains two bodies to be at a constant distance from each others center of mass.
       * @class DistanceConstraint
       * @constructor
       * @author schteppe
       * @param {Body} bodyA
       * @param {Body} bodyB
       * @param {Number} [distance] The distance to keep. If undefined, it will be set to the current distance between bodyA and bodyB
       * @param {Number} [maxForce=1e6]
       * @extends Constraint
       */
      function DistanceConstraint(bodyA,bodyB,distance,maxForce){
          Constraint.call(this,bodyA,bodyB);

          if(typeof(distance)==="undefined") {
              distance = bodyA.position.distanceTo(bodyB.position);
          }

          if(typeof(maxForce)==="undefined") {
              maxForce = 1e6;
          }

          /**
           * @property {number} distance
           */
          this.distance = distance;

          /**
           * @property {ContactEquation} distanceEquation
           */
          var eq = this.distanceEquation = new ContactEquation(bodyA, bodyB);
          this.equations.push(eq);

          // Make it bidirectional
          eq.minForce = -maxForce;
          eq.maxForce =  maxForce;
      }
      DistanceConstraint.prototype = new Constraint();

      DistanceConstraint.prototype.update = function(){
          var bodyA = this.bodyA;
          var bodyB = this.bodyB;
          var eq = this.distanceEquation;
          var halfDist = this.distance * 0.5;
          var normal = eq.ni;

          bodyB.position.vsub(bodyA.position, normal);
          normal.normalize();
          normal.mult(halfDist, eq.ri);
          normal.mult(-halfDist, eq.rj);
      };
      },{"../equations/ContactEquation":20,"./Constraint":14}],16:[function(_dereq_,module,exports){
      module.exports = HingeConstraint;

      _dereq_('./Constraint');
      var PointToPointConstraint = _dereq_('./PointToPointConstraint');
      var RotationalEquation = _dereq_('../equations/RotationalEquation');
      var RotationalMotorEquation = _dereq_('../equations/RotationalMotorEquation');
      _dereq_('../equations/ContactEquation');
      var Vec3 = _dereq_('../math/Vec3');

      /**
       * Hinge constraint. Think of it as a door hinge. It tries to keep the door in the correct place and with the correct orientation.
       * @class HingeConstraint
       * @constructor
       * @author schteppe
       * @param {Body} bodyA
       * @param {Body} bodyB
       * @param {object} [options]
       * @param {Vec3} [options.pivotA] A point defined locally in bodyA. This defines the offset of axisA.
       * @param {Vec3} [options.axisA] An axis that bodyA can rotate around, defined locally in bodyA.
       * @param {Vec3} [options.pivotB]
       * @param {Vec3} [options.axisB]
       * @param {Number} [options.maxForce=1e6]
       * @extends PointToPointConstraint
       */
      function HingeConstraint(bodyA, bodyB, options){
          options = options || {};
          var maxForce = typeof(options.maxForce) !== 'undefined' ? options.maxForce : 1e6;
          var pivotA = options.pivotA ? options.pivotA.clone() : new Vec3();
          var pivotB = options.pivotB ? options.pivotB.clone() : new Vec3();

          PointToPointConstraint.call(this, bodyA, pivotA, bodyB, pivotB, maxForce);

          /**
           * Rotation axis, defined locally in bodyA.
           * @property {Vec3} axisA
           */
          var axisA = this.axisA = options.axisA ? options.axisA.clone() : new Vec3(1,0,0);
          axisA.normalize();

          /**
           * Rotation axis, defined locally in bodyB.
           * @property {Vec3} axisB
           */
          var axisB = this.axisB = options.axisB ? options.axisB.clone() : new Vec3(1,0,0);
          axisB.normalize();

          /**
           * @property {RotationalEquation} rotationalEquation1
           */
          var r1 = this.rotationalEquation1 = new RotationalEquation(bodyA,bodyB,options);

          /**
           * @property {RotationalEquation} rotationalEquation2
           */
          var r2 = this.rotationalEquation2 = new RotationalEquation(bodyA,bodyB,options);

          /**
           * @property {RotationalMotorEquation} motorEquation
           */
          var motor = this.motorEquation = new RotationalMotorEquation(bodyA,bodyB,maxForce);
          motor.enabled = false; // Not enabled by default

          // Equations to be fed to the solver
          this.equations.push(
              r1, // rotational1
              r2, // rotational2
              motor
          );
      }
      HingeConstraint.prototype = new PointToPointConstraint();
      HingeConstraint.constructor = HingeConstraint;

      /**
       * @method enableMotor
       */
      HingeConstraint.prototype.enableMotor = function(){
          this.motorEquation.enabled = true;
      };

      /**
       * @method disableMotor
       */
      HingeConstraint.prototype.disableMotor = function(){
          this.motorEquation.enabled = false;
      };

      /**
       * @method setMotorSpeed
       * @param {number} speed
       */
      HingeConstraint.prototype.setMotorSpeed = function(speed){
          this.motorEquation.targetVelocity = speed;
      };

      /**
       * @method setMotorMaxForce
       * @param {number} maxForce
       */
      HingeConstraint.prototype.setMotorMaxForce = function(maxForce){
          this.motorEquation.maxForce = maxForce;
          this.motorEquation.minForce = -maxForce;
      };

      var HingeConstraint_update_tmpVec1 = new Vec3();
      var HingeConstraint_update_tmpVec2 = new Vec3();

      HingeConstraint.prototype.update = function(){
          var bodyA = this.bodyA,
              bodyB = this.bodyB,
              motor = this.motorEquation,
              r1 = this.rotationalEquation1,
              r2 = this.rotationalEquation2,
              worldAxisA = HingeConstraint_update_tmpVec1,
              worldAxisB = HingeConstraint_update_tmpVec2;

          var axisA = this.axisA;
          var axisB = this.axisB;

          PointToPointConstraint.prototype.update.call(this);

          // Get world axes
          bodyA.quaternion.vmult(axisA, worldAxisA);
          bodyB.quaternion.vmult(axisB, worldAxisB);

          worldAxisA.tangents(r1.axisA, r2.axisA);
          r1.axisB.copy(worldAxisB);
          r2.axisB.copy(worldAxisB);

          if(this.motorEquation.enabled){
              bodyA.quaternion.vmult(this.axisA, motor.axisA);
              bodyB.quaternion.vmult(this.axisB, motor.axisB);
          }
      };


      },{"../equations/ContactEquation":20,"../equations/RotationalEquation":23,"../equations/RotationalMotorEquation":24,"../math/Vec3":31,"./Constraint":14,"./PointToPointConstraint":18}],17:[function(_dereq_,module,exports){
      module.exports = LockConstraint;

      _dereq_('./Constraint');
      var PointToPointConstraint = _dereq_('./PointToPointConstraint');
      var RotationalEquation = _dereq_('../equations/RotationalEquation');
      _dereq_('../equations/RotationalMotorEquation');
      _dereq_('../equations/ContactEquation');
      var Vec3 = _dereq_('../math/Vec3');

      /**
       * Lock constraint. Will remove all degrees of freedom between the bodies.
       * @class LockConstraint
       * @constructor
       * @author schteppe
       * @param {Body} bodyA
       * @param {Body} bodyB
       * @param {object} [options]
       * @param {Number} [options.maxForce=1e6]
       * @extends PointToPointConstraint
       */
      function LockConstraint(bodyA, bodyB, options){
          options = options || {};
          var maxForce = typeof(options.maxForce) !== 'undefined' ? options.maxForce : 1e6;

          // Set pivot point in between
          var pivotA = new Vec3();
          var pivotB = new Vec3();
          var halfWay = new Vec3();
          bodyA.position.vadd(bodyB.position, halfWay);
          halfWay.scale(0.5, halfWay);
          bodyB.pointToLocalFrame(halfWay, pivotB);
          bodyA.pointToLocalFrame(halfWay, pivotA);

          // The point-to-point constraint will keep a point shared between the bodies
          PointToPointConstraint.call(this, bodyA, pivotA, bodyB, pivotB, maxForce);

          // Store initial rotation of the bodies as unit vectors in the local body spaces
          this.xA = bodyA.vectorToLocalFrame(Vec3.UNIT_X);
          this.xB = bodyB.vectorToLocalFrame(Vec3.UNIT_X);
          this.yA = bodyA.vectorToLocalFrame(Vec3.UNIT_Y);
          this.yB = bodyB.vectorToLocalFrame(Vec3.UNIT_Y);
          this.zA = bodyA.vectorToLocalFrame(Vec3.UNIT_Z);
          this.zB = bodyB.vectorToLocalFrame(Vec3.UNIT_Z);

          // ...and the following rotational equations will keep all rotational DOF's in place

          /**
           * @property {RotationalEquation} rotationalEquation1
           */
          var r1 = this.rotationalEquation1 = new RotationalEquation(bodyA,bodyB,options);

          /**
           * @property {RotationalEquation} rotationalEquation2
           */
          var r2 = this.rotationalEquation2 = new RotationalEquation(bodyA,bodyB,options);

          /**
           * @property {RotationalEquation} rotationalEquation3
           */
          var r3 = this.rotationalEquation3 = new RotationalEquation(bodyA,bodyB,options);

          this.equations.push(r1, r2, r3);
      }
      LockConstraint.prototype = new PointToPointConstraint();
      LockConstraint.constructor = LockConstraint;

      new Vec3();
      new Vec3();

      LockConstraint.prototype.update = function(){
          var bodyA = this.bodyA,
              bodyB = this.bodyB;
              this.motorEquation;
              var r1 = this.rotationalEquation1,
              r2 = this.rotationalEquation2,
              r3 = this.rotationalEquation3;


          PointToPointConstraint.prototype.update.call(this);

          // These vector pairs must be orthogonal
          bodyA.vectorToWorldFrame(this.xA, r1.axisA);
          bodyB.vectorToWorldFrame(this.yB, r1.axisB);

          bodyA.vectorToWorldFrame(this.yA, r2.axisA);
          bodyB.vectorToWorldFrame(this.zB, r2.axisB);

          bodyA.vectorToWorldFrame(this.zA, r3.axisA);
          bodyB.vectorToWorldFrame(this.xB, r3.axisB);
      };


      },{"../equations/ContactEquation":20,"../equations/RotationalEquation":23,"../equations/RotationalMotorEquation":24,"../math/Vec3":31,"./Constraint":14,"./PointToPointConstraint":18}],18:[function(_dereq_,module,exports){
      module.exports = PointToPointConstraint;

      var Constraint = _dereq_('./Constraint');
      var ContactEquation = _dereq_('../equations/ContactEquation');
      var Vec3 = _dereq_('../math/Vec3');

      /**
       * Connects two bodies at given offset points.
       * @class PointToPointConstraint
       * @extends Constraint
       * @constructor
       * @param {Body} bodyA
       * @param {Vec3} pivotA The point relative to the center of mass of bodyA which bodyA is constrained to.
       * @param {Body} bodyB Body that will be constrained in a similar way to the same point as bodyA. We will therefore get a link between bodyA and bodyB. If not specified, bodyA will be constrained to a static point.
       * @param {Vec3} pivotB See pivotA.
       * @param {Number} maxForce The maximum force that should be applied to constrain the bodies.
       *
       * @example
       *     var bodyA = new Body({ mass: 1 });
       *     var bodyB = new Body({ mass: 1 });
       *     bodyA.position.set(-1, 0, 0);
       *     bodyB.position.set(1, 0, 0);
       *     bodyA.addShape(shapeA);
       *     bodyB.addShape(shapeB);
       *     world.addBody(bodyA);
       *     world.addBody(bodyB);
       *     var localPivotA = new Vec3(1, 0, 0);
       *     var localPivotB = new Vec3(-1, 0, 0);
       *     var constraint = new PointToPointConstraint(bodyA, localPivotA, bodyB, localPivotB);
       *     world.addConstraint(constraint);
       */
      function PointToPointConstraint(bodyA,pivotA,bodyB,pivotB,maxForce){
          Constraint.call(this,bodyA,bodyB);

          maxForce = typeof(maxForce) !== 'undefined' ? maxForce : 1e6;

          /**
           * Pivot, defined locally in bodyA.
           * @property {Vec3} pivotA
           */
          this.pivotA = pivotA ? pivotA.clone() : new Vec3();

          /**
           * Pivot, defined locally in bodyB.
           * @property {Vec3} pivotB
           */
          this.pivotB = pivotB ? pivotB.clone() : new Vec3();

          /**
           * @property {ContactEquation} equationX
           */
          var x = this.equationX = new ContactEquation(bodyA,bodyB);

          /**
           * @property {ContactEquation} equationY
           */
          var y = this.equationY = new ContactEquation(bodyA,bodyB);

          /**
           * @property {ContactEquation} equationZ
           */
          var z = this.equationZ = new ContactEquation(bodyA,bodyB);

          // Equations to be fed to the solver
          this.equations.push(x, y, z);

          // Make the equations bidirectional
          x.minForce = y.minForce = z.minForce = -maxForce;
          x.maxForce = y.maxForce = z.maxForce =  maxForce;

          x.ni.set(1, 0, 0);
          y.ni.set(0, 1, 0);
          z.ni.set(0, 0, 1);
      }
      PointToPointConstraint.prototype = new Constraint();

      PointToPointConstraint.prototype.update = function(){
          var bodyA = this.bodyA;
          var bodyB = this.bodyB;
          var x = this.equationX;
          var y = this.equationY;
          var z = this.equationZ;

          // Rotate the pivots to world space
          bodyA.quaternion.vmult(this.pivotA,x.ri);
          bodyB.quaternion.vmult(this.pivotB,x.rj);

          y.ri.copy(x.ri);
          y.rj.copy(x.rj);
          z.ri.copy(x.ri);
          z.rj.copy(x.rj);
      };
      },{"../equations/ContactEquation":20,"../math/Vec3":31,"./Constraint":14}],19:[function(_dereq_,module,exports){
      module.exports = ConeEquation;

      var Vec3 = _dereq_('../math/Vec3');
      _dereq_('../math/Mat3');
      var Equation = _dereq_('./Equation');

      /**
       * Cone equation. Works to keep the given body world vectors aligned, or tilted within a given angle from each other.
       * @class ConeEquation
       * @constructor
       * @author schteppe
       * @param {Body} bodyA
       * @param {Body} bodyB
       * @param {Vec3} [options.axisA] Local axis in A
       * @param {Vec3} [options.axisB] Local axis in B
       * @param {Vec3} [options.angle] The "cone angle" to keep
       * @param {number} [options.maxForce=1e6]
       * @extends Equation
       */
      function ConeEquation(bodyA, bodyB, options){
          options = options || {};
          var maxForce = typeof(options.maxForce) !== 'undefined' ? options.maxForce : 1e6;

          Equation.call(this,bodyA,bodyB,-maxForce, maxForce);

          this.axisA = options.axisA ? options.axisA.clone() : new Vec3(1, 0, 0);
          this.axisB = options.axisB ? options.axisB.clone() : new Vec3(0, 1, 0);

          /**
           * The cone angle to keep
           * @property {number} angle
           */
          this.angle = typeof(options.angle) !== 'undefined' ? options.angle : 0;
      }

      ConeEquation.prototype = new Equation();
      ConeEquation.prototype.constructor = ConeEquation;

      var tmpVec1 = new Vec3();
      var tmpVec2 = new Vec3();

      ConeEquation.prototype.computeB = function(h){
          var a = this.a,
              b = this.b,

              ni = this.axisA,
              nj = this.axisB,

              nixnj = tmpVec1,
              njxni = tmpVec2,

              GA = this.jacobianElementA,
              GB = this.jacobianElementB;

          // Caluclate cross products
          ni.cross(nj, nixnj);
          nj.cross(ni, njxni);

          // The angle between two vector is:
          // cos(theta) = a * b / (length(a) * length(b) = { len(a) = len(b) = 1 } = a * b

          // g = a * b
          // gdot = (b x a) * wi + (a x b) * wj
          // G = [0 bxa 0 axb]
          // W = [vi wi vj wj]
          GA.rotational.copy(njxni);
          GB.rotational.copy(nixnj);

          var g = Math.cos(this.angle) - ni.dot(nj),
              GW = this.computeGW(),
              GiMf = this.computeGiMf();

          var B = - g * a - GW * b - h * GiMf;

          return B;
      };


      },{"../math/Mat3":28,"../math/Vec3":31,"./Equation":21}],20:[function(_dereq_,module,exports){
      module.exports = ContactEquation;

      var Equation = _dereq_('./Equation');
      var Vec3 = _dereq_('../math/Vec3');
      _dereq_('../math/Mat3');

      /**
       * Contact/non-penetration constraint equation
       * @class ContactEquation
       * @constructor
       * @author schteppe
       * @param {Body} bodyA
       * @param {Body} bodyB
       * @extends Equation
       */
      function ContactEquation(bodyA, bodyB, maxForce){
          maxForce = typeof(maxForce) !== 'undefined' ? maxForce : 1e6;
          Equation.call(this, bodyA, bodyB, 0, maxForce);

          /**
           * @property si
           * @type {Shape}
           */
          this.si = null;

          /**
           * @property sj
           * @type {Shape}
           */
          this.sj = null;
          
          /**
           * @property restitution
           * @type {Number}
           */
          this.restitution = 0.0; // "bounciness": u1 = -e*u0

          /**
           * World-oriented vector that goes from the center of bi to the contact point.
           * @property {Vec3} ri
           */
          this.ri = new Vec3();

          /**
           * World-oriented vector that starts in body j position and goes to the contact point.
           * @property {Vec3} rj
           */
          this.rj = new Vec3();

          /**
           * Contact normal, pointing out of body i.
           * @property {Vec3} ni
           */
          this.ni = new Vec3();
      }

      ContactEquation.prototype = new Equation();
      ContactEquation.prototype.constructor = ContactEquation;

      var ContactEquation_computeB_temp1 = new Vec3(); // Temp vectors
      var ContactEquation_computeB_temp2 = new Vec3();
      var ContactEquation_computeB_temp3 = new Vec3();
      ContactEquation.prototype.computeB = function(h){
          var a = this.a,
              b = this.b,
              bi = this.bi,
              bj = this.bj,
              ri = this.ri,
              rj = this.rj,
              rixn = ContactEquation_computeB_temp1,
              rjxn = ContactEquation_computeB_temp2,

              vi = bi.velocity,
              wi = bi.angularVelocity;
              bi.force;
              bi.torque;

              var vj = bj.velocity,
              wj = bj.angularVelocity;
              bj.force;
              bj.torque;

              var penetrationVec = ContactEquation_computeB_temp3,

              GA = this.jacobianElementA,
              GB = this.jacobianElementB,

              n = this.ni;

          // Caluclate cross products
          ri.cross(n,rixn);
          rj.cross(n,rjxn);

          // g = xj+rj -(xi+ri)
          // G = [ -ni  -rixn  ni  rjxn ]
          n.negate(GA.spatial);
          rixn.negate(GA.rotational);
          GB.spatial.copy(n);
          GB.rotational.copy(rjxn);

          // Calculate the penetration vector
          penetrationVec.copy(bj.position);
          penetrationVec.vadd(rj,penetrationVec);
          penetrationVec.vsub(bi.position,penetrationVec);
          penetrationVec.vsub(ri,penetrationVec);

          var g = n.dot(penetrationVec);

          // Compute iteration
          var ePlusOne = this.restitution + 1;
          var GW = ePlusOne * vj.dot(n) - ePlusOne * vi.dot(n) + wj.dot(rjxn) - wi.dot(rixn);
          var GiMf = this.computeGiMf();

          var B = - g * a - GW * b - h*GiMf;

          return B;
      };

      var ContactEquation_getImpactVelocityAlongNormal_vi = new Vec3();
      var ContactEquation_getImpactVelocityAlongNormal_vj = new Vec3();
      var ContactEquation_getImpactVelocityAlongNormal_xi = new Vec3();
      var ContactEquation_getImpactVelocityAlongNormal_xj = new Vec3();
      var ContactEquation_getImpactVelocityAlongNormal_relVel = new Vec3();

      /**
       * Get the current relative velocity in the contact point.
       * @method getImpactVelocityAlongNormal
       * @return {number}
       */
      ContactEquation.prototype.getImpactVelocityAlongNormal = function(){
          var vi = ContactEquation_getImpactVelocityAlongNormal_vi;
          var vj = ContactEquation_getImpactVelocityAlongNormal_vj;
          var xi = ContactEquation_getImpactVelocityAlongNormal_xi;
          var xj = ContactEquation_getImpactVelocityAlongNormal_xj;
          var relVel = ContactEquation_getImpactVelocityAlongNormal_relVel;

          this.bi.position.vadd(this.ri, xi);
          this.bj.position.vadd(this.rj, xj);

          this.bi.getVelocityAtWorldPoint(xi, vi);
          this.bj.getVelocityAtWorldPoint(xj, vj);

          vi.vsub(vj, relVel);

          return this.ni.dot(relVel);
      };


      },{"../math/Mat3":28,"../math/Vec3":31,"./Equation":21}],21:[function(_dereq_,module,exports){
      module.exports = Equation;

      var JacobianElement = _dereq_('../math/JacobianElement'),
          Vec3 = _dereq_('../math/Vec3');

      /**
       * Equation base class
       * @class Equation
       * @constructor
       * @author schteppe
       * @param {Body} bi
       * @param {Body} bj
       * @param {Number} minForce Minimum (read: negative max) force to be applied by the constraint.
       * @param {Number} maxForce Maximum (read: positive max) force to be applied by the constraint.
       */
      function Equation(bi,bj,minForce,maxForce){
          this.id = Equation.id++;

          /**
           * @property {number} minForce
           */
          this.minForce = typeof(minForce)==="undefined" ? -1e6 : minForce;

          /**
           * @property {number} maxForce
           */
          this.maxForce = typeof(maxForce)==="undefined" ? 1e6 : maxForce;

          /**
           * @property bi
           * @type {Body}
           */
          this.bi = bi;

          /**
           * @property bj
           * @type {Body}
           */
          this.bj = bj;

          /**
           * SPOOK parameter
           * @property {number} a
           */
          this.a = 0.0;

          /**
           * SPOOK parameter
           * @property {number} b
           */
          this.b = 0.0;

          /**
           * SPOOK parameter
           * @property {number} eps
           */
          this.eps = 0.0;

          /**
           * @property {JacobianElement} jacobianElementA
           */
          this.jacobianElementA = new JacobianElement();

          /**
           * @property {JacobianElement} jacobianElementB
           */
          this.jacobianElementB = new JacobianElement();

          /**
           * @property {boolean} enabled
           * @default true
           */
          this.enabled = true;

          /**
           * A number, proportional to the force added to the bodies.
           * @property {number} multiplier
           * @readonly
           */
          this.multiplier = 0;

          // Set typical spook params
          this.setSpookParams(1e7,4,1/60);
      }
      Equation.prototype.constructor = Equation;

      Equation.id = 0;

      /**
       * Recalculates a,b,eps.
       * @method setSpookParams
       */
      Equation.prototype.setSpookParams = function(stiffness,relaxation,timeStep){
          var d = relaxation,
              k = stiffness,
              h = timeStep;
          this.a = 4.0 / (h * (1 + 4 * d));
          this.b = (4.0 * d) / (1 + 4 * d);
          this.eps = 4.0 / (h * h * k * (1 + 4 * d));
      };

      /**
       * Computes the RHS of the SPOOK equation
       * @method computeB
       * @return {Number}
       */
      Equation.prototype.computeB = function(a,b,h){
          var GW = this.computeGW(),
              Gq = this.computeGq(),
              GiMf = this.computeGiMf();
          return - Gq * a - GW * b - GiMf*h;
      };

      /**
       * Computes G*q, where q are the generalized body coordinates
       * @method computeGq
       * @return {Number}
       */
      Equation.prototype.computeGq = function(){
          var GA = this.jacobianElementA,
              GB = this.jacobianElementB,
              bi = this.bi,
              bj = this.bj,
              xi = bi.position,
              xj = bj.position;
          return GA.spatial.dot(xi) + GB.spatial.dot(xj);
      };

      new Vec3();

      /**
       * Computes G*W, where W are the body velocities
       * @method computeGW
       * @return {Number}
       */
      Equation.prototype.computeGW = function(){
          var GA = this.jacobianElementA,
              GB = this.jacobianElementB,
              bi = this.bi,
              bj = this.bj,
              vi = bi.velocity,
              vj = bj.velocity,
              wi = bi.angularVelocity,
              wj = bj.angularVelocity;
          return GA.multiplyVectors(vi,wi) + GB.multiplyVectors(vj,wj);
      };


      /**
       * Computes G*Wlambda, where W are the body velocities
       * @method computeGWlambda
       * @return {Number}
       */
      Equation.prototype.computeGWlambda = function(){
          var GA = this.jacobianElementA,
              GB = this.jacobianElementB,
              bi = this.bi,
              bj = this.bj,
              vi = bi.vlambda,
              vj = bj.vlambda,
              wi = bi.wlambda,
              wj = bj.wlambda;
          return GA.multiplyVectors(vi,wi) + GB.multiplyVectors(vj,wj);
      };

      /**
       * Computes G*inv(M)*f, where M is the mass matrix with diagonal blocks for each body, and f are the forces on the bodies.
       * @method computeGiMf
       * @return {Number}
       */
      var iMfi = new Vec3(),
          iMfj = new Vec3(),
          invIi_vmult_taui = new Vec3(),
          invIj_vmult_tauj = new Vec3();
      Equation.prototype.computeGiMf = function(){
          var GA = this.jacobianElementA,
              GB = this.jacobianElementB,
              bi = this.bi,
              bj = this.bj,
              fi = bi.force,
              ti = bi.torque,
              fj = bj.force,
              tj = bj.torque,
              invMassi = bi.invMassSolve,
              invMassj = bj.invMassSolve;

          fi.scale(invMassi,iMfi);
          fj.scale(invMassj,iMfj);

          bi.invInertiaWorldSolve.vmult(ti,invIi_vmult_taui);
          bj.invInertiaWorldSolve.vmult(tj,invIj_vmult_tauj);

          return GA.multiplyVectors(iMfi,invIi_vmult_taui) + GB.multiplyVectors(iMfj,invIj_vmult_tauj);
      };

      /**
       * Computes G*inv(M)*G'
       * @method computeGiMGt
       * @return {Number}
       */
      var tmp = new Vec3();
      Equation.prototype.computeGiMGt = function(){
          var GA = this.jacobianElementA,
              GB = this.jacobianElementB,
              bi = this.bi,
              bj = this.bj,
              invMassi = bi.invMassSolve,
              invMassj = bj.invMassSolve,
              invIi = bi.invInertiaWorldSolve,
              invIj = bj.invInertiaWorldSolve,
              result = invMassi + invMassj;

          invIi.vmult(GA.rotational,tmp);
          result += tmp.dot(GA.rotational);

          invIj.vmult(GB.rotational,tmp);
          result += tmp.dot(GB.rotational);

          return  result;
      };

      var addToWlambda_temp = new Vec3();
          new Vec3();
          new Vec3();
          new Vec3();
          new Vec3();
          new Vec3();

      /**
       * Add constraint velocity to the bodies.
       * @method addToWlambda
       * @param {Number} deltalambda
       */
      Equation.prototype.addToWlambda = function(deltalambda){
          var GA = this.jacobianElementA,
              GB = this.jacobianElementB,
              bi = this.bi,
              bj = this.bj,
              temp = addToWlambda_temp;

          // Add to linear velocity
          // v_lambda += inv(M) * delta_lamba * G
          bi.vlambda.addScaledVector(bi.invMassSolve * deltalambda, GA.spatial, bi.vlambda);
          bj.vlambda.addScaledVector(bj.invMassSolve * deltalambda, GB.spatial, bj.vlambda);

          // Add to angular velocity
          bi.invInertiaWorldSolve.vmult(GA.rotational,temp);
          bi.wlambda.addScaledVector(deltalambda, temp, bi.wlambda);

          bj.invInertiaWorldSolve.vmult(GB.rotational,temp);
          bj.wlambda.addScaledVector(deltalambda, temp, bj.wlambda);
      };

      /**
       * Compute the denominator part of the SPOOK equation: C = G*inv(M)*G' + eps
       * @method computeInvC
       * @param  {Number} eps
       * @return {Number}
       */
      Equation.prototype.computeC = function(){
          return this.computeGiMGt() + this.eps;
      };

      },{"../math/JacobianElement":27,"../math/Vec3":31}],22:[function(_dereq_,module,exports){
      module.exports = FrictionEquation;

      var Equation = _dereq_('./Equation');
      var Vec3 = _dereq_('../math/Vec3');
      _dereq_('../math/Mat3');

      /**
       * Constrains the slipping in a contact along a tangent
       * @class FrictionEquation
       * @constructor
       * @author schteppe
       * @param {Body} bodyA
       * @param {Body} bodyB
       * @param {Number} slipForce should be +-F_friction = +-mu * F_normal = +-mu * m * g
       * @extends Equation
       */
      function FrictionEquation(bodyA, bodyB, slipForce){
          Equation.call(this,bodyA, bodyB, -slipForce, slipForce);
          this.ri = new Vec3();
          this.rj = new Vec3();
          this.t = new Vec3(); // tangent
      }

      FrictionEquation.prototype = new Equation();
      FrictionEquation.prototype.constructor = FrictionEquation;

      var FrictionEquation_computeB_temp1 = new Vec3();
      var FrictionEquation_computeB_temp2 = new Vec3();
      FrictionEquation.prototype.computeB = function(h){
          this.a;
              var b = this.b;
              this.bi;
              this.bj;
              var ri = this.ri,
              rj = this.rj,
              rixt = FrictionEquation_computeB_temp1,
              rjxt = FrictionEquation_computeB_temp2,
              t = this.t;

          // Caluclate cross products
          ri.cross(t,rixt);
          rj.cross(t,rjxt);

          // G = [-t -rixt t rjxt]
          // And remember, this is a pure velocity constraint, g is always zero!
          var GA = this.jacobianElementA,
              GB = this.jacobianElementB;
          t.negate(GA.spatial);
          rixt.negate(GA.rotational);
          GB.spatial.copy(t);
          GB.rotational.copy(rjxt);

          var GW = this.computeGW();
          var GiMf = this.computeGiMf();

          var B = - GW * b - h * GiMf;

          return B;
      };

      },{"../math/Mat3":28,"../math/Vec3":31,"./Equation":21}],23:[function(_dereq_,module,exports){
      module.exports = RotationalEquation;

      var Vec3 = _dereq_('../math/Vec3');
      _dereq_('../math/Mat3');
      var Equation = _dereq_('./Equation');

      /**
       * Rotational constraint. Works to keep the local vectors orthogonal to each other in world space.
       * @class RotationalEquation
       * @constructor
       * @author schteppe
       * @param {Body} bodyA
       * @param {Body} bodyB
       * @param {Vec3} [options.axisA]
       * @param {Vec3} [options.axisB]
       * @param {number} [options.maxForce]
       * @extends Equation
       */
      function RotationalEquation(bodyA, bodyB, options){
          options = options || {};
          var maxForce = typeof(options.maxForce) !== 'undefined' ? options.maxForce : 1e6;

          Equation.call(this,bodyA,bodyB,-maxForce, maxForce);

          this.axisA = options.axisA ? options.axisA.clone() : new Vec3(1, 0, 0);
          this.axisB = options.axisB ? options.axisB.clone() : new Vec3(0, 1, 0);

          this.maxAngle = Math.PI / 2;
      }

      RotationalEquation.prototype = new Equation();
      RotationalEquation.prototype.constructor = RotationalEquation;

      var tmpVec1 = new Vec3();
      var tmpVec2 = new Vec3();

      RotationalEquation.prototype.computeB = function(h){
          var a = this.a,
              b = this.b,

              ni = this.axisA,
              nj = this.axisB,

              nixnj = tmpVec1,
              njxni = tmpVec2,

              GA = this.jacobianElementA,
              GB = this.jacobianElementB;

          // Caluclate cross products
          ni.cross(nj, nixnj);
          nj.cross(ni, njxni);

          // g = ni * nj
          // gdot = (nj x ni) * wi + (ni x nj) * wj
          // G = [0 njxni 0 nixnj]
          // W = [vi wi vj wj]
          GA.rotational.copy(njxni);
          GB.rotational.copy(nixnj);

          var g = Math.cos(this.maxAngle) - ni.dot(nj),
              GW = this.computeGW(),
              GiMf = this.computeGiMf();

          var B = - g * a - GW * b - h * GiMf;

          return B;
      };


      },{"../math/Mat3":28,"../math/Vec3":31,"./Equation":21}],24:[function(_dereq_,module,exports){
      module.exports = RotationalMotorEquation;

      var Vec3 = _dereq_('../math/Vec3');
      _dereq_('../math/Mat3');
      var Equation = _dereq_('./Equation');

      /**
       * Rotational motor constraint. Tries to keep the relative angular velocity of the bodies to a given value.
       * @class RotationalMotorEquation
       * @constructor
       * @author schteppe
       * @param {Body} bodyA
       * @param {Body} bodyB
       * @param {Number} maxForce
       * @extends Equation
       */
      function RotationalMotorEquation(bodyA, bodyB, maxForce){
          maxForce = typeof(maxForce)!=='undefined' ? maxForce : 1e6;
          Equation.call(this,bodyA,bodyB,-maxForce,maxForce);

          /**
           * World oriented rotational axis
           * @property {Vec3} axisA
           */
          this.axisA = new Vec3();

          /**
           * World oriented rotational axis
           * @property {Vec3} axisB
           */
          this.axisB = new Vec3(); // World oriented rotational axis

          /**
           * Motor velocity
           * @property {Number} targetVelocity
           */
          this.targetVelocity = 0;
      }

      RotationalMotorEquation.prototype = new Equation();
      RotationalMotorEquation.prototype.constructor = RotationalMotorEquation;

      RotationalMotorEquation.prototype.computeB = function(h){
          this.a;
              var b = this.b;
              this.bi;
              this.bj;

              var axisA = this.axisA,
              axisB = this.axisB,

              GA = this.jacobianElementA,
              GB = this.jacobianElementB;

          // g = 0
          // gdot = axisA * wi - axisB * wj
          // gdot = G * W = G * [vi wi vj wj]
          // =>
          // G = [0 axisA 0 -axisB]

          GA.rotational.copy(axisA);
          axisB.negate(GB.rotational);

          var GW = this.computeGW() - this.targetVelocity,
              GiMf = this.computeGiMf();

          var B = - GW * b - h * GiMf;

          return B;
      };

      },{"../math/Mat3":28,"../math/Vec3":31,"./Equation":21}],25:[function(_dereq_,module,exports){
      var Utils = _dereq_('../utils/Utils');

      module.exports = ContactMaterial;

      /**
       * Defines what happens when two materials meet.
       * @class ContactMaterial
       * @constructor
       * @param {Material} m1
       * @param {Material} m2
       * @param {object} [options]
       * @param {Number} [options.friction=0.3]
       * @param {Number} [options.restitution=0.3]
       * @param {number} [options.contactEquationStiffness=1e7]
       * @param {number} [options.contactEquationRelaxation=3]
       * @param {number} [options.frictionEquationStiffness=1e7]
       * @param {Number} [options.frictionEquationRelaxation=3]
       */
      function ContactMaterial(m1, m2, options){
          options = Utils.defaults(options, {
              friction: 0.3,
              restitution: 0.3,
              contactEquationStiffness: 1e7,
              contactEquationRelaxation: 3,
              frictionEquationStiffness: 1e7,
              frictionEquationRelaxation: 3
          });

          /**
           * Identifier of this material
           * @property {Number} id
           */
          this.id = ContactMaterial.idCounter++;

          /**
           * Participating materials
           * @property {Array} materials
           * @todo  Should be .materialA and .materialB instead
           */
          this.materials = [m1, m2];

          /**
           * Friction coefficient
           * @property {Number} friction
           */
          this.friction = options.friction;

          /**
           * Restitution coefficient
           * @property {Number} restitution
           */
          this.restitution = options.restitution;

          /**
           * Stiffness of the produced contact equations
           * @property {Number} contactEquationStiffness
           */
          this.contactEquationStiffness = options.contactEquationStiffness;

          /**
           * Relaxation time of the produced contact equations
           * @property {Number} contactEquationRelaxation
           */
          this.contactEquationRelaxation = options.contactEquationRelaxation;

          /**
           * Stiffness of the produced friction equations
           * @property {Number} frictionEquationStiffness
           */
          this.frictionEquationStiffness = options.frictionEquationStiffness;

          /**
           * Relaxation time of the produced friction equations
           * @property {Number} frictionEquationRelaxation
           */
          this.frictionEquationRelaxation = options.frictionEquationRelaxation;
      }

      ContactMaterial.idCounter = 0;

      },{"../utils/Utils":54}],26:[function(_dereq_,module,exports){
      module.exports = Material;

      /**
       * Defines a physics material.
       * @class Material
       * @constructor
       * @param {object} [options]
       * @author schteppe
       */
      function Material(options){
          var name = '';
          options = options || {};

          // Backwards compatibility fix
          if(typeof(options) === 'string'){
              name = options;
              options = {};
          } else if(typeof(options) === 'object') {
              name = '';
          }

          /**
           * @property name
           * @type {String}
           */
          this.name = name;

          /**
           * material id.
           * @property id
           * @type {number}
           */
          this.id = Material.idCounter++;

          /**
           * Friction for this material. If non-negative, it will be used instead of the friction given by ContactMaterials. If there's no matching ContactMaterial, the value from .defaultContactMaterial in the World will be used.
           * @property {number} friction
           */
          this.friction = typeof(options.friction) !== 'undefined' ? options.friction : -1;

          /**
           * Restitution for this material. If non-negative, it will be used instead of the restitution given by ContactMaterials. If there's no matching ContactMaterial, the value from .defaultContactMaterial in the World will be used.
           * @property {number} restitution
           */
          this.restitution = typeof(options.restitution) !== 'undefined' ? options.restitution : -1;

          this.correctInelastic = 0;
      }

      Material.idCounter = 0;

      },{}],27:[function(_dereq_,module,exports){
      module.exports = JacobianElement;

      var Vec3 = _dereq_('./Vec3');

      /**
       * An element containing 6 entries, 3 spatial and 3 rotational degrees of freedom.
       * @class JacobianElement
       * @constructor
       */
      function JacobianElement(){

          /**
           * @property {Vec3} spatial
           */
          this.spatial = new Vec3();

          /**
           * @property {Vec3} rotational
           */
          this.rotational = new Vec3();
      }

      /**
       * Multiply with other JacobianElement
       * @method multiplyElement
       * @param  {JacobianElement} element
       * @return {Number}
       */
      JacobianElement.prototype.multiplyElement = function(element){
          return element.spatial.dot(this.spatial) + element.rotational.dot(this.rotational);
      };

      /**
       * Multiply with two vectors
       * @method multiplyVectors
       * @param  {Vec3} spatial
       * @param  {Vec3} rotational
       * @return {Number}
       */
      JacobianElement.prototype.multiplyVectors = function(spatial,rotational){
          return spatial.dot(this.spatial) + rotational.dot(this.rotational);
      };

      },{"./Vec3":31}],28:[function(_dereq_,module,exports){
      module.exports = Mat3;

      var Vec3 = _dereq_('./Vec3');

      /**
       * A 3x3 matrix.
       * @class Mat3
       * @constructor
       * @param array elements Array of nine elements. Optional.
       * @author schteppe / http://github.com/schteppe
       */
      function Mat3(elements){
          /**
           * A vector of length 9, containing all matrix elements
           * @property {Array} elements
           */
          if(elements){
              this.elements = elements;
          } else {
              this.elements = [0,0,0,0,0,0,0,0,0];
          }
      }

      /**
       * Sets the matrix to identity
       * @method identity
       * @todo Should perhaps be renamed to setIdentity() to be more clear.
       * @todo Create another function that immediately creates an identity matrix eg. eye()
       */
      Mat3.prototype.identity = function(){
          var e = this.elements;
          e[0] = 1;
          e[1] = 0;
          e[2] = 0;

          e[3] = 0;
          e[4] = 1;
          e[5] = 0;

          e[6] = 0;
          e[7] = 0;
          e[8] = 1;
      };

      /**
       * Set all elements to zero
       * @method setZero
       */
      Mat3.prototype.setZero = function(){
          var e = this.elements;
          e[0] = 0;
          e[1] = 0;
          e[2] = 0;
          e[3] = 0;
          e[4] = 0;
          e[5] = 0;
          e[6] = 0;
          e[7] = 0;
          e[8] = 0;
      };

      /**
       * Sets the matrix diagonal elements from a Vec3
       * @method setTrace
       * @param {Vec3} vec3
       */
      Mat3.prototype.setTrace = function(vec3){
          var e = this.elements;
          e[0] = vec3.x;
          e[4] = vec3.y;
          e[8] = vec3.z;
      };

      /**
       * Gets the matrix diagonal elements
       * @method getTrace
       * @return {Vec3}
       */
      Mat3.prototype.getTrace = function(target){
          var target = target || new Vec3();
          var e = this.elements;
          target.x = e[0];
          target.y = e[4];
          target.z = e[8];
      };

      /**
       * Matrix-Vector multiplication
       * @method vmult
       * @param {Vec3} v The vector to multiply with
       * @param {Vec3} target Optional, target to save the result in.
       */
      Mat3.prototype.vmult = function(v,target){
          target = target || new Vec3();

          var e = this.elements,
              x = v.x,
              y = v.y,
              z = v.z;
          target.x = e[0]*x + e[1]*y + e[2]*z;
          target.y = e[3]*x + e[4]*y + e[5]*z;
          target.z = e[6]*x + e[7]*y + e[8]*z;

          return target;
      };

      /**
       * Matrix-scalar multiplication
       * @method smult
       * @param {Number} s
       */
      Mat3.prototype.smult = function(s){
          for(var i=0; i<this.elements.length; i++){
              this.elements[i] *= s;
          }
      };

      /**
       * Matrix multiplication
       * @method mmult
       * @param {Mat3} m Matrix to multiply with from left side.
       * @return {Mat3} The result.
       */
      Mat3.prototype.mmult = function(m,target){
          var r = target || new Mat3();
          for(var i=0; i<3; i++){
              for(var j=0; j<3; j++){
                  var sum = 0.0;
                  for(var k=0; k<3; k++){
                      sum += m.elements[i+k*3] * this.elements[k+j*3];
                  }
                  r.elements[i+j*3] = sum;
              }
          }
          return r;
      };

      /**
       * Scale each column of the matrix
       * @method scale
       * @param {Vec3} v
       * @return {Mat3} The result.
       */
      Mat3.prototype.scale = function(v,target){
          target = target || new Mat3();
          var e = this.elements,
              t = target.elements;
          for(var i=0; i!==3; i++){
              t[3*i + 0] = v.x * e[3*i + 0];
              t[3*i + 1] = v.y * e[3*i + 1];
              t[3*i + 2] = v.z * e[3*i + 2];
          }
          return target;
      };

      /**
       * Solve Ax=b
       * @method solve
       * @param {Vec3} b The right hand side
       * @param {Vec3} target Optional. Target vector to save in.
       * @return {Vec3} The solution x
       * @todo should reuse arrays
       */
      Mat3.prototype.solve = function(b,target){
          target = target || new Vec3();

          // Construct equations
          var nr = 3; // num rows
          var nc = 4; // num cols
          var eqns = [];
          for(var i=0; i<nr*nc; i++){
              eqns.push(0);
          }
          var i,j;
          for(i=0; i<3; i++){
              for(j=0; j<3; j++){
                  eqns[i+nc*j] = this.elements[i+3*j];
              }
          }
          eqns[3+4*0] = b.x;
          eqns[3+4*1] = b.y;
          eqns[3+4*2] = b.z;

          // Compute right upper triangular version of the matrix - Gauss elimination
          var n = 3, k = n, np;
          var kp = 4; // num rows
          var p;
          do {
              i = k - n;
              if (eqns[i+nc*i] === 0) {
                  // the pivot is null, swap lines
                  for (j = i + 1; j < k; j++) {
                      if (eqns[i+nc*j] !== 0) {
                          np = kp;
                          do {  // do ligne( i ) = ligne( i ) + ligne( k )
                              p = kp - np;
                              eqns[p+nc*i] += eqns[p+nc*j];
                          } while (--np);
                          break;
                      }
                  }
              }
              if (eqns[i+nc*i] !== 0) {
                  for (j = i + 1; j < k; j++) {
                      var multiplier = eqns[i+nc*j] / eqns[i+nc*i];
                      np = kp;
                      do {  // do ligne( k ) = ligne( k ) - multiplier * ligne( i )
                          p = kp - np;
                          eqns[p+nc*j] = p <= i ? 0 : eqns[p+nc*j] - eqns[p+nc*i] * multiplier ;
                      } while (--np);
                  }
              }
          } while (--n);

          // Get the solution
          target.z = eqns[2*nc+3] / eqns[2*nc+2];
          target.y = (eqns[1*nc+3] - eqns[1*nc+2]*target.z) / eqns[1*nc+1];
          target.x = (eqns[0*nc+3] - eqns[0*nc+2]*target.z - eqns[0*nc+1]*target.y) / eqns[0*nc+0];

          if(isNaN(target.x) || isNaN(target.y) || isNaN(target.z) || target.x===Infinity || target.y===Infinity || target.z===Infinity){
              throw "Could not solve equation! Got x=["+target.toString()+"], b=["+b.toString()+"], A=["+this.toString()+"]";
          }

          return target;
      };

      /**
       * Get an element in the matrix by index. Index starts at 0, not 1!!!
       * @method e
       * @param {Number} row
       * @param {Number} column
       * @param {Number} value Optional. If provided, the matrix element will be set to this value.
       * @return {Number}
       */
      Mat3.prototype.e = function( row , column ,value){
          if(value===undefined){
              return this.elements[column+3*row];
          } else {
              // Set value
              this.elements[column+3*row] = value;
          }
      };

      /**
       * Copy another matrix into this matrix object.
       * @method copy
       * @param {Mat3} source
       * @return {Mat3} this
       */
      Mat3.prototype.copy = function(source){
          for(var i=0; i < source.elements.length; i++){
              this.elements[i] = source.elements[i];
          }
          return this;
      };

      /**
       * Returns a string representation of the matrix.
       * @method toString
       * @return string
       */
      Mat3.prototype.toString = function(){
          var r = "";
          var sep = ",";
          for(var i=0; i<9; i++){
              r += this.elements[i] + sep;
          }
          return r;
      };

      /**
       * reverse the matrix
       * @method reverse
       * @param {Mat3} target Optional. Target matrix to save in.
       * @return {Mat3} The solution x
       */
      Mat3.prototype.reverse = function(target){

          target = target || new Mat3();

          // Construct equations
          var nr = 3; // num rows
          var nc = 6; // num cols
          var eqns = [];
          for(var i=0; i<nr*nc; i++){
              eqns.push(0);
          }
          var i,j;
          for(i=0; i<3; i++){
              for(j=0; j<3; j++){
                  eqns[i+nc*j] = this.elements[i+3*j];
              }
          }
          eqns[3+6*0] = 1;
          eqns[3+6*1] = 0;
          eqns[3+6*2] = 0;
          eqns[4+6*0] = 0;
          eqns[4+6*1] = 1;
          eqns[4+6*2] = 0;
          eqns[5+6*0] = 0;
          eqns[5+6*1] = 0;
          eqns[5+6*2] = 1;

          // Compute right upper triangular version of the matrix - Gauss elimination
          var n = 3, k = n, np;
          var kp = nc; // num rows
          var p;
          do {
              i = k - n;
              if (eqns[i+nc*i] === 0) {
                  // the pivot is null, swap lines
                  for (j = i + 1; j < k; j++) {
                      if (eqns[i+nc*j] !== 0) {
                          np = kp;
                          do { // do line( i ) = line( i ) + line( k )
                              p = kp - np;
                              eqns[p+nc*i] += eqns[p+nc*j];
                          } while (--np);
                          break;
                      }
                  }
              }
              if (eqns[i+nc*i] !== 0) {
                  for (j = i + 1; j < k; j++) {
                      var multiplier = eqns[i+nc*j] / eqns[i+nc*i];
                      np = kp;
                      do { // do line( k ) = line( k ) - multiplier * line( i )
                          p = kp - np;
                          eqns[p+nc*j] = p <= i ? 0 : eqns[p+nc*j] - eqns[p+nc*i] * multiplier ;
                      } while (--np);
                  }
              }
          } while (--n);

          // eliminate the upper left triangle of the matrix
          i = 2;
          do {
              j = i-1;
              do {
                  var multiplier = eqns[i+nc*j] / eqns[i+nc*i];
                  np = nc;
                  do {
                      p = nc - np;
                      eqns[p+nc*j] =  eqns[p+nc*j] - eqns[p+nc*i] * multiplier ;
                  } while (--np);
              } while (j--);
          } while (--i);

          // operations on the diagonal
          i = 2;
          do {
              var multiplier = 1 / eqns[i+nc*i];
              np = nc;
              do {
                  p = nc - np;
                  eqns[p+nc*i] = eqns[p+nc*i] * multiplier ;
              } while (--np);
          } while (i--);

          i = 2;
          do {
              j = 2;
              do {
                  p = eqns[nr+j+nc*i];
                  if( isNaN( p ) || p ===Infinity ){
                      throw "Could not reverse! A=["+this.toString()+"]";
                  }
                  target.e( i , j , p );
              } while (j--);
          } while (i--);

          return target;
      };

      /**
       * Set the matrix from a quaterion
       * @method setRotationFromQuaternion
       * @param {Quaternion} q
       */
      Mat3.prototype.setRotationFromQuaternion = function( q ) {
          var x = q.x, y = q.y, z = q.z, w = q.w,
              x2 = x + x, y2 = y + y, z2 = z + z,
              xx = x * x2, xy = x * y2, xz = x * z2,
              yy = y * y2, yz = y * z2, zz = z * z2,
              wx = w * x2, wy = w * y2, wz = w * z2,
              e = this.elements;

          e[3*0 + 0] = 1 - ( yy + zz );
          e[3*0 + 1] = xy - wz;
          e[3*0 + 2] = xz + wy;

          e[3*1 + 0] = xy + wz;
          e[3*1 + 1] = 1 - ( xx + zz );
          e[3*1 + 2] = yz - wx;

          e[3*2 + 0] = xz - wy;
          e[3*2 + 1] = yz + wx;
          e[3*2 + 2] = 1 - ( xx + yy );

          return this;
      };

      /**
       * Transpose the matrix
       * @method transpose
       * @param  {Mat3} target Where to store the result.
       * @return {Mat3} The target Mat3, or a new Mat3 if target was omitted.
       */
      Mat3.prototype.transpose = function( target ) {
          target = target || new Mat3();

          var Mt = target.elements,
              M = this.elements;

          for(var i=0; i!==3; i++){
              for(var j=0; j!==3; j++){
                  Mt[3*i + j] = M[3*j + i];
              }
          }

          return target;
      };

      },{"./Vec3":31}],29:[function(_dereq_,module,exports){
      module.exports = Quaternion;

      var Vec3 = _dereq_('./Vec3');

      /**
       * A Quaternion describes a rotation in 3D space. The Quaternion is mathematically defined as Q = x*i + y*j + z*k + w, where (i,j,k) are imaginary basis vectors. (x,y,z) can be seen as a vector related to the axis of rotation, while the real multiplier, w, is related to the amount of rotation.
       * @class Quaternion
       * @constructor
       * @param {Number} x Multiplier of the imaginary basis vector i.
       * @param {Number} y Multiplier of the imaginary basis vector j.
       * @param {Number} z Multiplier of the imaginary basis vector k.
       * @param {Number} w Multiplier of the real part.
       * @see http://en.wikipedia.org/wiki/Quaternion
       */
      function Quaternion(x,y,z,w){
          /**
           * @property {Number} x
           */
          this.x = x!==undefined ? x : 0;

          /**
           * @property {Number} y
           */
          this.y = y!==undefined ? y : 0;

          /**
           * @property {Number} z
           */
          this.z = z!==undefined ? z : 0;

          /**
           * The multiplier of the real quaternion basis vector.
           * @property {Number} w
           */
          this.w = w!==undefined ? w : 1;
      }

      /**
       * Set the value of the quaternion.
       * @method set
       * @param {Number} x
       * @param {Number} y
       * @param {Number} z
       * @param {Number} w
       */
      Quaternion.prototype.set = function(x,y,z,w){
          this.x = x;
          this.y = y;
          this.z = z;
          this.w = w;
          return this;
      };

      /**
       * Convert to a readable format
       * @method toString
       * @return string
       */
      Quaternion.prototype.toString = function(){
          return this.x+","+this.y+","+this.z+","+this.w;
      };

      /**
       * Convert to an Array
       * @method toArray
       * @return Array
       */
      Quaternion.prototype.toArray = function(){
          return [this.x, this.y, this.z, this.w];
      };

      /**
       * Set the quaternion components given an axis and an angle.
       * @method setFromAxisAngle
       * @param {Vec3} axis
       * @param {Number} angle in radians
       */
      Quaternion.prototype.setFromAxisAngle = function(axis,angle){
          var s = Math.sin(angle*0.5);
          this.x = axis.x * s;
          this.y = axis.y * s;
          this.z = axis.z * s;
          this.w = Math.cos(angle*0.5);
          return this;
      };

      /**
       * Converts the quaternion to axis/angle representation.
       * @method toAxisAngle
       * @param {Vec3} [targetAxis] A vector object to reuse for storing the axis.
       * @return {Array} An array, first elemnt is the axis and the second is the angle in radians.
       */
      Quaternion.prototype.toAxisAngle = function(targetAxis){
          targetAxis = targetAxis || new Vec3();
          this.normalize(); // if w>1 acos and sqrt will produce errors, this cant happen if quaternion is normalised
          var angle = 2 * Math.acos(this.w);
          var s = Math.sqrt(1-this.w*this.w); // assuming quaternion normalised then w is less than 1, so term always positive.
          if (s < 0.001) { // test to avoid divide by zero, s is always positive due to sqrt
              // if s close to zero then direction of axis not important
              targetAxis.x = this.x; // if it is important that axis is normalised then replace with x=1; y=z=0;
              targetAxis.y = this.y;
              targetAxis.z = this.z;
          } else {
              targetAxis.x = this.x / s; // normalise axis
              targetAxis.y = this.y / s;
              targetAxis.z = this.z / s;
          }
          return [targetAxis,angle];
      };

      var sfv_t1 = new Vec3(),
          sfv_t2 = new Vec3();

      /**
       * Set the quaternion value given two vectors. The resulting rotation will be the needed rotation to rotate u to v.
       * @method setFromVectors
       * @param {Vec3} u
       * @param {Vec3} v
       */
      Quaternion.prototype.setFromVectors = function(u,v){
          if(u.isAntiparallelTo(v)){
              var t1 = sfv_t1;
              var t2 = sfv_t2;

              u.tangents(t1,t2);
              this.setFromAxisAngle(t1,Math.PI);
          } else {
              var a = u.cross(v);
              this.x = a.x;
              this.y = a.y;
              this.z = a.z;
              this.w = Math.sqrt(Math.pow(u.norm(),2) * Math.pow(v.norm(),2)) + u.dot(v);
              this.normalize();
          }
          return this;
      };

      /**
       * Quaternion multiplication
       * @method mult
       * @param {Quaternion} q
       * @param {Quaternion} target Optional.
       * @return {Quaternion}
       */
      new Vec3();
      new Vec3();
      new Vec3();
      Quaternion.prototype.mult = function(q,target){
          target = target || new Quaternion();

          var ax = this.x, ay = this.y, az = this.z, aw = this.w,
              bx = q.x, by = q.y, bz = q.z, bw = q.w;

          target.x = ax * bw + aw * bx + ay * bz - az * by;
          target.y = ay * bw + aw * by + az * bx - ax * bz;
          target.z = az * bw + aw * bz + ax * by - ay * bx;
          target.w = aw * bw - ax * bx - ay * by - az * bz;

          return target;
      };

      /**
       * Get the inverse quaternion rotation.
       * @method inverse
       * @param {Quaternion} target
       * @return {Quaternion}
       */
      Quaternion.prototype.inverse = function(target){
          var x = this.x, y = this.y, z = this.z, w = this.w;
          target = target || new Quaternion();

          this.conjugate(target);
          var inorm2 = 1/(x*x + y*y + z*z + w*w);
          target.x *= inorm2;
          target.y *= inorm2;
          target.z *= inorm2;
          target.w *= inorm2;

          return target;
      };

      /**
       * Get the quaternion conjugate
       * @method conjugate
       * @param {Quaternion} target
       * @return {Quaternion}
       */
      Quaternion.prototype.conjugate = function(target){
          target = target || new Quaternion();

          target.x = -this.x;
          target.y = -this.y;
          target.z = -this.z;
          target.w = this.w;

          return target;
      };

      /**
       * Normalize the quaternion. Note that this changes the values of the quaternion.
       * @method normalize
       */
      Quaternion.prototype.normalize = function(){
          var l = Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w);
          if ( l === 0 ) {
              this.x = 0;
              this.y = 0;
              this.z = 0;
              this.w = 0;
          } else {
              l = 1 / l;
              this.x *= l;
              this.y *= l;
              this.z *= l;
              this.w *= l;
          }
          return this;
      };

      /**
       * Approximation of quaternion normalization. Works best when quat is already almost-normalized.
       * @method normalizeFast
       * @see http://jsperf.com/fast-quaternion-normalization
       * @author unphased, https://github.com/unphased
       */
      Quaternion.prototype.normalizeFast = function () {
          var f = (3.0-(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w))/2.0;
          if ( f === 0 ) {
              this.x = 0;
              this.y = 0;
              this.z = 0;
              this.w = 0;
          } else {
              this.x *= f;
              this.y *= f;
              this.z *= f;
              this.w *= f;
          }
          return this;
      };

      /**
       * Multiply the quaternion by a vector
       * @method vmult
       * @param {Vec3} v
       * @param {Vec3} target Optional
       * @return {Vec3}
       */
      Quaternion.prototype.vmult = function(v,target){
          target = target || new Vec3();

          var x = v.x,
              y = v.y,
              z = v.z;

          var qx = this.x,
              qy = this.y,
              qz = this.z,
              qw = this.w;

          // q*v
          var ix =  qw * x + qy * z - qz * y,
          iy =  qw * y + qz * x - qx * z,
          iz =  qw * z + qx * y - qy * x,
          iw = -qx * x - qy * y - qz * z;

          target.x = ix * qw + iw * -qx + iy * -qz - iz * -qy;
          target.y = iy * qw + iw * -qy + iz * -qx - ix * -qz;
          target.z = iz * qw + iw * -qz + ix * -qy - iy * -qx;

          return target;
      };

      /**
       * Copies value of source to this quaternion.
       * @method copy
       * @param {Quaternion} source
       * @return {Quaternion} this
       */
      Quaternion.prototype.copy = function(source){
          this.x = source.x;
          this.y = source.y;
          this.z = source.z;
          this.w = source.w;
          return this;
      };

      /**
       * Convert the quaternion to euler angle representation. Order: YZX, as this page describes: http://www.euclideanspace.com/maths/standards/index.htm
       * @method toEuler
       * @param {Vec3} target
       * @param string order Three-character string e.g. "YZX", which also is default.
       */
      Quaternion.prototype.toEuler = function(target,order){
          order = order || "YZX";

          var heading, attitude, bank;
          var x = this.x, y = this.y, z = this.z, w = this.w;

          switch(order){
          case "YZX":
              var test = x*y + z*w;
              if (test > 0.499) { // singularity at north pole
                  heading = 2 * Math.atan2(x,w);
                  attitude = Math.PI/2;
                  bank = 0;
              }
              if (test < -0.499) { // singularity at south pole
                  heading = -2 * Math.atan2(x,w);
                  attitude = - Math.PI/2;
                  bank = 0;
              }
              if(isNaN(heading)){
                  var sqx = x*x;
                  var sqy = y*y;
                  var sqz = z*z;
                  heading = Math.atan2(2*y*w - 2*x*z , 1 - 2*sqy - 2*sqz); // Heading
                  attitude = Math.asin(2*test); // attitude
                  bank = Math.atan2(2*x*w - 2*y*z , 1 - 2*sqx - 2*sqz); // bank
              }
              break;
          default:
              throw new Error("Euler order "+order+" not supported yet.");
          }

          target.y = heading;
          target.z = attitude;
          target.x = bank;
      };

      /**
       * See http://www.mathworks.com/matlabcentral/fileexchange/20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/content/SpinCalc.m
       * @method setFromEuler
       * @param {Number} x
       * @param {Number} y
       * @param {Number} z
       * @param {String} order The order to apply angles: 'XYZ' or 'YXZ' or any other combination
       */
      Quaternion.prototype.setFromEuler = function ( x, y, z, order ) {
          order = order || "XYZ";

          var c1 = Math.cos( x / 2 );
          var c2 = Math.cos( y / 2 );
          var c3 = Math.cos( z / 2 );
          var s1 = Math.sin( x / 2 );
          var s2 = Math.sin( y / 2 );
          var s3 = Math.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;

          }

          return this;
      };

      /**
       * @method clone
       * @return {Quaternion}
       */
      Quaternion.prototype.clone = function(){
          return new Quaternion(this.x, this.y, this.z, this.w);
      };

      /**
       * Performs a spherical linear interpolation between two quat
       *
       * @method slerp
       * @param {Quaternion} toQuat second operand
       * @param {Number} t interpolation amount between the self quaternion and toQuat
       * @param {Quaternion} [target] A quaternion to store the result in. If not provided, a new one will be created.
       * @returns {Quaternion} The "target" object
       */
      Quaternion.prototype.slerp = function (toQuat, t, target) {
          target = target || new Quaternion();

          var ax = this.x,
              ay = this.y,
              az = this.z,
              aw = this.w,
              bx = toQuat.x,
              by = toQuat.y,
              bz = toQuat.z,
              bw = toQuat.w;

          var omega, cosom, sinom, scale0, scale1;

          // calc cosine
          cosom = ax * bx + ay * by + az * bz + aw * bw;

          // adjust signs (if necessary)
          if ( cosom < 0.0 ) {
              cosom = -cosom;
              bx = - bx;
              by = - by;
              bz = - bz;
              bw = - bw;
          }

          // calculate coefficients
          if ( (1.0 - cosom) > 0.000001 ) {
              // standard case (slerp)
              omega  = Math.acos(cosom);
              sinom  = Math.sin(omega);
              scale0 = Math.sin((1.0 - t) * omega) / sinom;
              scale1 = Math.sin(t * omega) / sinom;
          } else {
              // "from" and "to" quaternions are very close
              //  ... so we can do a linear interpolation
              scale0 = 1.0 - t;
              scale1 = t;
          }

          // calculate final values
          target.x = scale0 * ax + scale1 * bx;
          target.y = scale0 * ay + scale1 * by;
          target.z = scale0 * az + scale1 * bz;
          target.w = scale0 * aw + scale1 * bw;

          return target;
      };

      /**
       * Rotate an absolute orientation quaternion given an angular velocity and a time step.
       * @param  {Vec3} angularVelocity
       * @param  {number} dt
       * @param  {Vec3} angularFactor
       * @param  {Quaternion} target
       * @return {Quaternion} The "target" object
       */
      Quaternion.prototype.integrate = function(angularVelocity, dt, angularFactor, target){
          target = target || new Quaternion();

          var ax = angularVelocity.x * angularFactor.x,
              ay = angularVelocity.y * angularFactor.y,
              az = angularVelocity.z * angularFactor.z,
              bx = this.x,
              by = this.y,
              bz = this.z,
              bw = this.w;

          var half_dt = dt * 0.5;

          target.x += half_dt * (ax * bw + ay * bz - az * by);
          target.y += half_dt * (ay * bw + az * bx - ax * bz);
          target.z += half_dt * (az * bw + ax * by - ay * bx);
          target.w += half_dt * (- ax * bx - ay * by - az * bz);

          return target;
      };

      Quaternion.prototype.euqals = function(v){
          return this.x===v.x&&this.y===v.y&&this.z===v.z&&this.w===v.w;
      };
      },{"./Vec3":31}],30:[function(_dereq_,module,exports){
      var Vec3 = _dereq_('./Vec3');
      var Quaternion = _dereq_('./Quaternion');

      module.exports = Transform;

      /**
       * @class Transform
       * @constructor
       */
      function Transform(options) {
          options = options || {};

      	/**
      	 * @property {Vec3} position
      	 */
      	this.position = new Vec3();
          if(options.position){
              this.position.copy(options.position);
          }

      	/**
      	 * @property {Quaternion} quaternion
      	 */
      	this.quaternion = new Quaternion();
          if(options.quaternion){
              this.quaternion.copy(options.quaternion);
          }
      }

      var tmpQuat = new Quaternion();

      /**
       * @static
       * @method pointToLocaFrame
       * @param {Vec3} position
       * @param {Quaternion} quaternion
       * @param {Vec3} worldPoint
       * @param {Vec3} result
       */
      Transform.pointToLocalFrame = function(position, quaternion, worldPoint, result){
          var result = result || new Vec3();
          worldPoint.vsub(position, result);
          quaternion.conjugate(tmpQuat);
          tmpQuat.vmult(result, result);
          return result;
      };

      /**
       * Get a global point in local transform coordinates.
       * @method pointToLocal
       * @param  {Vec3} point
       * @param  {Vec3} result
       * @return {Vec3} The "result" vector object
       */
      Transform.prototype.pointToLocal = function(worldPoint, result){
          return Transform.pointToLocalFrame(this.position, this.quaternion, worldPoint, result);
      };

      /**
       * @static
       * @method pointToWorldFrame
       * @param {Vec3} position
       * @param {Vec3} quaternion
       * @param {Vec3} localPoint
       * @param {Vec3} result
       */
      Transform.pointToWorldFrame = function(position, quaternion, localPoint, result){
          var result = result || new Vec3();
          quaternion.vmult(localPoint, result);
          result.vadd(position, result);
          return result;
      };

      /**
       * Get a local point in global transform coordinates.
       * @method pointToWorld
       * @param  {Vec3} point
       * @param  {Vec3} result
       * @return {Vec3} The "result" vector object
       */
      Transform.prototype.pointToWorld = function(localPoint, result){
          return Transform.pointToWorldFrame(this.position, this.quaternion, localPoint, result);
      };


      Transform.prototype.vectorToWorldFrame = function(localVector, result){
          var result = result || new Vec3();
          this.quaternion.vmult(localVector, result);
          return result;
      };

      Transform.vectorToWorldFrame = function(quaternion, localVector, result){
          quaternion.vmult(localVector, result);
          return result;
      };

      Transform.vectorToLocalFrame = function(position, quaternion, worldVector, result){
          var result = result || new Vec3();
          quaternion.w *= -1;
          quaternion.vmult(worldVector, result);
          quaternion.w *= -1;
          return result;
      };

      },{"./Quaternion":29,"./Vec3":31}],31:[function(_dereq_,module,exports){
      module.exports = Vec3;

      var Mat3 = _dereq_('./Mat3');

      /**
       * 3-dimensional vector
       * @class Vec3
       * @constructor
       * @param {Number} x
       * @param {Number} y
       * @param {Number} z
       * @author schteppe
       * @example
       *     var v = new Vec3(1, 2, 3);
       *     console.log('x=' + v.x); // x=1
       */
      function Vec3(x,y,z){
          /**
           * @property x
           * @type {Number}
           */
          this.x = x||0.0;

          /**
           * @property y
           * @type {Number}
           */
          this.y = y||0.0;

          /**
           * @property z
           * @type {Number}
           */
          this.z = z||0.0;
      }

      /**
       * @static
       * @property {Vec3} ZERO
       */
      Vec3.ZERO = new Vec3(0, 0, 0);

      /**
       * @static
       * @property {Vec3} UNIT_X
       */
      Vec3.UNIT_X = new Vec3(1, 0, 0);

      /**
       * @static
       * @property {Vec3} UNIT_Y
       */
      Vec3.UNIT_Y = new Vec3(0, 1, 0);

      /**
       * @static
       * @property {Vec3} UNIT_Z
       */
      Vec3.UNIT_Z = new Vec3(0, 0, 1);

      /**
       * Vector cross product
       * @method cross
       * @param {Vec3} v
       * @param {Vec3} target Optional. Target to save in.
       * @return {Vec3}
       */
      Vec3.prototype.cross = function(v,target){
          var vx=v.x, vy=v.y, vz=v.z, x=this.x, y=this.y, z=this.z;
          target = target || new Vec3();

          target.x = (y * vz) - (z * vy);
          target.y = (z * vx) - (x * vz);
          target.z = (x * vy) - (y * vx);

          return target;
      };

      /**
       * Set the vectors' 3 elements
       * @method set
       * @param {Number} x
       * @param {Number} y
       * @param {Number} z
       * @return Vec3
       */
      Vec3.prototype.set = function(x,y,z){
          this.x = x;
          this.y = y;
          this.z = z;
          return this;
      };

      /**
       * Set all components of the vector to zero.
       * @method setZero
       */
      Vec3.prototype.setZero = function(){
          this.x = this.y = this.z = 0;
      };

      /**
       * Vector addition
       * @method vadd
       * @param {Vec3} v
       * @param {Vec3} target Optional.
       * @return {Vec3}
       */
      Vec3.prototype.vadd = function(v,target){
          if(target){
              target.x = v.x + this.x;
              target.y = v.y + this.y;
              target.z = v.z + this.z;
          } else {
              return new Vec3(this.x + v.x,
                                     this.y + v.y,
                                     this.z + v.z);
          }
      };

      /**
       * Vector subtraction
       * @method vsub
       * @param {Vec3} v
       * @param {Vec3} target Optional. Target to save in.
       * @return {Vec3}
       */
      Vec3.prototype.vsub = function(v,target){
          if(target){
              target.x = this.x - v.x;
              target.y = this.y - v.y;
              target.z = this.z - v.z;
          } else {
              return new Vec3(this.x-v.x,
                                     this.y-v.y,
                                     this.z-v.z);
          }
      };

      /**
       * Get the cross product matrix a_cross from a vector, such that a x b = a_cross * b = c
       * @method crossmat
       * @see http://www8.cs.umu.se/kurser/TDBD24/VT06/lectures/Lecture6.pdf
       * @return {Mat3}
       */
      Vec3.prototype.crossmat = function(){
          return new Mat3([     0,  -this.z,   this.y,
                                  this.z,        0,  -this.x,
                                 -this.y,   this.x,        0]);
      };

      /**
       * Normalize the vector. Note that this changes the values in the vector.
       * @method normalize
       * @return {Number} Returns the norm of the vector
       */
      Vec3.prototype.normalize = function(){
          var x=this.x, y=this.y, z=this.z;
          var n = Math.sqrt(x*x + y*y + z*z);
          if(n>0.0){
              var invN = 1/n;
              this.x *= invN;
              this.y *= invN;
              this.z *= invN;
          } else {
              // Make something up
              this.x = 0;
              this.y = 0;
              this.z = 0;
          }
          return n;
      };

      /**
       * Get the version of this vector that is of length 1.
       * @method unit
       * @param {Vec3} target Optional target to save in
       * @return {Vec3} Returns the unit vector
       */
      Vec3.prototype.unit = function(target){
          target = target || new Vec3();
          var x=this.x, y=this.y, z=this.z;
          var ninv = Math.sqrt(x*x + y*y + z*z);
          if(ninv>0.0){
              ninv = 1.0/ninv;
              target.x = x * ninv;
              target.y = y * ninv;
              target.z = z * ninv;
          } else {
              target.x = 1;
              target.y = 0;
              target.z = 0;
          }
          return target;
      };

      /**
       * Get the length of the vector
       * @method norm
       * @return {Number}
       * @deprecated Use .length() instead
       */
      Vec3.prototype.norm = function(){
          var x=this.x, y=this.y, z=this.z;
          return Math.sqrt(x*x + y*y + z*z);
      };

      /**
       * Get the length of the vector
       * @method length
       * @return {Number}
       */
      Vec3.prototype.length = Vec3.prototype.norm;

      /**
       * Get the squared length of the vector
       * @method norm2
       * @return {Number}
       * @deprecated Use .lengthSquared() instead.
       */
      Vec3.prototype.norm2 = function(){
          return this.dot(this);
      };

      /**
       * Get the squared length of the vector.
       * @method lengthSquared
       * @return {Number}
       */
      Vec3.prototype.lengthSquared = Vec3.prototype.norm2;

      /**
       * Get distance from this point to another point
       * @method distanceTo
       * @param  {Vec3} p
       * @return {Number}
       */
      Vec3.prototype.distanceTo = function(p){
          var x=this.x, y=this.y, z=this.z;
          var px=p.x, py=p.y, pz=p.z;
          return Math.sqrt((px-x)*(px-x)+
                           (py-y)*(py-y)+
                           (pz-z)*(pz-z));
      };

      /**
       * Get squared distance from this point to another point
       * @method distanceSquared
       * @param  {Vec3} p
       * @return {Number}
       */
      Vec3.prototype.distanceSquared = function(p){
          var x=this.x, y=this.y, z=this.z;
          var px=p.x, py=p.y, pz=p.z;
          return (px-x)*(px-x) + (py-y)*(py-y) + (pz-z)*(pz-z);
      };

      /**
       * Multiply all the components of the vector with a scalar.
       * @deprecated Use .scale instead
       * @method mult
       * @param {Number} scalar
       * @param {Vec3} target The vector to save the result in.
       * @return {Vec3}
       * @deprecated Use .scale() instead
       */
      Vec3.prototype.mult = function(scalar,target){
          target = target || new Vec3();
          var x = this.x,
              y = this.y,
              z = this.z;
          target.x = scalar * x;
          target.y = scalar * y;
          target.z = scalar * z;
          return target;
      };

      /**
       * Multiply the vector with an other vector, component-wise.
       * @method mult
       * @param {Number} vector
       * @param {Vec3} target The vector to save the result in.
       * @return {Vec3}
       */
      Vec3.prototype.vmul = function(vector, target){
          target = target || new Vec3();
          target.x = vector.x * this.x;
          target.y = vector.y * this.y;
          target.z = vector.z * this.z;
          return target;
      };

      /**
       * Multiply the vector with a scalar.
       * @method scale
       * @param {Number} scalar
       * @param {Vec3} target
       * @return {Vec3}
       */
      Vec3.prototype.scale = Vec3.prototype.mult;

      /**
       * Scale a vector and add it to this vector. Save the result in "target". (target = this + vector * scalar)
       * @method addScaledVector
       * @param {Number} scalar
       * @param {Vec3} vector
       * @param {Vec3} target The vector to save the result in.
       * @return {Vec3}
       */
      Vec3.prototype.addScaledVector = function(scalar, vector, target){
          target = target || new Vec3();
          target.x = this.x + scalar * vector.x;
          target.y = this.y + scalar * vector.y;
          target.z = this.z + scalar * vector.z;
          return target;
      };

      /**
       * Calculate dot product
       * @method dot
       * @param {Vec3} v
       * @return {Number}
       */
      Vec3.prototype.dot = function(v){
          return this.x * v.x + this.y * v.y + this.z * v.z;
      };

      /**
       * @method isZero
       * @return bool
       */
      Vec3.prototype.isZero = function(){
          return this.x===0 && this.y===0 && this.z===0;
      };

      /**
       * Make the vector point in the opposite direction.
       * @method negate
       * @param {Vec3} target Optional target to save in
       * @return {Vec3}
       */
      Vec3.prototype.negate = function(target){
          target = target || new Vec3();
          target.x = -this.x;
          target.y = -this.y;
          target.z = -this.z;
          return target;
      };

      /**
       * Compute two artificial tangents to the vector
       * @method tangents
       * @param {Vec3} t1 Vector object to save the first tangent in
       * @param {Vec3} t2 Vector object to save the second tangent in
       */
      var Vec3_tangents_n = new Vec3();
      var Vec3_tangents_randVec = new Vec3();
      Vec3.prototype.tangents = function(t1,t2){
          var norm = this.norm();
          if(norm>0.0){
              var n = Vec3_tangents_n;
              var inorm = 1/norm;
              n.set(this.x*inorm,this.y*inorm,this.z*inorm);
              var randVec = Vec3_tangents_randVec;
              if(Math.abs(n.x) < 0.9){
                  randVec.set(1,0,0);
                  n.cross(randVec,t1);
              } else {
                  randVec.set(0,1,0);
                  n.cross(randVec,t1);
              }
              n.cross(t1,t2);
          } else {
              // The normal length is zero, make something up
              t1.set(1, 0, 0);
              t2.set(0, 1, 0);
          }
      };

      /**
       * Converts to a more readable format
       * @method toString
       * @return string
       */
      Vec3.prototype.toString = function(){
          return this.x+","+this.y+","+this.z;
      };

      /**
       * Converts to an array
       * @method toArray
       * @return Array
       */
      Vec3.prototype.toArray = function(){
          return [this.x, this.y, this.z];
      };

      /**
       * Copies value of source to this vector.
       * @method copy
       * @param {Vec3} source
       * @return {Vec3} this
       */
      Vec3.prototype.copy = function(source){
          this.x = source.x;
          this.y = source.y;
          this.z = source.z;
          return this;
      };


      /**
       * Do a linear interpolation between two vectors
       * @method lerp
       * @param {Vec3} v
       * @param {Number} t A number between 0 and 1. 0 will make this function return u, and 1 will make it return v. Numbers in between will generate a vector in between them.
       * @param {Vec3} target
       */
      Vec3.prototype.lerp = function(v,t,target){
          var x=this.x, y=this.y, z=this.z;
          target.x = x + (v.x-x)*t;
          target.y = y + (v.y-y)*t;
          target.z = z + (v.z-z)*t;
      };

      /**
       * Check if a vector equals is almost equal to another one.
       * @method almostEquals
       * @param {Vec3} v
       * @param {Number} precision
       * @return bool
       */
      Vec3.prototype.almostEquals = function(v,precision){
          if(precision===undefined){
              precision = 1e-6;
          }
          if( Math.abs(this.x-v.x)>precision ||
              Math.abs(this.y-v.y)>precision ||
              Math.abs(this.z-v.z)>precision){
              return false;
          }
          return true;
      };

      /**
       * Check if a vector is almost zero
       * @method almostZero
       * @param {Number} precision
       */
      Vec3.prototype.almostZero = function(precision){
          if(precision===undefined){
              precision = 1e-6;
          }
          if( Math.abs(this.x)>precision ||
              Math.abs(this.y)>precision ||
              Math.abs(this.z)>precision){
              return false;
          }
          return true;
      };

      var antip_neg = new Vec3();

      /**
       * Check if the vector is anti-parallel to another vector.
       * @method isAntiparallelTo
       * @param  {Vec3}  v
       * @param  {Number}  precision Set to zero for exact comparisons
       * @return {Boolean}
       */
      Vec3.prototype.isAntiparallelTo = function(v,precision){
          this.negate(antip_neg);
          return antip_neg.almostEquals(v,precision);
      };

      /**
       * Clone the vector
       * @method clone
       * @return {Vec3}
       */
      Vec3.prototype.clone = function(){
          return new Vec3(this.x, this.y, this.z);
      };
      },{"./Mat3":28}],32:[function(_dereq_,module,exports){
      module.exports = Body;

      var EventTarget = _dereq_('../utils/EventTarget');
      var Shape = _dereq_('../shapes/Shape');
      var Vec3 = _dereq_('../math/Vec3');
      var Mat3 = _dereq_('../math/Mat3');
      var Quaternion = _dereq_('../math/Quaternion');
      _dereq_('../material/Material');
      var AABB = _dereq_('../collision/AABB');
      var Box = _dereq_('../shapes/Box');
      var RaycastResult = _dereq_('../collision/RaycastResult');
      var World = _dereq_('../world/World');

      /**
       * Base class for all body types.
       * @class Body
       * @constructor
       * @extends EventTarget
       * @param {object} [options]
       * @param {Vec3} [options.position]
       * @param {Vec3} [options.velocity]
       * @param {Vec3} [options.angularVelocity]
       * @param {Quaternion} [options.quaternion]
       * @param {number} [options.mass]
       * @param {Material} [options.material]
       * @param {number} [options.type]
       * @param {number} [options.linearDamping=0.01]
       * @param {number} [options.angularDamping=0.01]
       * @param {boolean} [options.allowSleep=true]
       * @param {number} [options.sleepSpeedLimit=0.1]
       * @param {number} [options.sleepTimeLimit=1]
       * @param {number} [options.collisionFilterGroup=1]
       * @param {number} [options.collisionFilterMask=-1]
       * @param {boolean} [options.fixedRotation=false]
       * @param {Vec3} [options.linearFactor]
       * @param {Vec3} [options.angularFactor]
       * @param {Shape} [options.shape]
       * @example
       *     var body = new Body({
       *         mass: 1
       *     });
       *     var shape = new Sphere(1);
       *     body.addShape(shape);
       *     world.addBody(body);
       */
      function Body(options){
          options = options || {};

          EventTarget.apply(this);

          this.id = Body.idCounter++;

          /**
           * Reference to the world the body is living in
           * @property world
           * @type {World}
           */
          this.world = null;

          /**
           * Callback function that is used BEFORE stepping the system. Use it to apply forces, for example. Inside the function, "this" will refer to this Body object.
           * @property preStep
           * @type {Function}
           * @deprecated Use World events instead
           */
          this.preStep = null;

          /**
           * If the body speed exceeds this threshold, CCD (continuous collision detection) will be enabled. Set it to a negative number to disable CCD completely for this body.
           * @property {number} ccdSpeedThreshold
           * @default -1
           */
          this.ccdSpeedThreshold = options.ccdSpeedThreshold !== undefined ? options.ccdSpeedThreshold : -1;
          
          /**
           * The number of iterations that should be used when searching for the time of impact during CCD. A larger number will assure that there's a small penetration on CCD collision, but a small number will give more performance.
           * @property {number} ccdIterations
           * @default 10
           */
          this.ccdIterations = options.ccdIterations !== undefined ? options.ccdIterations : 5;


          /**
           * Callback function that is used AFTER stepping the system. Inside the function, "this" will refer to this Body object.
           * @property postStep
           * @type {Function}
           * @deprecated Use World events instead
           */
          this.postStep = null;

          this.vlambda = new Vec3();

          /**
           * @property {Number} collisionFilterGroup
           */
          this.collisionFilterGroup = typeof(options.collisionFilterGroup) === 'number' ? options.collisionFilterGroup : 1;

          /**
           * @property {Number} collisionFilterMask
           */
          this.collisionFilterMask = typeof(options.collisionFilterMask) === 'number' ? options.collisionFilterMask : -1;

          /**
           * Whether to produce contact forces when in contact with other bodies. Note that contacts will be generated, but they will be disabled.
           * @property {Number} collisionResponse
           */
          this.collisionResponse = true;

          /**
           * World space position of the body.
           * @property position
           * @type {Vec3}
           */
          this.position = new Vec3();

          /**
           * @property {Vec3} previousPosition
           */
          this.previousPosition = new Vec3();

          /**
           * Interpolated position of the body.
           * @property {Vec3} interpolatedPosition
           */
          this.interpolatedPosition = new Vec3();

          /**
           * Initial position of the body
           * @property initPosition
           * @type {Vec3}
           */
          this.initPosition = new Vec3();

          if(options.position){
              this.position.copy(options.position);
              this.previousPosition.copy(options.position);
              this.interpolatedPosition.copy(options.position);
              this.initPosition.copy(options.position);
          }

          /**
           * World space velocity of the body.
           * @property velocity
           * @type {Vec3}
           */
          this.velocity = new Vec3();

          if(options.velocity){
              this.velocity.copy(options.velocity);
          }

          /**
           * @property initVelocity
           * @type {Vec3}
           */
          this.initVelocity = new Vec3();

          /**
           * Linear force on the body in world space.
           * @property force
           * @type {Vec3}
           */
          this.force = new Vec3();

          var mass = typeof(options.mass) === 'number' ? options.mass : 0;

          /**
           * @property mass
           * @type {Number}
           * @default 0
           */
          this.mass = mass;

          /**
           * @property invMass
           * @type {Number}
           */
          this.invMass = mass > 0 ? 1.0 / mass : 0;

          /**
           * @property material
           * @type {Material}
           */
          this.material = options.material || null;

          /**
           * @property linearDamping
           * @type {Number}
           */
          this.linearDamping = typeof(options.linearDamping) === 'number' ? options.linearDamping : 0.01;

          /**
           * One of: Body.DYNAMIC, Body.STATIC and Body.KINEMATIC.
           * @property type
           * @type {Number}
           */
          this.type = (mass <= 0.0 ? Body.STATIC : Body.DYNAMIC);
          if(typeof(options.type) === typeof(Body.STATIC)){
              this.type = options.type;
          }

          /**
           * If true, the body will automatically fall to sleep.
           * @property allowSleep
           * @type {Boolean}
           * @default true
           */
          this.allowSleep = typeof(options.allowSleep) !== 'undefined' ? options.allowSleep : true;

          /**
           * Current sleep state.
           * @property sleepState
           * @type {Number}
           */
          this.sleepState = 0;

          /**
           * If the speed (the norm of the velocity) is smaller than this value, the body is considered sleepy.
           * @property sleepSpeedLimit
           * @type {Number}
           * @default 0.1
           */
          this.sleepSpeedLimit = typeof(options.sleepSpeedLimit) !== 'undefined' ? options.sleepSpeedLimit : 0.1;

          /**
           * If the body has been sleepy for this sleepTimeLimit seconds, it is considered sleeping.
           * @property sleepTimeLimit
           * @type {Number}
           * @default 1
           */
          this.sleepTimeLimit = typeof(options.sleepTimeLimit) !== 'undefined' ? options.sleepTimeLimit : 1;

          this.timeLastSleepy = 0;

          this._wakeUpAfterNarrowphase = false;

          /**
           * World space rotational force on the body, around center of mass.
           * @property {Vec3} torque
           */
          this.torque = new Vec3();

          /**
           * World space orientation of the body.
           * @property quaternion
           * @type {Quaternion}
           */
          this.quaternion = new Quaternion();

          /**
           * @property initQuaternion
           * @type {Quaternion}
           */
          this.initQuaternion = new Quaternion();

          /**
           * @property {Quaternion} previousQuaternion
           */
          this.previousQuaternion = new Quaternion();

          /**
           * Interpolated orientation of the body.
           * @property {Quaternion} interpolatedQuaternion
           */
          this.interpolatedQuaternion = new Quaternion();

          if(options.quaternion){
              this.quaternion.copy(options.quaternion);
              this.initQuaternion.copy(options.quaternion);
              this.previousQuaternion.copy(options.quaternion);
              this.interpolatedQuaternion.copy(options.quaternion);
          }

          /**
           * Angular velocity of the body, in world space. Think of the angular velocity as a vector, which the body rotates around. The length of this vector determines how fast (in radians per second) the body rotates.
           * @property angularVelocity
           * @type {Vec3}
           */
          this.angularVelocity = new Vec3();

          if(options.angularVelocity){
              this.angularVelocity.copy(options.angularVelocity);
          }

          /**
           * @property initAngularVelocity
           * @type {Vec3}
           */
          this.initAngularVelocity = new Vec3();

          /**
           * @property shapes
           * @type {array}
           */
          this.shapes = [];

          /**
           * Position of each Shape in the body, given in local Body space.
           * @property shapeOffsets
           * @type {array}
           */
          this.shapeOffsets = [];

          /**
           * Orientation of each Shape, given in local Body space.
           * @property shapeOrientations
           * @type {array}
           */
          this.shapeOrientations = [];

          /**
           * @property inertia
           * @type {Vec3}
           */
          this.inertia = new Vec3();

          /**
           * @property {Vec3} invInertia
           */
          this.invInertia = new Vec3();

          /**
           * @property {Mat3} invInertiaWorld
           */
          this.invInertiaWorld = new Mat3();

          this.invMassSolve = 0;

          /**
           * @property {Vec3} invInertiaSolve
           */
          this.invInertiaSolve = new Vec3();

          /**
           * @property {Mat3} invInertiaWorldSolve
           */
          this.invInertiaWorldSolve = new Mat3();

          /**
           * Set to true if you don't want the body to rotate. Make sure to run .updateMassProperties() after changing this.
           * @property {Boolean} fixedRotation
           * @default false
           */
          this.fixedRotation = typeof(options.fixedRotation) !== "undefined" ? options.fixedRotation : false;

          /**
           * use gravity ?
           * @property {Boolean} useGravity
           * @default true
           */
          this.useGravity = true;

          /**
           * @property {Number} angularDamping
           */
          this.angularDamping = typeof(options.angularDamping) !== 'undefined' ? options.angularDamping : 0.01;

          /**
           * Use this property to limit the motion along any world axis. (1,1,1) will allow motion along all axes while (0,0,0) allows none.
           * @property {Vec3} linearFactor
           */
          this.linearFactor = new Vec3(1,1,1);
          if(options.linearFactor){
              this.linearFactor.copy(options.linearFactor);
          }

          /**
           * Use this property to limit the rotational motion along any world axis. (1,1,1) will allow rotation along all axes while (0,0,0) allows none.
           * @property {Vec3} angularFactor
           */
          this.angularFactor = new Vec3(1,1,1);
          if(options.angularFactor){
              this.angularFactor.copy(options.angularFactor);
          }

          /**
           * World space bounding box of the body and its shapes.
           * @property aabb
           * @type {AABB}
           */
          this.aabb = new AABB();

          /**
           * Indicates if the AABB needs to be updated before use.
           * @property aabbNeedsUpdate
           * @type {Boolean}
           */
          this.aabbNeedsUpdate = true;

          /**
           * Total bounding radius of the Body including its shapes, relative to body.position.
           * @property boundingRadius
           * @type {Number}
           */
          this.boundingRadius = 0;

          this.wlambda = new Vec3();

          if(options.shape){
              this.addShape(options.shape);
          }

          /**
           * has trigger?
           */
          this.hasTrigger = true;

          this.updateMassProperties();
      }
      Body.prototype = new EventTarget();
      Body.prototype.constructor = Body;

      /**
       * Dispatched after two bodies collide. This event is dispatched on each
       * of the two bodies involved in the collision.
       * @event collide
       * @param {Body} body The body that was involved in the collision.
       * @param {ContactEquation} contact The details of the collision.
       */
      Body.COLLIDE_EVENT_NAME = "collide";

      /**
       * A dynamic body is fully simulated. Can be moved manually by the user, but normally they move according to forces. A dynamic body can collide with all body types. A dynamic body always has finite, non-zero mass.
       * @static
       * @property DYNAMIC
       * @type {Number}
       */
      Body.DYNAMIC = 1;

      /**
       * A static body does not move during simulation and behaves as if it has infinite mass. Static bodies can be moved manually by setting the position of the body. The velocity of a static body is always zero. Static bodies do not collide with other static or kinematic bodies.
       * @static
       * @property STATIC
       * @type {Number}
       */
      Body.STATIC = 2;

      /**
       * A kinematic body moves under simulation according to its velocity. They do not respond to forces. They can be moved manually, but normally a kinematic body is moved by setting its velocity. A kinematic body behaves as if it has infinite mass. Kinematic bodies do not collide with other static or kinematic bodies.
       * @static
       * @property KINEMATIC
       * @type {Number}
       */
      Body.KINEMATIC = 4;



      /**
       * @static
       * @property AWAKE
       * @type {number}
       */
      Body.AWAKE = 0;

      /**
       * @static
       * @property SLEEPY
       * @type {number}
       */
      Body.SLEEPY = 1;

      /**
       * @static
       * @property SLEEPING
       * @type {number}
       */
      Body.SLEEPING = 2;

      Body.idCounter = 0;

      /**
       * Dispatched after a sleeping body has woken up.
       * @event wakeup
       */
      Body.wakeupEvent = {
          type: "wakeup"
      };

      /**
       * Wake the body up.
       * @method wakeUp
       */
      Body.prototype.wakeUp = function(){
          var s = this.sleepState;
          this.sleepState = 0;
          this._wakeUpAfterNarrowphase = false;
          if(s === Body.SLEEPING){
              this.dispatchEvent(Body.wakeupEvent);
          }
      };

      /**
       * Force body sleep
       * @method sleep
       */
      Body.prototype.sleep = function(){
          this.sleepState = Body.SLEEPING;
          this.velocity.set(0,0,0);
          this.angularVelocity.set(0,0,0);
          this._wakeUpAfterNarrowphase = false;
      };

      /**
       * Dispatched after a body has gone in to the sleepy state.
       * @event sleepy
       */
      Body.sleepyEvent = {
          type: "sleepy"
      };

      /**
       * Dispatched after a body has fallen asleep.
       * @event sleep
       */
      Body.sleepEvent = {
          type: "sleep"
      };

      /**
       * Called every timestep to update internal sleep timer and change sleep state if needed.
       * @method sleepTick
       * @param {Number} time The world time in seconds
       */
      Body.prototype.sleepTick = function(time){
          if(this.allowSleep){
              var sleepState = this.sleepState;
              var speedSquared = this.velocity.norm2() + this.angularVelocity.norm2();
              var speedLimitSquared = Math.pow(this.sleepSpeedLimit,2);
              if(sleepState===Body.AWAKE && speedSquared < speedLimitSquared){
                  this.sleepState = Body.SLEEPY; // Sleepy
                  this.timeLastSleepy = time;
                  this.dispatchEvent(Body.sleepyEvent);
              } else if(sleepState===Body.SLEEPY && speedSquared > speedLimitSquared){
                  this.wakeUp(); // Wake up
              } else if(sleepState===Body.SLEEPY && (time - this.timeLastSleepy ) > this.sleepTimeLimit){
                  this.sleep(); // Sleeping
                  this.dispatchEvent(Body.sleepEvent);
              }
          }
      };

      /**
       * If the body is sleeping, it should be immovable / have infinite mass during solve. We solve it by having a separate "solve mass".
       * @method updateSolveMassProperties
       */
      Body.prototype.updateSolveMassProperties = function(){
          if(this.sleepState === Body.SLEEPING || this.type === Body.KINEMATIC){
              this.invMassSolve = 0;
              this.invInertiaSolve.setZero();
              this.invInertiaWorldSolve.setZero();
          } else {
              this.invMassSolve = this.invMass;
              this.invInertiaSolve.copy(this.invInertia);
              this.invInertiaWorldSolve.copy(this.invInertiaWorld);
          }
      };

      /**
       * Convert a world point to local body frame.
       * @method pointToLocalFrame
       * @param  {Vec3} worldPoint
       * @param  {Vec3} result
       * @return {Vec3}
       */
      Body.prototype.pointToLocalFrame = function(worldPoint,result){
          var result = result || new Vec3();
          worldPoint.vsub(this.position,result);
          this.quaternion.conjugate().vmult(result,result);
          return result;
      };

      /**
       * Convert a world vector to local body frame.
       * @method vectorToLocalFrame
       * @param  {Vec3} worldPoint
       * @param  {Vec3} result
       * @return {Vec3}
       */
      Body.prototype.vectorToLocalFrame = function(worldVector, result){
          var result = result || new Vec3();
          this.quaternion.conjugate().vmult(worldVector,result);
          return result;
      };

      /**
       * Convert a local body point to world frame.
       * @method pointToWorldFrame
       * @param  {Vec3} localPoint
       * @param  {Vec3} result
       * @return {Vec3}
       */
      Body.prototype.pointToWorldFrame = function(localPoint,result){
          var result = result || new Vec3();
          this.quaternion.vmult(localPoint,result);
          result.vadd(this.position,result);
          return result;
      };

      /**
       * Convert a local body point to world frame.
       * @method vectorToWorldFrame
       * @param  {Vec3} localVector
       * @param  {Vec3} result
       * @return {Vec3}
       */
      Body.prototype.vectorToWorldFrame = function(localVector, result){
          var result = result || new Vec3();
          this.quaternion.vmult(localVector, result);
          return result;
      };

      var tmpVec = new Vec3();
      var tmpQuat = new Quaternion();

      /**
       * Add a shape to the body with a local offset and orientation.
       * @method addShape
       * @param {Shape} shape
       * @param {Vec3} [_offset]
       * @param {Quaternion} [_orientation]
       * @return {Body} The body object, for chainability.
       */
      Body.prototype.addShape = function(shape, _offset, _orientation){
          var offset = new Vec3();
          var orientation = new Quaternion();

          if(_offset){
              offset.copy(_offset);
          }
          if(_orientation){
              orientation.copy(_orientation);
          }

          this.shapes.push(shape);
          this.shapeOffsets.push(offset);
          this.shapeOrientations.push(orientation);
          this.aabbNeedsUpdate = true;
          this.updateMassProperties();
          this.updateBoundingRadius();

          this.updateHasTrigger();
          World.idToShapeMap[shape.id] = shape;
          shape.body = this;

          return this;
      };

      /**
       * Remove a shape from the body
       */
      Body.prototype.removeShape = function(shape){   
          var idx = this.shapes.indexOf(shape);
          if (idx === -1) {
              return;
          }
          // shape.body = null;  needed ?
          // delete World.idToShapeMap[shape.id];  needed ?

          this.shapes.splice(idx, 1);
          this.shapeOffsets.splice(idx, 1);
          this.shapeOrientations.splice(idx, 1);

          this.aabbNeedsUpdate = true;
          this.updateMassProperties();
          this.updateBoundingRadius();
          this.updateHasTrigger();
      };

      /**
       * Update the bounding radius of the body. Should be done if any of the shapes are changed.
       * @method updateBoundingRadius
       */
      Body.prototype.updateBoundingRadius = function(){
          var shapes = this.shapes,
              shapeOffsets = this.shapeOffsets,
              N = shapes.length,
              radius = 0;

          for(var i=0; i!==N; i++){
              var shape = shapes[i];
              shape.updateBoundingSphereRadius();
              var offset = shapeOffsets[i].norm(),
                  r = shape.boundingSphereRadius;
              if(offset + r > radius){
                  radius = offset + r;
              }
          }

          this.boundingRadius = radius;
      };

      var computeAABB_shapeAABB = new AABB();

      /**
       * Updates the .aabb
       * @method computeAABB
       * @todo rename to updateAABB()
       */
      Body.prototype.computeAABB = function(){
          var shapes = this.shapes,
              shapeOffsets = this.shapeOffsets,
              shapeOrientations = this.shapeOrientations,
              N = shapes.length,
              offset = tmpVec,
              orientation = tmpQuat,
              bodyQuat = this.quaternion,
              aabb = this.aabb,
              shapeAABB = computeAABB_shapeAABB;

          for(var i=0; i!==N; i++){
              var shape = shapes[i];

              // Get shape world position
              bodyQuat.vmult(shapeOffsets[i], offset);
              offset.vadd(this.position, offset);

              // Get shape world quaternion
              shapeOrientations[i].mult(bodyQuat, orientation);

              // Get shape AABB
              shape.calculateWorldAABB(offset, orientation, shapeAABB.lowerBound, shapeAABB.upperBound);

              if(i === 0){
                  aabb.copy(shapeAABB);
              } else {
                  aabb.extend(shapeAABB);
              }
          }

          this.aabbNeedsUpdate = false;
      };

      var uiw_m1 = new Mat3(),
          uiw_m2 = new Mat3();
          new Mat3();

      /**
       * Update .inertiaWorld and .invInertiaWorld
       * @method updateInertiaWorld
       */
      Body.prototype.updateInertiaWorld = function(force){
          var I = this.invInertia;
          if (I.x === I.y && I.y === I.z && !force) ; else {
              var m1 = uiw_m1,
                  m2 = uiw_m2;

              m1.setRotationFromQuaternion(this.quaternion);
              m1.transpose(m2);
              m1.scale(I,m1);
              m1.mmult(m2,this.invInertiaWorld);
          }
      };

      /**
       * Apply force to a world point. This could for example be a point on the Body surface. Applying force this way will add to Body.force and Body.torque.
       * @method applyForce
       * @param  {Vec3} force The amount of force to add.
       * @param  {Vec3} relativePoint A point relative to the center of mass to apply the force on.
       */
      new Vec3();
      var Body_applyForce_rotForce = new Vec3();
      Body.prototype.applyForce = function(force,relativePoint){
          if(this.type !== Body.DYNAMIC){ // Needed?
              return;
          }

          // Compute produced rotational force
          var rotForce = Body_applyForce_rotForce;
          relativePoint.cross(force,rotForce);

          // Add linear force
          this.force.vadd(force,this.force);

          // Add rotational force
          this.torque.vadd(rotForce,this.torque);
      };

      /**
       * Apply force to a local point in the body.
       * @method applyLocalForce
       * @param  {Vec3} force The force vector to apply, defined locally in the body frame.
       * @param  {Vec3} localPoint A local point in the body to apply the force on.
       */
      var Body_applyLocalForce_worldForce = new Vec3();
      var Body_applyLocalForce_relativePointWorld = new Vec3();
      Body.prototype.applyLocalForce = function(localForce, localPoint){
          if(this.type !== Body.DYNAMIC){
              return;
          }

          var worldForce = Body_applyLocalForce_worldForce;
          var relativePointWorld = Body_applyLocalForce_relativePointWorld;

          // Transform the force vector to world space
          this.vectorToWorldFrame(localForce, worldForce);
          this.vectorToWorldFrame(localPoint, relativePointWorld);

          this.applyForce(worldForce, relativePointWorld);
      };

      /**
       * Apply impulse to a world point. This could for example be a point on the Body surface. An impulse is a force added to a body during a short period of time (impulse = force * time). Impulses will be added to Body.velocity and Body.angularVelocity.
       * @method applyImpulse
       * @param  {Vec3} impulse The amount of impulse to add.
       * @param  {Vec3} relativePoint A point relative to the center of mass to apply the force on.
       */
      new Vec3();
      var Body_applyImpulse_velo = new Vec3();
      var Body_applyImpulse_rotVelo = new Vec3();
      Body.prototype.applyImpulse = function(impulse, relativePoint){
          if(this.type !== Body.DYNAMIC){
              return;
          }

          // Compute point position relative to the body center
          var r = relativePoint;

          // Compute produced central impulse velocity
          var velo = Body_applyImpulse_velo;
          velo.copy(impulse);
          velo.mult(this.invMass,velo);

          // Add linear impulse
          this.velocity.vadd(velo, this.velocity);

          // Compute produced rotational impulse velocity
          var rotVelo = Body_applyImpulse_rotVelo;
          r.cross(impulse,rotVelo);

          /*
          rotVelo.x *= this.invInertia.x;
          rotVelo.y *= this.invInertia.y;
          rotVelo.z *= this.invInertia.z;
          */
          this.invInertiaWorld.vmult(rotVelo,rotVelo);

          // Add rotational Impulse
          this.angularVelocity.vadd(rotVelo, this.angularVelocity);
      };

      /**
       * Apply locally-defined impulse to a local point in the body.
       * @method applyLocalImpulse
       * @param  {Vec3} force The force vector to apply, defined locally in the body frame.
       * @param  {Vec3} localPoint A local point in the body to apply the force on.
       */
      var Body_applyLocalImpulse_worldImpulse = new Vec3();
      var Body_applyLocalImpulse_relativePoint = new Vec3();
      Body.prototype.applyLocalImpulse = function(localImpulse, localPoint){
          if(this.type !== Body.DYNAMIC){
              return;
          }

          var worldImpulse = Body_applyLocalImpulse_worldImpulse;
          var relativePointWorld = Body_applyLocalImpulse_relativePoint;

          // Transform the force vector to world space
          this.vectorToWorldFrame(localImpulse, worldImpulse);
          this.vectorToWorldFrame(localPoint, relativePointWorld);

          this.applyImpulse(worldImpulse, relativePointWorld);
      };

      var Body_updateMassProperties_halfExtents = new Vec3();

      /**
       * Should be called whenever you change the body shape or mass.
       * @method updateMassProperties
       */
      Body.prototype.updateMassProperties = function(){
          var halfExtents = Body_updateMassProperties_halfExtents;

          this.invMass = this.mass > 0 ? 1.0 / this.mass : 0;
          var I = this.inertia;
          var fixed = this.fixedRotation;

          // Approximate with AABB box
          this.computeAABB();
          halfExtents.set(
              (this.aabb.upperBound.x-this.aabb.lowerBound.x) / 2,
              (this.aabb.upperBound.y-this.aabb.lowerBound.y) / 2,
              (this.aabb.upperBound.z-this.aabb.lowerBound.z) / 2
          );
          Box.calculateInertia(halfExtents, this.mass, I);

          this.invInertia.set(
              I.x > 0 && !fixed ? 1.0 / I.x : 0,
              I.y > 0 && !fixed ? 1.0 / I.y : 0,
              I.z > 0 && !fixed ? 1.0 / I.z : 0
          );
          this.updateInertiaWorld(true);
      };

      /**
       * Get world velocity of a point in the body.
       * @method getVelocityAtWorldPoint
       * @param  {Vec3} worldPoint
       * @param  {Vec3} result
       * @return {Vec3} The result vector.
       */
      Body.prototype.getVelocityAtWorldPoint = function(worldPoint, result){
          var r = new Vec3();
          worldPoint.vsub(this.position, r);
          this.angularVelocity.cross(r, result);
          this.velocity.vadd(result, result);
          return result;
      };

      new Vec3();
      new Vec3();
      var integrate_velodt = new Vec3();
      new Quaternion();
      var wq = new Quaternion();

      /**
       * Move the body forward in time.
       * @param {number} dt Time step
       * @param {boolean} quatNormalize Set to true to normalize the body quaternion
       * @param {boolean} quatNormalizeFast If the quaternion should be normalized using "fast" quaternion normalization
       */
      Body.prototype.integrate = function(dt, quatNormalize, quatNormalizeFast){

          // Save previous position
          this.previousPosition.copy(this.position);
          this.previousQuaternion.copy(this.quaternion);

          // Only for dynamic
          if(!(this.type === Body.DYNAMIC || (World.integrateKinematic && this.type === Body.KINEMATIC)) || this.sleepState === Body.SLEEPING){
              return;
          }

          var velo = this.velocity,
              angularVelo = this.angularVelocity,
              pos = this.position,
              force = this.force,
              torque = this.torque,
              quat = this.quaternion,
              invMass = this.invMass,
              invInertia = this.invInertiaWorld,
              linearFactor = this.linearFactor;

          var iMdt = invMass * dt;
          velo.x += force.x * iMdt * linearFactor.x;
          velo.y += force.y * iMdt * linearFactor.y;
          velo.z += force.z * iMdt * linearFactor.z;

          var e = invInertia.elements;
          var angularFactor = this.angularFactor;
          var tx = torque.x * angularFactor.x;
          var ty = torque.y * angularFactor.y;
          var tz = torque.z * angularFactor.z;
          angularVelo.x += dt * (e[0] * tx + e[1] * ty + e[2] * tz);
          angularVelo.y += dt * (e[3] * tx + e[4] * ty + e[5] * tz);
          angularVelo.z += dt * (e[6] * tx + e[7] * ty + e[8] * tz);

          // Use new velocity  - leap frog

          quat.integrate(this.angularVelocity, dt, this.angularFactor, quat);

          if(quatNormalize){
              if(quatNormalizeFast){
                  quat.normalizeFast();
              } else {
                  quat.normalize();
              }
          }

          // CCD
          if(this.type === Body.DYNAMIC && this.ccdSpeedThreshold > 0 && this.velocity.length() >= Math.pow(this.ccdSpeedThreshold, 2)){
              if(!this.integrateToTimeOfImpact(dt)){
                  // Regular position update
                  velo.mult(dt, integrate_velodt);
                  pos.vadd(integrate_velodt, pos);
              }
          } else {
              // Regular position update
              velo.mult(dt, integrate_velodt);
              pos.vadd(integrate_velodt, pos);
          }

          this.aabbNeedsUpdate = true;

          // Update world inertia
          this.updateInertiaWorld();
      };

      Body.prototype.updateKinematic = function (dt) {
          if (this.type === Body.KINEMATIC && dt !== 0) {
              this.velocity.setZero();
              this.angularVelocity.setZero();
              var invDt = 1 / dt;
              if (!this.previousPosition.almostEquals(this.position)) {
                  this.position.vsub(this.previousPosition, this.velocity);
                  this.velocity.mult(invDt, this.velocity);
                  this.aabbNeedsUpdate = true;
              }
              if (!this.previousQuaternion.euqals(this.quaternion)) {
                  this.previousQuaternion.conjugate(wq);
                  wq.mult(this.quaternion, wq);
                  wq.toEuler(this.angularVelocity);
                  this.angularVelocity.mult(invDt, this.angularVelocity);
                  this.aabbNeedsUpdate = true;
              }
          }
      };

      Body.prototype.applyGravity = function (gravity) {
          if (this.type === Body.DYNAMIC) {
              // zero external force if damping = 1
              if(this.linearDamping == 1) {
                  this.force.setZero();
              } else {
                  if (this.useGravity) {
                      var gx = gravity.x, gy = gravity.y, gz = gravity.z;
                      var f = this.force, m = this.mass;
                      f.x += m*gx; f.y += m*gy; f.z += m*gz;
                  }
              }
              if(this.angularDamping == 1) {
                  this.torque.setZero();
              }
          }
      };

      var direction = new Vec3();
      var end = new Vec3();
      var end2 = new Vec3();
      var end3 = new Vec3();
      var startToEnd = new Vec3();
      var rememberPosition = new Vec3();
      var result = new RaycastResult();
      var result1 = new RaycastResult();
      var result2 = new RaycastResult();
      var v3_0 = new Vec3();
      var v3_1 = new Vec3();
      var vel_norm = new Vec3();
      var m33 = new Mat3();
      Body.prototype.integrateToTimeOfImpact = function(dt){
          direction.copy(this.velocity);
          direction.normalize();

          this.velocity.mult(dt, end2);
          end2.vadd(this.position, end);

          end.vsub(this.position, startToEnd);
          var len = startToEnd.length();

          var hitBody;
          var g = this.collisionFilterGroup;
          this.collisionFilterGroup = 0;
          var radius = 1;
          for(var i=0; i<this.shapes.length; i++){
              var shape = this.shapes[i];
              var opt = {
                  collisionFilterMask: shape.collisionFilterMask,
                  collisionFilterGroup: shape.collisionFilterGroup,
                  skipBackfaces: true
              };
              v3_0.copy(this.position); // ray start
              v3_0.vadd(startToEnd, v3_1); // ray end
              Body.DrawLine(v3_0, v3_1);
              this.world.raycastClosest(v3_0, v3_1, opt, result);
              hitBody = result.body;
              if(shape.type === Shape.types.SPHERE){
                  radius = shape.radius;
                  if(World.ccdSphereAdvance){
                      vel_norm.copy(this.velocity); vel_norm.y = 0;
                      vel_norm.normalize(); v3_0.copy(vel_norm); m33.identity();
                      m33.elements[0] = v3_0.x;
                      m33.elements[1] = -v3_0.z;
                      m33.elements[3] = v3_0.z;
                      m33.elements[4] = v3_0.x;
                      end3.set(0,shape.radius,0);
                      m33.vmult(end3,end3);
                      end3.z=end3.y;end3.y=0;
                      end3.vadd(this.position,v3_0);
                      end2.vadd(v3_0, v3_1);
                      Body.DrawLine(v3_0, v3_1);
                      this.world.raycastClosest(v3_0, v3_1, opt, result1);
                      end3.negate(end3);
                      end3.vadd(this.position,v3_0);
                      end2.vadd(v3_0, v3_1);
                      Body.DrawLine(v3_0, v3_1);
                      this.world.raycastClosest(v3_0, v3_1, opt, result2);
                      if(result1.hasHit){
                          result1.hitPointWorld.vsub(this.position, v3_0);
                          var d = direction.dot(v3_0);
                          if(!result.hasHit||result.distance > d){
                              result.hasHit = true;
                              result.distance = d;
                              hitBody = result1.body;
                              direction.mult(d, v3_0);
                              v3_0.vadd(this.position, result.hitPointWorld);
                          }
                      }
                      if(result2.hasHit){
                          result2.hitPointWorld.vsub(this.position, v3_0);
                          var d = direction.dot(v3_0);
                          if(!result.hasHit||result.distance > d){
                              result.hasHit = true;
                              result.distance = d;
                              hitBody = result2.body;
                              direction.mult(d, v3_0);
                              v3_0.vadd(this.position, result.hitPointWorld);
                          }
                      }
                  }
              }
              if(hitBody)break;
          }
          this.collisionFilterGroup = g;
          if(!hitBody) return false;
          
          if(result.hasHit) Body.DrawSphere(result.hitPointWorld, 0.05);
          if(result1.hasHit) Body.DrawSphere(result1.hitPointWorld, 0.05);
          if(result2.hasHit) Body.DrawSphere(result2.hitPointWorld, 0.05);

          var timeOfImpact = 1;
          end = result.hitPointWorld;
          end.vsub(this.position, startToEnd);
          timeOfImpact = result.distance / len; // guess

          rememberPosition.copy(this.position);

          // Got a start and end point. Approximate time of impact using binary search
          var iter = 0;
          var tmin = 0;
          var tmid = timeOfImpact;
          var tmax = 1;
          while (tmax >= tmin && iter < this.ccdIterations) {
              iter++;

              // calculate the midpoint
              tmid = (tmax + tmin) / 2;

              // Move the body to that point
              startToEnd.mult(tmid, integrate_velodt);
              rememberPosition.vadd(integrate_velodt, this.position);
              this.computeAABB();
              Body.DrawSphere(this.position, radius);
              // check overlap
              var overlaps = this.aabb.overlaps(hitBody.aabb);
              if (overlaps) {
                  var overlapResult = [];
                  this.world.narrowphase.getContacts([this], [hitBody], this.world, overlapResult, [], [], []);
                  overlaps = overlapResult.length > 0;
              }

              if (overlaps) {
                  // change max to search lower interval
                  tmax = tmid;
              } else {
                  // change min to search upper interval
                  tmin = tmid;
              }
          }

          timeOfImpact = tmax; // Need to guarantee overlap to resolve collisions

          this.position.copy(rememberPosition);

          // move to TOI
          startToEnd.mult(timeOfImpact, integrate_velodt);
          this.position.vadd(integrate_velodt, this.position);

          return true;
      };
      Body.DrawSphere=Body.DrawLine=function() {};
      /**
       * Is Sleeping
       */
      Body.prototype.isSleeping = function(){
          return this.sleepState === Body.SLEEPING;
      };

      /**
       * Is Sleepy
       */
      Body.prototype.isSleepy = function(){
          return this.sleepState === Body.SLEEPY;
      };

      /**
       * Is Awake
       */
      Body.prototype.isAwake = function(){
          return this.sleepState === Body.AWAKE;
      };

      /**
       * Update hasTrigger
       */
      Body.prototype.updateHasTrigger = function () {
          for (var i = this.shapes.length; i--;) {
              this.hasTrigger = !this.shapes[i].collisionResponse;
              if (this.hasTrigger) break;
          }
      };

      },{"../collision/AABB":3,"../collision/RaycastResult":11,"../material/Material":26,"../math/Mat3":28,"../math/Quaternion":29,"../math/Vec3":31,"../shapes/Box":38,"../shapes/Shape":44,"../utils/EventTarget":50,"../world/World":57}],33:[function(_dereq_,module,exports){
      _dereq_('./Body');
      var Vec3 = _dereq_('../math/Vec3');
      var Quaternion = _dereq_('../math/Quaternion');
      _dereq_('../collision/RaycastResult');
      var Ray = _dereq_('../collision/Ray');
      var WheelInfo = _dereq_('../objects/WheelInfo');

      module.exports = RaycastVehicle;

      /**
       * Vehicle helper class that casts rays from the wheel positions towards the ground and applies forces.
       * @class RaycastVehicle
       * @constructor
       * @param {object} [options]
       * @param {Body} [options.chassisBody] The car chassis body.
       * @param {integer} [options.indexRightAxis] Axis to use for right. x=0, y=1, z=2
       * @param {integer} [options.indexLeftAxis]
       * @param {integer} [options.indexUpAxis]
       */
      function RaycastVehicle(options){

          /**
           * @property {Body} chassisBody
           */
          this.chassisBody = options.chassisBody;

          /**
           * An array of WheelInfo objects.
           * @property {array} wheelInfos
           */
          this.wheelInfos = [];

          /**
           * Will be set to true if the car is sliding.
           * @property {boolean} sliding
           */
          this.sliding = false;

          /**
           * @property {World} world
           */
          this.world = null;

          /**
           * Index of the right axis, 0=x, 1=y, 2=z
           * @property {integer} indexRightAxis
           * @default 1
           */
          this.indexRightAxis = typeof(options.indexRightAxis) !== 'undefined' ? options.indexRightAxis : 1;

          /**
           * Index of the forward axis, 0=x, 1=y, 2=z
           * @property {integer} indexForwardAxis
           * @default 0
           */
          this.indexForwardAxis = typeof(options.indexForwardAxis) !== 'undefined' ? options.indexForwardAxis : 0;

          /**
           * Index of the up axis, 0=x, 1=y, 2=z
           * @property {integer} indexUpAxis
           * @default 2
           */
          this.indexUpAxis = typeof(options.indexUpAxis) !== 'undefined' ? options.indexUpAxis : 2;
      }

      new Vec3();
      new Vec3();
      new Vec3();
      var tmpVec4 = new Vec3();
      var tmpVec5 = new Vec3();
      var tmpVec6 = new Vec3();
      new Ray();

      /**
       * Add a wheel. For information about the options, see WheelInfo.
       * @method addWheel
       * @param {object} [options]
       */
      RaycastVehicle.prototype.addWheel = function(options){
          options = options || {};

          var info = new WheelInfo(options);
          var index = this.wheelInfos.length;
          this.wheelInfos.push(info);

          return index;
      };

      /**
       * Set the steering value of a wheel.
       * @method setSteeringValue
       * @param {number} value
       * @param {integer} wheelIndex
       */
      RaycastVehicle.prototype.setSteeringValue = function(value, wheelIndex){
          var wheel = this.wheelInfos[wheelIndex];
          wheel.steering = value;
      };

      new Vec3();

      /**
       * Set the wheel force to apply on one of the wheels each time step
       * @method applyEngineForce
       * @param  {number} value
       * @param  {integer} wheelIndex
       */
      RaycastVehicle.prototype.applyEngineForce = function(value, wheelIndex){
          this.wheelInfos[wheelIndex].engineForce = value;
      };

      /**
       * Set the braking force of a wheel
       * @method setBrake
       * @param {number} brake
       * @param {integer} wheelIndex
       */
      RaycastVehicle.prototype.setBrake = function(brake, wheelIndex){
          this.wheelInfos[wheelIndex].brake = brake;
      };

      /**
       * Add the vehicle including its constraints to the world.
       * @method addToWorld
       * @param {World} world
       */
      RaycastVehicle.prototype.addToWorld = function(world){
          this.constraints;
          world.addBody(this.chassisBody);
          var that = this;
          this.preStepCallback = function(){
              that.updateVehicle(world.dt);
          };
          world.addEventListener('preStep', this.preStepCallback);
          this.world = world;
      };

      /**
       * Get one of the wheel axles, world-oriented.
       * @private
       * @method getVehicleAxisWorld
       * @param  {integer} axisIndex
       * @param  {Vec3} result
       */
      RaycastVehicle.prototype.getVehicleAxisWorld = function(axisIndex, result){
          result.set(
              axisIndex === 0 ? 1 : 0,
              axisIndex === 1 ? 1 : 0,
              axisIndex === 2 ? 1 : 0
          );
          this.chassisBody.vectorToWorldFrame(result, result);
      };

      RaycastVehicle.prototype.updateVehicle = function(timeStep){
          var wheelInfos = this.wheelInfos;
          var numWheels = wheelInfos.length;
          var chassisBody = this.chassisBody;

          for (var i = 0; i < numWheels; i++) {
              this.updateWheelTransform(i);
          }

          this.currentVehicleSpeedKmHour = 3.6 * chassisBody.velocity.norm();

          var forwardWorld = new Vec3();
          this.getVehicleAxisWorld(this.indexForwardAxis, forwardWorld);

          if (forwardWorld.dot(chassisBody.velocity) < 0){
              this.currentVehicleSpeedKmHour *= -1;
          }

          // simulate suspension
          for (var i = 0; i < numWheels; i++) {
              this.castRay(wheelInfos[i]);
          }

          this.updateSuspension(timeStep);

          var impulse = new Vec3();
          var relpos = new Vec3();
          for (var i = 0; i < numWheels; i++) {
              //apply suspension force
              var wheel = wheelInfos[i];
              var suspensionForce = wheel.suspensionForce;
              if (suspensionForce > wheel.maxSuspensionForce) {
                  suspensionForce = wheel.maxSuspensionForce;
              }
              wheel.raycastResult.hitNormalWorld.scale(suspensionForce * timeStep, impulse);

              wheel.raycastResult.hitPointWorld.vsub(chassisBody.position, relpos);
              chassisBody.applyImpulse(impulse, relpos);
          }

          this.updateFriction(timeStep);

          var hitNormalWorldScaledWithProj = new Vec3();
          var fwd  = new Vec3();
          var vel = new Vec3();
          for (i = 0; i < numWheels; i++) {
              var wheel = wheelInfos[i];
              //var relpos = new Vec3();
              //wheel.chassisConnectionPointWorld.vsub(chassisBody.position, relpos);
              chassisBody.getVelocityAtWorldPoint(wheel.chassisConnectionPointWorld, vel);

              // Hack to get the rotation in the correct direction
              var m = 1;
              switch(this.indexUpAxis){
              case 1:
                  m = -1;
                  break;
              }

              if (wheel.isInContact) {

                  this.getVehicleAxisWorld(this.indexForwardAxis, fwd);
                  var proj = fwd.dot(wheel.raycastResult.hitNormalWorld);
                  wheel.raycastResult.hitNormalWorld.scale(proj, hitNormalWorldScaledWithProj);

                  fwd.vsub(hitNormalWorldScaledWithProj, fwd);

                  var proj2 = fwd.dot(vel);
                  wheel.deltaRotation = m * proj2 * timeStep / wheel.radius;
              }

              if((wheel.sliding || !wheel.isInContact) && wheel.engineForce !== 0 && wheel.useCustomSlidingRotationalSpeed){
                  // Apply custom rotation when accelerating and sliding
                  wheel.deltaRotation = (wheel.engineForce > 0 ? 1 : -1) * wheel.customSlidingRotationalSpeed * timeStep;
              }

              // Lock wheels
              if(Math.abs(wheel.brake) > Math.abs(wheel.engineForce)){
                  wheel.deltaRotation = 0;
              }

              wheel.rotation += wheel.deltaRotation; // Use the old value
              wheel.deltaRotation *= 0.99; // damping of rotation when not in contact
          }
      };

      RaycastVehicle.prototype.updateSuspension = function(deltaTime) {
          var chassisBody = this.chassisBody;
          var chassisMass = chassisBody.mass;
          var wheelInfos = this.wheelInfos;
          var numWheels = wheelInfos.length;

          for (var w_it = 0; w_it < numWheels; w_it++){
              var wheel = wheelInfos[w_it];

              if (wheel.isInContact){
                  var force;

                  // Spring
                  var susp_length = wheel.suspensionRestLength;
                  var current_length = wheel.suspensionLength;
                  var length_diff = (susp_length - current_length);

                  force = wheel.suspensionStiffness * length_diff * wheel.clippedInvContactDotSuspension;

                  // Damper
                  var projected_rel_vel = wheel.suspensionRelativeVelocity;
                  var susp_damping;
                  if (projected_rel_vel < 0) {
                      susp_damping = wheel.dampingCompression;
                  } else {
                      susp_damping = wheel.dampingRelaxation;
                  }
                  force -= susp_damping * projected_rel_vel;

                  wheel.suspensionForce = force * chassisMass;
                  if (wheel.suspensionForce < 0) {
                      wheel.suspensionForce = 0;
                  }
              } else {
                  wheel.suspensionForce = 0;
              }
          }
      };

      /**
       * Remove the vehicle including its constraints from the world.
       * @method removeFromWorld
       * @param {World} world
       */
      RaycastVehicle.prototype.removeFromWorld = function(world){
          this.constraints;
          world.remove(this.chassisBody);
          world.removeEventListener('preStep', this.preStepCallback);
          this.world = null;
      };

      var castRay_rayvector = new Vec3();
      var castRay_target = new Vec3();
      RaycastVehicle.prototype.castRay = function(wheel) {
          var rayvector = castRay_rayvector;
          var target = castRay_target;

          this.updateWheelTransformWorld(wheel);
          var chassisBody = this.chassisBody;

          var depth = -1;

          var raylen = wheel.suspensionRestLength + wheel.radius;

          wheel.directionWorld.scale(raylen, rayvector);
          var source = wheel.chassisConnectionPointWorld;
          source.vadd(rayvector, target);
          var raycastResult = wheel.raycastResult;

          raycastResult.reset();
          // Turn off ray collision with the chassis temporarily
          var oldState = chassisBody.collisionResponse;
          chassisBody.collisionResponse = false;

          // Cast ray against world
          this.world.rayTest(source, target, raycastResult);
          chassisBody.collisionResponse = oldState;

          var object = raycastResult.body;

          wheel.raycastResult.groundObject = 0;

          if (object) {
              depth = raycastResult.distance;
              wheel.raycastResult.hitNormalWorld  = raycastResult.hitNormalWorld;
              wheel.isInContact = true;

              var hitDistance = raycastResult.distance;
              wheel.suspensionLength = hitDistance - wheel.radius;

              // clamp on max suspension travel
              var minSuspensionLength = wheel.suspensionRestLength - wheel.maxSuspensionTravel;
              var maxSuspensionLength = wheel.suspensionRestLength + wheel.maxSuspensionTravel;
              if (wheel.suspensionLength < minSuspensionLength) {
                  wheel.suspensionLength = minSuspensionLength;
              }
              if (wheel.suspensionLength > maxSuspensionLength) {
                  wheel.suspensionLength = maxSuspensionLength;
                  wheel.raycastResult.reset();
              }

              var denominator = wheel.raycastResult.hitNormalWorld.dot(wheel.directionWorld);

              var chassis_velocity_at_contactPoint = new Vec3();
              chassisBody.getVelocityAtWorldPoint(wheel.raycastResult.hitPointWorld, chassis_velocity_at_contactPoint);

              var projVel = wheel.raycastResult.hitNormalWorld.dot( chassis_velocity_at_contactPoint );

              if (denominator >= -0.1) {
                  wheel.suspensionRelativeVelocity = 0;
                  wheel.clippedInvContactDotSuspension = 1 / 0.1;
              } else {
                  var inv = -1 / denominator;
                  wheel.suspensionRelativeVelocity = projVel * inv;
                  wheel.clippedInvContactDotSuspension = inv;
              }

          } else {

              //put wheel info as in rest position
              wheel.suspensionLength = wheel.suspensionRestLength + 0 * wheel.maxSuspensionTravel;
              wheel.suspensionRelativeVelocity = 0.0;
              wheel.directionWorld.scale(-1, wheel.raycastResult.hitNormalWorld);
              wheel.clippedInvContactDotSuspension = 1.0;
          }

          return depth;
      };

      RaycastVehicle.prototype.updateWheelTransformWorld = function(wheel){
          wheel.isInContact = false;
          var chassisBody = this.chassisBody;
          chassisBody.pointToWorldFrame(wheel.chassisConnectionPointLocal, wheel.chassisConnectionPointWorld);
          chassisBody.vectorToWorldFrame(wheel.directionLocal, wheel.directionWorld);
          chassisBody.vectorToWorldFrame(wheel.axleLocal, wheel.axleWorld);
      };


      /**
       * Update one of the wheel transform.
       * Note when rendering wheels: during each step, wheel transforms are updated BEFORE the chassis; ie. their position becomes invalid after the step. Thus when you render wheels, you must update wheel transforms before rendering them. See raycastVehicle demo for an example.
       * @method updateWheelTransform
       * @param {integer} wheelIndex The wheel index to update.
       */
      RaycastVehicle.prototype.updateWheelTransform = function(wheelIndex){
          var up = tmpVec4;
          var right = tmpVec5;
          var fwd = tmpVec6;

          var wheel = this.wheelInfos[wheelIndex];
          this.updateWheelTransformWorld(wheel);

          wheel.directionLocal.scale(-1, up);
          right.copy(wheel.axleLocal);
          up.cross(right, fwd);
          fwd.normalize();
          right.normalize();

          // Rotate around steering over the wheelAxle
          var steering = wheel.steering;
          var steeringOrn = new Quaternion();
          steeringOrn.setFromAxisAngle(up, steering);

          var rotatingOrn = new Quaternion();
          rotatingOrn.setFromAxisAngle(right, wheel.rotation);

          // World rotation of the wheel
          var q = wheel.worldTransform.quaternion;
          this.chassisBody.quaternion.mult(steeringOrn, q);
          q.mult(rotatingOrn, q);

          q.normalize();

          // world position of the wheel
          var p = wheel.worldTransform.position;
          p.copy(wheel.directionWorld);
          p.scale(wheel.suspensionLength, p);
          p.vadd(wheel.chassisConnectionPointWorld, p);
      };

      var directions = [
          new Vec3(1, 0, 0),
          new Vec3(0, 1, 0),
          new Vec3(0, 0, 1)
      ];

      /**
       * Get the world transform of one of the wheels
       * @method getWheelTransformWorld
       * @param  {integer} wheelIndex
       * @return {Transform}
       */
      RaycastVehicle.prototype.getWheelTransformWorld = function(wheelIndex) {
          return this.wheelInfos[wheelIndex].worldTransform;
      };


      var updateFriction_surfNormalWS_scaled_proj = new Vec3();
      var updateFriction_axle = [];
      var updateFriction_forwardWS = [];
      var sideFrictionStiffness2 = 1;
      RaycastVehicle.prototype.updateFriction = function(timeStep) {
          var surfNormalWS_scaled_proj = updateFriction_surfNormalWS_scaled_proj;

          //calculate the impulse, so that the wheels don't move sidewards
          var wheelInfos = this.wheelInfos;
          var numWheels = wheelInfos.length;
          var chassisBody = this.chassisBody;
          var forwardWS = updateFriction_forwardWS;
          var axle = updateFriction_axle;

          for (var i = 0; i < numWheels; i++) {
              var wheel = wheelInfos[i];

              var groundObject = wheel.raycastResult.body;

              wheel.sideImpulse = 0;
              wheel.forwardImpulse = 0;
              if(!forwardWS[i]){
                  forwardWS[i] = new Vec3();
              }
              if(!axle[i]){
                  axle[i] = new Vec3();
              }
          }

          for (var i = 0; i < numWheels; i++){
              var wheel = wheelInfos[i];

              var groundObject = wheel.raycastResult.body;

              if (groundObject) {
                  var axlei = axle[i];
                  var wheelTrans = this.getWheelTransformWorld(i);

                  // Get world axle
                  wheelTrans.vectorToWorldFrame(directions[this.indexRightAxis], axlei);

                  var surfNormalWS = wheel.raycastResult.hitNormalWorld;
                  var proj = axlei.dot(surfNormalWS);
                  surfNormalWS.scale(proj, surfNormalWS_scaled_proj);
                  axlei.vsub(surfNormalWS_scaled_proj, axlei);
                  axlei.normalize();

                  surfNormalWS.cross(axlei, forwardWS[i]);
                  forwardWS[i].normalize();

                  wheel.sideImpulse = resolveSingleBilateral(
                      chassisBody,
                      wheel.raycastResult.hitPointWorld,
                      groundObject,
                      wheel.raycastResult.hitPointWorld,
                      axlei
                  );

                  wheel.sideImpulse *= sideFrictionStiffness2;
              }
          }

          var sideFactor = 1;
          var fwdFactor = 0.5;

          this.sliding = false;
          for (var i = 0; i < numWheels; i++) {
              var wheel = wheelInfos[i];
              var groundObject = wheel.raycastResult.body;

              var rollingFriction = 0;

              wheel.slipInfo = 1;
              if (groundObject) {
                  var defaultRollingFrictionImpulse = 0;
                  var maxImpulse = wheel.brake ? wheel.brake : defaultRollingFrictionImpulse;

                  // btWheelContactPoint contactPt(chassisBody,groundObject,wheelInfraycastInfo.hitPointWorld,forwardWS[wheel],maxImpulse);
                  // rollingFriction = calcRollingFriction(contactPt);
                  rollingFriction = calcRollingFriction(chassisBody, groundObject, wheel.raycastResult.hitPointWorld, forwardWS[i], maxImpulse);

                  rollingFriction += wheel.engineForce * timeStep;

                  // rollingFriction = 0;
                  var factor = maxImpulse / rollingFriction;
                  wheel.slipInfo *= factor;
              }

              //switch between active rolling (throttle), braking and non-active rolling friction (nthrottle/break)

              wheel.forwardImpulse = 0;
              wheel.skidInfo = 1;

              if (groundObject) {
                  wheel.skidInfo = 1;

                  var maximp = wheel.suspensionForce * timeStep * wheel.frictionSlip;
                  var maximpSide = maximp;

                  var maximpSquared = maximp * maximpSide;

                  wheel.forwardImpulse = rollingFriction;//wheelInfo.engineForce* timeStep;

                  var x = wheel.forwardImpulse * fwdFactor;
                  var y = wheel.sideImpulse * sideFactor;

                  var impulseSquared = x * x + y * y;

                  wheel.sliding = false;
                  if (impulseSquared > maximpSquared) {
                      this.sliding = true;
                      wheel.sliding = true;

                      var factor = maximp / Math.sqrt(impulseSquared);

                      wheel.skidInfo *= factor;
                  }
              }
          }

          if (this.sliding) {
              for (var i = 0; i < numWheels; i++) {
                  var wheel = wheelInfos[i];
                  if (wheel.sideImpulse !== 0) {
                      if (wheel.skidInfo < 1){
                          wheel.forwardImpulse *= wheel.skidInfo;
                          wheel.sideImpulse *= wheel.skidInfo;
                      }
                  }
              }
          }

          // apply the impulses
          for (var i = 0; i < numWheels; i++) {
              var wheel = wheelInfos[i];

              var rel_pos = new Vec3();
              wheel.raycastResult.hitPointWorld.vsub(chassisBody.position, rel_pos);
              // cannons applyimpulse is using world coord for the position
              //rel_pos.copy(wheel.raycastResult.hitPointWorld);

              if (wheel.forwardImpulse !== 0) {
                  var impulse = new Vec3();
                  forwardWS[i].scale(wheel.forwardImpulse, impulse);
                  chassisBody.applyImpulse(impulse, rel_pos);
              }

              if (wheel.sideImpulse !== 0){
                  var groundObject = wheel.raycastResult.body;

                  var rel_pos2 = new Vec3();
                  wheel.raycastResult.hitPointWorld.vsub(groundObject.position, rel_pos2);
                  //rel_pos2.copy(wheel.raycastResult.hitPointWorld);
                  var sideImp = new Vec3();
                  axle[i].scale(wheel.sideImpulse, sideImp);

                  // Scale the relative position in the up direction with rollInfluence.
                  // If rollInfluence is 1, the impulse will be applied on the hitPoint (easy to roll over), if it is zero it will be applied in the same plane as the center of mass (not easy to roll over).
                  chassisBody.vectorToLocalFrame(rel_pos, rel_pos);
                  rel_pos['xyz'[this.indexUpAxis]] *= wheel.rollInfluence;
                  chassisBody.vectorToWorldFrame(rel_pos, rel_pos);
                  chassisBody.applyImpulse(sideImp, rel_pos);

                  //apply friction impulse on the ground
                  sideImp.scale(-1, sideImp);
                  groundObject.applyImpulse(sideImp, rel_pos2);
              }
          }
      };

      var calcRollingFriction_vel1 = new Vec3();
      var calcRollingFriction_vel2 = new Vec3();
      var calcRollingFriction_vel = new Vec3();

      function calcRollingFriction(body0, body1, frictionPosWorld, frictionDirectionWorld, maxImpulse) {
          var j1 = 0;
          var contactPosWorld = frictionPosWorld;

          // var rel_pos1 = new Vec3();
          // var rel_pos2 = new Vec3();
          var vel1 = calcRollingFriction_vel1;
          var vel2 = calcRollingFriction_vel2;
          var vel = calcRollingFriction_vel;
          // contactPosWorld.vsub(body0.position, rel_pos1);
          // contactPosWorld.vsub(body1.position, rel_pos2);

          body0.getVelocityAtWorldPoint(contactPosWorld, vel1);
          body1.getVelocityAtWorldPoint(contactPosWorld, vel2);
          vel1.vsub(vel2, vel);

          var vrel = frictionDirectionWorld.dot(vel);

          var denom0 = computeImpulseDenominator(body0, frictionPosWorld, frictionDirectionWorld);
          var denom1 = computeImpulseDenominator(body1, frictionPosWorld, frictionDirectionWorld);
          var relaxation = 1;
          var jacDiagABInv = relaxation / (denom0 + denom1);

          // calculate j that moves us to zero relative velocity
          j1 = -vrel * jacDiagABInv;

          if (maxImpulse < j1) {
              j1 = maxImpulse;
          }
          if (j1 < -maxImpulse) {
              j1 = -maxImpulse;
          }

          return j1;
      }

      var computeImpulseDenominator_r0 = new Vec3();
      var computeImpulseDenominator_c0 = new Vec3();
      var computeImpulseDenominator_vec = new Vec3();
      var computeImpulseDenominator_m = new Vec3();
      function computeImpulseDenominator(body, pos, normal) {
          var r0 = computeImpulseDenominator_r0;
          var c0 = computeImpulseDenominator_c0;
          var vec = computeImpulseDenominator_vec;
          var m = computeImpulseDenominator_m;

          pos.vsub(body.position, r0);
          r0.cross(normal, c0);
          body.invInertiaWorld.vmult(c0, m);
          m.cross(r0, vec);

          return body.invMass + normal.dot(vec);
      }


      var resolveSingleBilateral_vel1 = new Vec3();
      var resolveSingleBilateral_vel2 = new Vec3();
      var resolveSingleBilateral_vel = new Vec3();

      //bilateral constraint between two dynamic objects
      function resolveSingleBilateral(body1, pos1, body2, pos2, normal, impulse){
          var normalLenSqr = normal.norm2();
          if (normalLenSqr > 1.1){
              return 0; // no impulse
          }
          // var rel_pos1 = new Vec3();
          // var rel_pos2 = new Vec3();
          // pos1.vsub(body1.position, rel_pos1);
          // pos2.vsub(body2.position, rel_pos2);

          var vel1 = resolveSingleBilateral_vel1;
          var vel2 = resolveSingleBilateral_vel2;
          var vel = resolveSingleBilateral_vel;
          body1.getVelocityAtWorldPoint(pos1, vel1);
          body2.getVelocityAtWorldPoint(pos2, vel2);

          vel1.vsub(vel2, vel);

          var rel_vel = normal.dot(vel);

          var contactDamping = 0.2;
          var massTerm = 1 / (body1.invMass + body2.invMass);
          var impulse = - contactDamping * rel_vel * massTerm;

          return impulse;
      }
      },{"../collision/Ray":10,"../collision/RaycastResult":11,"../math/Quaternion":29,"../math/Vec3":31,"../objects/WheelInfo":37,"./Body":32}],34:[function(_dereq_,module,exports){
      var Body = _dereq_('./Body');
      var Sphere = _dereq_('../shapes/Sphere');
      var Box = _dereq_('../shapes/Box');
      var Vec3 = _dereq_('../math/Vec3');
      var HingeConstraint = _dereq_('../constraints/HingeConstraint');

      module.exports = RigidVehicle;

      /**
       * Simple vehicle helper class with spherical rigid body wheels.
       * @class RigidVehicle
       * @constructor
       * @param {Body} [options.chassisBody]
       */
      function RigidVehicle(options){
          this.wheelBodies = [];

          /**
           * @property coordinateSystem
           * @type {Vec3}
           */
          this.coordinateSystem = typeof(options.coordinateSystem)==='undefined' ? new Vec3(1, 2, 3) : options.coordinateSystem.clone();

          /**
           * @property {Body} chassisBody
           */
          this.chassisBody = options.chassisBody;

          if(!this.chassisBody){
              // No chassis body given. Create it!
              var chassisShape = new Box(new Vec3(5, 2, 0.5));
              this.chassisBody = new Body(1, chassisShape);
          }

          /**
           * @property constraints
           * @type {Array}
           */
          this.constraints = [];

          this.wheelAxes = [];
          this.wheelForces = [];
      }

      /**
       * Add a wheel
       * @method addWheel
       * @param {object} options
       * @param {boolean} [options.isFrontWheel]
       * @param {Vec3} [options.position] Position of the wheel, locally in the chassis body.
       * @param {Vec3} [options.direction] Slide direction of the wheel along the suspension.
       * @param {Vec3} [options.axis] Axis of rotation of the wheel, locally defined in the chassis.
       * @param {Body} [options.body] The wheel body.
       */
      RigidVehicle.prototype.addWheel = function(options){
          options = options || {};
          var wheelBody = options.body;
          if(!wheelBody){
              wheelBody =  new Body(1, new Sphere(1.2));
          }
          this.wheelBodies.push(wheelBody);
          this.wheelForces.push(0);

          // Position constrain wheels
          new Vec3();
          var position = typeof(options.position) !== 'undefined' ? options.position.clone() : new Vec3();

          // Set position locally to the chassis
          var worldPosition = new Vec3();
          this.chassisBody.pointToWorldFrame(position, worldPosition);
          wheelBody.position.set(worldPosition.x, worldPosition.y, worldPosition.z);

          // Constrain wheel
          var axis = typeof(options.axis) !== 'undefined' ? options.axis.clone() : new Vec3(0, 1, 0);
          this.wheelAxes.push(axis);

          var hingeConstraint = new HingeConstraint(this.chassisBody, wheelBody, {
              pivotA: position,
              axisA: axis,
              pivotB: Vec3.ZERO,
              axisB: axis,
              collideConnected: false
          });
          this.constraints.push(hingeConstraint);

          return this.wheelBodies.length - 1;
      };

      /**
       * Set the steering value of a wheel.
       * @method setSteeringValue
       * @param {number} value
       * @param {integer} wheelIndex
       * @todo check coordinateSystem
       */
      RigidVehicle.prototype.setSteeringValue = function(value, wheelIndex){
          // Set angle of the hinge axis
          var axis = this.wheelAxes[wheelIndex];

          var c = Math.cos(value),
              s = Math.sin(value),
              x = axis.x,
              y = axis.y;
          this.constraints[wheelIndex].axisA.set(
              c*x -s*y,
              s*x +c*y,
              0
          );
      };

      /**
       * Set the target rotational speed of the hinge constraint.
       * @method setMotorSpeed
       * @param {number} value
       * @param {integer} wheelIndex
       */
      RigidVehicle.prototype.setMotorSpeed = function(value, wheelIndex){
          var hingeConstraint = this.constraints[wheelIndex];
          hingeConstraint.enableMotor();
          hingeConstraint.motorTargetVelocity = value;
      };

      /**
       * Set the target rotational speed of the hinge constraint.
       * @method disableMotor
       * @param {number} value
       * @param {integer} wheelIndex
       */
      RigidVehicle.prototype.disableMotor = function(wheelIndex){
          var hingeConstraint = this.constraints[wheelIndex];
          hingeConstraint.disableMotor();
      };

      var torque = new Vec3();

      /**
       * Set the wheel force to apply on one of the wheels each time step
       * @method setWheelForce
       * @param  {number} value
       * @param  {integer} wheelIndex
       */
      RigidVehicle.prototype.setWheelForce = function(value, wheelIndex){
          this.wheelForces[wheelIndex] = value;
      };

      /**
       * Apply a torque on one of the wheels.
       * @method applyWheelForce
       * @param  {number} value
       * @param  {integer} wheelIndex
       */
      RigidVehicle.prototype.applyWheelForce = function(value, wheelIndex){
          var axis = this.wheelAxes[wheelIndex];
          var wheelBody = this.wheelBodies[wheelIndex];
          var bodyTorque = wheelBody.torque;

          axis.scale(value, torque);
          wheelBody.vectorToWorldFrame(torque, torque);
          bodyTorque.vadd(torque, bodyTorque);
      };

      /**
       * Add the vehicle including its constraints to the world.
       * @method addToWorld
       * @param {World} world
       */
      RigidVehicle.prototype.addToWorld = function(world){
          var constraints = this.constraints;
          var bodies = this.wheelBodies.concat([this.chassisBody]);

          for (var i = 0; i < bodies.length; i++) {
              world.addBody(bodies[i]);
          }

          for (var i = 0; i < constraints.length; i++) {
              world.addConstraint(constraints[i]);
          }

          world.addEventListener('preStep', this._update.bind(this));
      };

      RigidVehicle.prototype._update = function(){
          var wheelForces = this.wheelForces;
          for (var i = 0; i < wheelForces.length; i++) {
              this.applyWheelForce(wheelForces[i], i);
          }
      };

      /**
       * Remove the vehicle including its constraints from the world.
       * @method removeFromWorld
       * @param {World} world
       */
      RigidVehicle.prototype.removeFromWorld = function(world){
          var constraints = this.constraints;
          var bodies = this.wheelBodies.concat([this.chassisBody]);

          for (var i = 0; i < bodies.length; i++) {
              world.remove(bodies[i]);
          }

          for (var i = 0; i < constraints.length; i++) {
              world.removeConstraint(constraints[i]);
          }
      };

      var worldAxis = new Vec3();

      /**
       * Get current rotational velocity of a wheel
       * @method getWheelSpeed
       * @param {integer} wheelIndex
       */
      RigidVehicle.prototype.getWheelSpeed = function(wheelIndex){
          var axis = this.wheelAxes[wheelIndex];
          var wheelBody = this.wheelBodies[wheelIndex];
          var w = wheelBody.angularVelocity;
          this.chassisBody.vectorToWorldFrame(axis, worldAxis);
          return w.dot(worldAxis);
      };

      },{"../constraints/HingeConstraint":16,"../math/Vec3":31,"../shapes/Box":38,"../shapes/Sphere":45,"./Body":32}],35:[function(_dereq_,module,exports){
      module.exports = SPHSystem;

      _dereq_('../shapes/Shape');
      var Vec3 = _dereq_('../math/Vec3');
      _dereq_('../math/Quaternion');
      _dereq_('../shapes/Particle');
      _dereq_('../objects/Body');
      _dereq_('../material/Material');

      /**
       * Smoothed-particle hydrodynamics system
       * @class SPHSystem
       * @constructor
       */
      function SPHSystem(){
          this.particles = [];
      	
          /**
           * Density of the system (kg/m3).
           * @property {number} density
           */
          this.density = 1;
      	
          /**
           * Distance below which two particles are considered to be neighbors.
           * It should be adjusted so there are about 15-20 neighbor particles within this radius.
           * @property {number} smoothingRadius
           */
          this.smoothingRadius = 1;
          this.speedOfSound = 1;
      	
          /**
           * Viscosity of the system.
           * @property {number} viscosity
           */
          this.viscosity = 0.01;
          this.eps = 0.000001;

          // Stuff Computed per particle
          this.pressures = [];
          this.densities = [];
          this.neighbors = [];
      }

      /**
       * Add a particle to the system.
       * @method add
       * @param {Body} particle
       */
      SPHSystem.prototype.add = function(particle){
          this.particles.push(particle);
          if(this.neighbors.length < this.particles.length){
              this.neighbors.push([]);
          }
      };

      /**
       * Remove a particle from the system.
       * @method remove
       * @param {Body} particle
       */
      SPHSystem.prototype.remove = function(particle){
          var idx = this.particles.indexOf(particle);
          if(idx !== -1){
              this.particles.splice(idx,1);
              if(this.neighbors.length > this.particles.length){
                  this.neighbors.pop();
              }
          }
      };

      /**
       * Get neighbors within smoothing volume, save in the array neighbors
       * @method getNeighbors
       * @param {Body} particle
       * @param {Array} neighbors
       */
      var SPHSystem_getNeighbors_dist = new Vec3();
      SPHSystem.prototype.getNeighbors = function(particle,neighbors){
          var N = this.particles.length,
              id = particle.id,
              R2 = this.smoothingRadius * this.smoothingRadius,
              dist = SPHSystem_getNeighbors_dist;
          for(var i=0; i!==N; i++){
              var p = this.particles[i];
              p.position.vsub(particle.position,dist);
              if(id!==p.id && dist.norm2() < R2){
                  neighbors.push(p);
              }
          }
      };

      // Temp vectors for calculation
      var SPHSystem_update_dist = new Vec3(),
          SPHSystem_update_a_pressure = new Vec3(),
          SPHSystem_update_a_visc = new Vec3(),
          SPHSystem_update_gradW = new Vec3(),
          SPHSystem_update_r_vec = new Vec3(),
          SPHSystem_update_u = new Vec3(); // Relative velocity
      SPHSystem.prototype.update = function(){
          var N = this.particles.length,
              dist = SPHSystem_update_dist,
              cs = this.speedOfSound,
              eps = this.eps;

          for(var i=0; i!==N; i++){
              var p = this.particles[i]; // Current particle
              var neighbors = this.neighbors[i];

              // Get neighbors
              neighbors.length = 0;
              this.getNeighbors(p,neighbors);
              neighbors.push(this.particles[i]); // Add current too
              var numNeighbors = neighbors.length;

              // Accumulate density for the particle
              var sum = 0.0;
              for(var j=0; j!==numNeighbors; j++){

                  //printf("Current particle has position %f %f %f\n",objects[id].pos.x(),objects[id].pos.y(),objects[id].pos.z());
                  p.position.vsub(neighbors[j].position, dist);
                  var len = dist.norm();

                  var weight = this.w(len);
                  sum += neighbors[j].mass * weight;
              }

              // Save
              this.densities[i] = sum;
              this.pressures[i] = cs * cs * (this.densities[i] - this.density);
          }

          // Add forces

          // Sum to these accelerations
          var a_pressure= SPHSystem_update_a_pressure;
          var a_visc =    SPHSystem_update_a_visc;
          var gradW =     SPHSystem_update_gradW;
          var r_vec =     SPHSystem_update_r_vec;
          var u =         SPHSystem_update_u;

          for(var i=0; i!==N; i++){

              var particle = this.particles[i];

              a_pressure.set(0,0,0);
              a_visc.set(0,0,0);

              // Init vars
              var Pij;
              var nabla;

              // Sum up for all other neighbors
              var neighbors = this.neighbors[i];
              var numNeighbors = neighbors.length;

              //printf("Neighbors: ");
              for(var j=0; j!==numNeighbors; j++){

                  var neighbor = neighbors[j];
                  //printf("%d ",nj);

                  // Get r once for all..
                  particle.position.vsub(neighbor.position,r_vec);
                  var r = r_vec.norm();

                  // Pressure contribution
                  Pij = -neighbor.mass * (this.pressures[i] / (this.densities[i]*this.densities[i] + eps) + this.pressures[j] / (this.densities[j]*this.densities[j] + eps));
                  this.gradw(r_vec, gradW);
                  // Add to pressure acceleration
                  gradW.mult(Pij , gradW);
                  a_pressure.vadd(gradW, a_pressure);

                  // Viscosity contribution
                  neighbor.velocity.vsub(particle.velocity, u);
                  u.mult( 1.0 / (0.0001+this.densities[i] * this.densities[j]) * this.viscosity * neighbor.mass , u );
                  nabla = this.nablaw(r);
                  u.mult(nabla,u);
                  // Add to viscosity acceleration
                  a_visc.vadd( u, a_visc );
              }

              // Calculate force
              a_visc.mult(particle.mass, a_visc);
              a_pressure.mult(particle.mass, a_pressure);

              // Add force to particles
              particle.force.vadd(a_visc, particle.force);
              particle.force.vadd(a_pressure, particle.force);
          }
      };

      // Calculate the weight using the W(r) weightfunction
      SPHSystem.prototype.w = function(r){
          // 315
          var h = this.smoothingRadius;
          return 315.0/(64.0*Math.PI*Math.pow(h,9)) * Math.pow(h*h-r*r,3);
      };

      // calculate gradient of the weight function
      SPHSystem.prototype.gradw = function(rVec,resultVec){
          var r = rVec.norm(),
              h = this.smoothingRadius;
          rVec.mult(945.0/(32.0*Math.PI*Math.pow(h,9)) * Math.pow((h*h-r*r),2) , resultVec);
      };

      // Calculate nabla(W)
      SPHSystem.prototype.nablaw = function(r){
          var h = this.smoothingRadius;
          var nabla = 945.0/(32.0*Math.PI*Math.pow(h,9)) * (h*h-r*r)*(7*r*r - 3*h*h);
          return nabla;
      };

      },{"../material/Material":26,"../math/Quaternion":29,"../math/Vec3":31,"../objects/Body":32,"../shapes/Particle":42,"../shapes/Shape":44}],36:[function(_dereq_,module,exports){
      var Vec3 = _dereq_('../math/Vec3');

      module.exports = Spring;

      /**
       * A spring, connecting two bodies.
       *
       * @class Spring
       * @constructor
       * @param {Body} bodyA
       * @param {Body} bodyB
       * @param {Object} [options]
       * @param {number} [options.restLength]   A number > 0. Default: 1
       * @param {number} [options.stiffness]    A number >= 0. Default: 100
       * @param {number} [options.damping]      A number >= 0. Default: 1
       * @param {Vec3}  [options.worldAnchorA] Where to hook the spring to body A, in world coordinates.
       * @param {Vec3}  [options.worldAnchorB]
       * @param {Vec3}  [options.localAnchorA] Where to hook the spring to body A, in local body coordinates.
       * @param {Vec3}  [options.localAnchorB]
       */
      function Spring(bodyA,bodyB,options){
          options = options || {};

          /**
           * Rest length of the spring.
           * @property restLength
           * @type {number}
           */
          this.restLength = typeof(options.restLength) === "number" ? options.restLength : 1;

          /**
           * Stiffness of the spring.
           * @property stiffness
           * @type {number}
           */
          this.stiffness = options.stiffness || 100;

          /**
           * Damping of the spring.
           * @property damping
           * @type {number}
           */
          this.damping = options.damping || 1;

          /**
           * First connected body.
           * @property bodyA
           * @type {Body}
           */
          this.bodyA = bodyA;

          /**
           * Second connected body.
           * @property bodyB
           * @type {Body}
           */
          this.bodyB = bodyB;

          /**
           * Anchor for bodyA in local bodyA coordinates.
           * @property localAnchorA
           * @type {Vec3}
           */
          this.localAnchorA = new Vec3();

          /**
           * Anchor for bodyB in local bodyB coordinates.
           * @property localAnchorB
           * @type {Vec3}
           */
          this.localAnchorB = new Vec3();

          if(options.localAnchorA){
              this.localAnchorA.copy(options.localAnchorA);
          }
          if(options.localAnchorB){
              this.localAnchorB.copy(options.localAnchorB);
          }
          if(options.worldAnchorA){
              this.setWorldAnchorA(options.worldAnchorA);
          }
          if(options.worldAnchorB){
              this.setWorldAnchorB(options.worldAnchorB);
          }
      }

      /**
       * Set the anchor point on body A, using world coordinates.
       * @method setWorldAnchorA
       * @param {Vec3} worldAnchorA
       */
      Spring.prototype.setWorldAnchorA = function(worldAnchorA){
          this.bodyA.pointToLocalFrame(worldAnchorA,this.localAnchorA);
      };

      /**
       * Set the anchor point on body B, using world coordinates.
       * @method setWorldAnchorB
       * @param {Vec3} worldAnchorB
       */
      Spring.prototype.setWorldAnchorB = function(worldAnchorB){
          this.bodyB.pointToLocalFrame(worldAnchorB,this.localAnchorB);
      };

      /**
       * Get the anchor point on body A, in world coordinates.
       * @method getWorldAnchorA
       * @param {Vec3} result The vector to store the result in.
       */
      Spring.prototype.getWorldAnchorA = function(result){
          this.bodyA.pointToWorldFrame(this.localAnchorA,result);
      };

      /**
       * Get the anchor point on body B, in world coordinates.
       * @method getWorldAnchorB
       * @param {Vec3} result The vector to store the result in.
       */
      Spring.prototype.getWorldAnchorB = function(result){
          this.bodyB.pointToWorldFrame(this.localAnchorB,result);
      };

      var applyForce_r =              new Vec3(),
          applyForce_r_unit =         new Vec3(),
          applyForce_u =              new Vec3(),
          applyForce_f =              new Vec3(),
          applyForce_worldAnchorA =   new Vec3(),
          applyForce_worldAnchorB =   new Vec3(),
          applyForce_ri =             new Vec3(),
          applyForce_rj =             new Vec3(),
          applyForce_ri_x_f =         new Vec3(),
          applyForce_rj_x_f =         new Vec3(),
          applyForce_tmp =            new Vec3();

      /**
       * Apply the spring force to the connected bodies.
       * @method applyForce
       */
      Spring.prototype.applyForce = function(){
          var k = this.stiffness,
              d = this.damping,
              l = this.restLength,
              bodyA = this.bodyA,
              bodyB = this.bodyB,
              r = applyForce_r,
              r_unit = applyForce_r_unit,
              u = applyForce_u,
              f = applyForce_f,
              tmp = applyForce_tmp;

          var worldAnchorA = applyForce_worldAnchorA,
              worldAnchorB = applyForce_worldAnchorB,
              ri = applyForce_ri,
              rj = applyForce_rj,
              ri_x_f = applyForce_ri_x_f,
              rj_x_f = applyForce_rj_x_f;

          // Get world anchors
          this.getWorldAnchorA(worldAnchorA);
          this.getWorldAnchorB(worldAnchorB);

          // Get offset points
          worldAnchorA.vsub(bodyA.position,ri);
          worldAnchorB.vsub(bodyB.position,rj);

          // Compute distance vector between world anchor points
          worldAnchorB.vsub(worldAnchorA,r);
          var rlen = r.norm();
          r_unit.copy(r);
          r_unit.normalize();

          // Compute relative velocity of the anchor points, u
          bodyB.velocity.vsub(bodyA.velocity,u);
          // Add rotational velocity

          bodyB.angularVelocity.cross(rj,tmp);
          u.vadd(tmp,u);
          bodyA.angularVelocity.cross(ri,tmp);
          u.vsub(tmp,u);

          // F = - k * ( x - L ) - D * ( u )
          r_unit.mult(-k*(rlen-l) - d*u.dot(r_unit), f);

          // Add forces to bodies
          bodyA.force.vsub(f,bodyA.force);
          bodyB.force.vadd(f,bodyB.force);

          // Angular force
          ri.cross(f,ri_x_f);
          rj.cross(f,rj_x_f);
          bodyA.torque.vsub(ri_x_f,bodyA.torque);
          bodyB.torque.vadd(rj_x_f,bodyB.torque);
      };

      },{"../math/Vec3":31}],37:[function(_dereq_,module,exports){
      var Vec3 = _dereq_('../math/Vec3');
      var Transform = _dereq_('../math/Transform');
      var RaycastResult = _dereq_('../collision/RaycastResult');
      var Utils = _dereq_('../utils/Utils');

      module.exports = WheelInfo;

      /**
       * @class WheelInfo
       * @constructor
       * @param {Object} [options]
       *
       * @param {Vec3} [options.chassisConnectionPointLocal]
       * @param {Vec3} [options.chassisConnectionPointWorld]
       * @param {Vec3} [options.directionLocal]
       * @param {Vec3} [options.directionWorld]
       * @param {Vec3} [options.axleLocal]
       * @param {Vec3} [options.axleWorld]
       * @param {number} [options.suspensionRestLength=1]
       * @param {number} [options.suspensionMaxLength=2]
       * @param {number} [options.radius=1]
       * @param {number} [options.suspensionStiffness=100]
       * @param {number} [options.dampingCompression=10]
       * @param {number} [options.dampingRelaxation=10]
       * @param {number} [options.frictionSlip=10000]
       * @param {number} [options.steering=0]
       * @param {number} [options.rotation=0]
       * @param {number} [options.deltaRotation=0]
       * @param {number} [options.rollInfluence=0.01]
       * @param {number} [options.maxSuspensionForce]
       * @param {boolean} [options.isFrontWheel=true]
       * @param {number} [options.clippedInvContactDotSuspension=1]
       * @param {number} [options.suspensionRelativeVelocity=0]
       * @param {number} [options.suspensionForce=0]
       * @param {number} [options.skidInfo=0]
       * @param {number} [options.suspensionLength=0]
       * @param {number} [options.maxSuspensionTravel=1]
       * @param {boolean} [options.useCustomSlidingRotationalSpeed=false]
       * @param {number} [options.customSlidingRotationalSpeed=-0.1]
       */
      function WheelInfo(options){
          options = Utils.defaults(options, {
              chassisConnectionPointLocal: new Vec3(),
              chassisConnectionPointWorld: new Vec3(),
              directionLocal: new Vec3(),
              directionWorld: new Vec3(),
              axleLocal: new Vec3(),
              axleWorld: new Vec3(),
              suspensionRestLength: 1,
              suspensionMaxLength: 2,
              radius: 1,
              suspensionStiffness: 100,
              dampingCompression: 10,
              dampingRelaxation: 10,
              frictionSlip: 10000,
              steering: 0,
              rotation: 0,
              deltaRotation: 0,
              rollInfluence: 0.01,
              maxSuspensionForce: Number.MAX_VALUE,
              isFrontWheel: true,
              clippedInvContactDotSuspension: 1,
              suspensionRelativeVelocity: 0,
              suspensionForce: 0,
              skidInfo: 0,
              suspensionLength: 0,
              maxSuspensionTravel: 1,
              useCustomSlidingRotationalSpeed: false,
              customSlidingRotationalSpeed: -0.1
          });

          /**
           * Max travel distance of the suspension, in meters.
           * @property {number} maxSuspensionTravel
           */
          this.maxSuspensionTravel = options.maxSuspensionTravel;

          /**
           * Speed to apply to the wheel rotation when the wheel is sliding.
           * @property {number} customSlidingRotationalSpeed
           */
          this.customSlidingRotationalSpeed = options.customSlidingRotationalSpeed;

          /**
           * If the customSlidingRotationalSpeed should be used.
           * @property {Boolean} useCustomSlidingRotationalSpeed
           */
          this.useCustomSlidingRotationalSpeed = options.useCustomSlidingRotationalSpeed;

          /**
           * @property {Boolean} sliding
           */
          this.sliding = false;

          /**
           * Connection point, defined locally in the chassis body frame.
           * @property {Vec3} chassisConnectionPointLocal
           */
          this.chassisConnectionPointLocal = options.chassisConnectionPointLocal.clone();

          /**
           * @property {Vec3} chassisConnectionPointWorld
           */
          this.chassisConnectionPointWorld = options.chassisConnectionPointWorld.clone();

          /**
           * @property {Vec3} directionLocal
           */
          this.directionLocal = options.directionLocal.clone();

          /**
           * @property {Vec3} directionWorld
           */
          this.directionWorld = options.directionWorld.clone();

          /**
           * @property {Vec3} axleLocal
           */
          this.axleLocal = options.axleLocal.clone();

          /**
           * @property {Vec3} axleWorld
           */
          this.axleWorld = options.axleWorld.clone();

          /**
           * @property {number} suspensionRestLength
           */
          this.suspensionRestLength = options.suspensionRestLength;

          /**
           * @property {number} suspensionMaxLength
           */
          this.suspensionMaxLength = options.suspensionMaxLength;

          /**
           * @property {number} radius
           */
          this.radius = options.radius;

          /**
           * @property {number} suspensionStiffness
           */
          this.suspensionStiffness = options.suspensionStiffness;

          /**
           * @property {number} dampingCompression
           */
          this.dampingCompression = options.dampingCompression;

          /**
           * @property {number} dampingRelaxation
           */
          this.dampingRelaxation = options.dampingRelaxation;

          /**
           * @property {number} frictionSlip
           */
          this.frictionSlip = options.frictionSlip;

          /**
           * @property {number} steering
           */
          this.steering = 0;

          /**
           * Rotation value, in radians.
           * @property {number} rotation
           */
          this.rotation = 0;

          /**
           * @property {number} deltaRotation
           */
          this.deltaRotation = 0;

          /**
           * @property {number} rollInfluence
           */
          this.rollInfluence = options.rollInfluence;

          /**
           * @property {number} maxSuspensionForce
           */
          this.maxSuspensionForce = options.maxSuspensionForce;

          /**
           * @property {number} engineForce
           */
          this.engineForce = 0;

          /**
           * @property {number} brake
           */
          this.brake = 0;

          /**
           * @property {number} isFrontWheel
           */
          this.isFrontWheel = options.isFrontWheel;

          /**
           * @property {number} clippedInvContactDotSuspension
           */
          this.clippedInvContactDotSuspension = 1;

          /**
           * @property {number} suspensionRelativeVelocity
           */
          this.suspensionRelativeVelocity = 0;

          /**
           * @property {number} suspensionForce
           */
          this.suspensionForce = 0;

          /**
           * @property {number} skidInfo
           */
          this.skidInfo = 0;

          /**
           * @property {number} suspensionLength
           */
          this.suspensionLength = 0;

          /**
           * @property {number} sideImpulse
           */
          this.sideImpulse = 0;

          /**
           * @property {number} forwardImpulse
           */
          this.forwardImpulse = 0;

          /**
           * The result from raycasting
           * @property {RaycastResult} raycastResult
           */
          this.raycastResult = new RaycastResult();

          /**
           * Wheel world transform
           * @property {Transform} worldTransform
           */
          this.worldTransform = new Transform();

          /**
           * @property {boolean} isInContact
           */
          this.isInContact = false;
      }

      var chassis_velocity_at_contactPoint = new Vec3();
      var relpos = new Vec3();
      var chassis_velocity_at_contactPoint = new Vec3();
      WheelInfo.prototype.updateWheel = function(chassis){
          var raycastResult = this.raycastResult;

          if (this.isInContact){
              var project= raycastResult.hitNormalWorld.dot(raycastResult.directionWorld);
              raycastResult.hitPointWorld.vsub(chassis.position, relpos);
              chassis.getVelocityAtWorldPoint(relpos, chassis_velocity_at_contactPoint);
              var projVel = raycastResult.hitNormalWorld.dot( chassis_velocity_at_contactPoint );
              if (project >= -0.1) {
                  this.suspensionRelativeVelocity = 0.0;
                  this.clippedInvContactDotSuspension = 1.0 / 0.1;
              } else {
                  var inv = -1 / project;
                  this.suspensionRelativeVelocity = projVel * inv;
                  this.clippedInvContactDotSuspension = inv;
              }

          } else {
              // Not in contact : position wheel in a nice (rest length) position
              raycastResult.suspensionLength = this.suspensionRestLength;
              this.suspensionRelativeVelocity = 0.0;
              raycastResult.directionWorld.scale(-1, raycastResult.hitNormalWorld);
              this.clippedInvContactDotSuspension = 1.0;
          }
      };
      },{"../collision/RaycastResult":11,"../math/Transform":30,"../math/Vec3":31,"../utils/Utils":54}],38:[function(_dereq_,module,exports){
      module.exports = Box;

      var Shape = _dereq_('./Shape');
      var Vec3 = _dereq_('../math/Vec3');
      var ConvexPolyhedron = _dereq_('./ConvexPolyhedron');

      /**
       * A 3d box shape.
       * @class Box
       * @constructor
       * @param {Vec3} halfExtents
       * @author schteppe
       * @extends Shape
       */
      function Box(halfExtents){
          Shape.call(this, {
              type: Shape.types.BOX
          });

          /**
           * @property halfExtents
           * @type {Vec3}
           */
          this.halfExtents = halfExtents;

          /**
           * Used by the contact generator to make contacts with other convex polyhedra for example
           * @property convexPolyhedronRepresentation
           * @type {ConvexPolyhedron}
           */
          this.convexPolyhedronRepresentation = null;

          this.updateConvexPolyhedronRepresentation();
          this.updateBoundingSphereRadius();
      }
      Box.prototype = new Shape();
      Box.prototype.constructor = Box;

      /**
       * Updates the local convex polyhedron representation used for some collisions.
       * @method updateConvexPolyhedronRepresentation
       */
      Box.prototype.updateConvexPolyhedronRepresentation = function(){
          var sx = this.halfExtents.x;
          var sy = this.halfExtents.y;
          var sz = this.halfExtents.z;
          var V = Vec3;

          var vertices = [
              new V(-sx,-sy,-sz),
              new V( sx,-sy,-sz),
              new V( sx, sy,-sz),
              new V(-sx, sy,-sz),
              new V(-sx,-sy, sz),
              new V( sx,-sy, sz),
              new V( sx, sy, sz),
              new V(-sx, sy, sz)
          ];

          var indices = [
              [3,2,1,0], // -z
              [4,5,6,7], // +z
              [5,4,0,1], // -y
              [2,3,7,6], // +y
              [0,4,7,3], // -x
              [1,2,6,5], // +x
          ];

          [
              new V(0, 0, 1),
              new V(0, 1, 0),
              new V(1, 0, 0)
          ];

          var h = new ConvexPolyhedron(vertices, indices);
          this.convexPolyhedronRepresentation = h;
          h.material = this.material;
      };

      /**
       * @method calculateLocalInertia
       * @param  {Number} mass
       * @param  {Vec3} target
       * @return {Vec3}
       */
      Box.prototype.calculateLocalInertia = function(mass,target){
          target = target || new Vec3();
          Box.calculateInertia(this.halfExtents, mass, target);
          return target;
      };

      Box.calculateInertia = function(halfExtents,mass,target){
          var e = halfExtents;
          if (e.isZero()) {
              target.x = 2.0 / 12.0 * mass;
              target.y = 2.0 / 12.0 * mass;
              target.z = 2.0 / 12.0 * mass;
          }else {
              target.x = 1.0 / 12.0 * mass * (   2*e.y*2*e.y + 2*e.z*2*e.z );
              target.y = 1.0 / 12.0 * mass * (   2*e.x*2*e.x + 2*e.z*2*e.z );
              target.z = 1.0 / 12.0 * mass * (   2*e.y*2*e.y + 2*e.x*2*e.x );
          }
      };

      /**
       * Get the box 6 side normals
       * @method getSideNormals
       * @param {array}      sixTargetVectors An array of 6 vectors, to store the resulting side normals in.
       * @param {Quaternion} quat             Orientation to apply to the normal vectors. If not provided, the vectors will be in respect to the local frame.
       * @return {array}
       */
      Box.prototype.getSideNormals = function(sixTargetVectors,quat){
          var sides = sixTargetVectors;
          var ex = this.halfExtents;
          sides[0].set(  ex.x,     0,     0);
          sides[1].set(     0,  ex.y,     0);
          sides[2].set(     0,     0,  ex.z);
          sides[3].set( -ex.x,     0,     0);
          sides[4].set(     0, -ex.y,     0);
          sides[5].set(     0,     0, -ex.z);

          if(quat!==undefined){
              for(var i=0; i!==sides.length; i++){
                  quat.vmult(sides[i],sides[i]);
              }
          }

          return sides;
      };

      Box.prototype.volume = function(){
          return 8.0 * this.halfExtents.x * this.halfExtents.y * this.halfExtents.z;
      };

      Box.prototype.updateBoundingSphereRadius = function(){
          this.boundingSphereRadius = this.halfExtents.norm();
      };

      var worldCornerTempPos = new Vec3();
      new Vec3();
      Box.prototype.forEachWorldCorner = function(pos,quat,callback){

          var e = this.halfExtents;
          var corners = [[  e.x,  e.y,  e.z],
                         [ -e.x,  e.y,  e.z],
                         [ -e.x, -e.y,  e.z],
                         [ -e.x, -e.y, -e.z],
                         [  e.x, -e.y, -e.z],
                         [  e.x,  e.y, -e.z],
                         [ -e.x,  e.y, -e.z],
                         [  e.x, -e.y,  e.z]];
          for(var i=0; i<corners.length; i++){
              worldCornerTempPos.set(corners[i][0],corners[i][1],corners[i][2]);
              quat.vmult(worldCornerTempPos,worldCornerTempPos);
              pos.vadd(worldCornerTempPos,worldCornerTempPos);
              callback(worldCornerTempPos.x,
                       worldCornerTempPos.y,
                       worldCornerTempPos.z);
          }
      };

      var worldCornersTemp = [
          new Vec3(),
          new Vec3(),
          new Vec3(),
          new Vec3(),
          new Vec3(),
          new Vec3(),
          new Vec3(),
          new Vec3()
      ];
      Box.prototype.calculateWorldAABB = function(pos,quat,min,max){

          var e = this.halfExtents;
          worldCornersTemp[0].set(e.x, e.y, e.z);
          worldCornersTemp[1].set(-e.x,  e.y, e.z);
          worldCornersTemp[2].set(-e.x, -e.y, e.z);
          worldCornersTemp[3].set(-e.x, -e.y, -e.z);
          worldCornersTemp[4].set(e.x, -e.y, -e.z);
          worldCornersTemp[5].set(e.x,  e.y, -e.z);
          worldCornersTemp[6].set(-e.x,  e.y, -e.z);
          worldCornersTemp[7].set(e.x, -e.y,  e.z);

          var wc = worldCornersTemp[0];
          quat.vmult(wc, wc);
          pos.vadd(wc, wc);
          max.copy(wc);
          min.copy(wc);
          for(var i=1; i<8; i++){
              var wc = worldCornersTemp[i];
              quat.vmult(wc, wc);
              pos.vadd(wc, wc);
              var x = wc.x;
              var y = wc.y;
              var z = wc.z;
              if(x > max.x){
                  max.x = x;
              }
              if(y > max.y){
                  max.y = y;
              }
              if(z > max.z){
                  max.z = z;
              }

              if(x < min.x){
                  min.x = x;
              }
              if(y < min.y){
                  min.y = y;
              }
              if(z < min.z){
                  min.z = z;
              }
          }

          // Get each axis max
          // min.set(Infinity,Infinity,Infinity);
          // max.set(-Infinity,-Infinity,-Infinity);
          // this.forEachWorldCorner(pos,quat,function(x,y,z){
          //     if(x > max.x){
          //         max.x = x;
          //     }
          //     if(y > max.y){
          //         max.y = y;
          //     }
          //     if(z > max.z){
          //         max.z = z;
          //     }

          //     if(x < min.x){
          //         min.x = x;
          //     }
          //     if(y < min.y){
          //         min.y = y;
          //     }
          //     if(z < min.z){
          //         min.z = z;
          //     }
          // });
      };

      },{"../math/Vec3":31,"./ConvexPolyhedron":39,"./Shape":44}],39:[function(_dereq_,module,exports){
      module.exports = ConvexPolyhedron;

      var Shape = _dereq_('./Shape');
      var Vec3 = _dereq_('../math/Vec3');
      _dereq_('../math/Quaternion');
      var Transform = _dereq_('../math/Transform');

      /**
       * A set of polygons describing a convex shape.
       * @class ConvexPolyhedron
       * @constructor
       * @extends Shape
       * @description The shape MUST be convex for the code to work properly. No polygons may be coplanar (contained
       * in the same 3D plane), instead these should be merged into one polygon.
       *
       * @param {array} points An array of Vec3's
       * @param {array} faces Array of integer arrays, describing which vertices that is included in each face.
       *
       * @author qiao / https://github.com/qiao (original author, see https://github.com/qiao/three.js/commit/85026f0c769e4000148a67d45a9e9b9c5108836f)
       * @author schteppe / https://github.com/schteppe
       * @see http://www.altdevblogaday.com/2011/05/13/contact-generation-between-3d-convex-meshes/
       * @see http://bullet.googlecode.com/svn/trunk/src/BulletCollision/NarrowPhaseCollision/btPolyhedralContactClipping.cpp
       *
       * @todo Move the clipping functions to ContactGenerator?
       * @todo Automatically merge coplanar polygons in constructor.
       */
      function ConvexPolyhedron(points, faces, uniqueAxes) {
          Shape.call(this, {
              type: Shape.types.CONVEXPOLYHEDRON
          });

          /**
           * Array of Vec3
           * @property vertices
           * @type {Array}
           */
          this.vertices = points||[];

          this.worldVertices = []; // World transformed version of .vertices
          this.worldVerticesNeedsUpdate = true;

          /**
           * Array of integer arrays, indicating which vertices each face consists of
           * @property faces
           * @type {Array}
           */
          this.faces = faces||[];

          /**
           * Array of Vec3
           * @property faceNormals
           * @type {Array}
           */
          this.faceNormals = [];
          this.computeNormals();

          this.worldFaceNormalsNeedsUpdate = true;
          this.worldFaceNormals = []; // World transformed version of .faceNormals

          /**
           * Array of Vec3
           * @property uniqueEdges
           * @type {Array}
           */
          this.uniqueEdges = [];

          /**
           * If given, these locally defined, normalized axes are the only ones being checked when doing separating axis check.
           * @property {Array} uniqueAxes
           */
          this.uniqueAxes = uniqueAxes ? uniqueAxes.slice() : null;

          this.computeEdges();
          this.updateBoundingSphereRadius();
      }
      ConvexPolyhedron.prototype = new Shape();
      ConvexPolyhedron.prototype.constructor = ConvexPolyhedron;

      var computeEdges_tmpEdge = new Vec3();
      /**
       * Computes uniqueEdges
       * @method computeEdges
       */
      ConvexPolyhedron.prototype.computeEdges = function(){
          var faces = this.faces;
          var vertices = this.vertices;
          vertices.length;
          var edges = this.uniqueEdges;

          edges.length = 0;

          var edge = computeEdges_tmpEdge;

          for(var i=0; i !== faces.length; i++){
              var face = faces[i];
              var numVertices = face.length;
              for(var j = 0; j !== numVertices; j++){
                  var k = ( j+1 ) % numVertices;
                  vertices[face[j]].vsub(vertices[face[k]], edge);
                  edge.normalize();
                  var found = false;
                  for(var p=0; p !== edges.length; p++){
                      if (edges[p].almostEquals(edge) || edges[p].almostEquals(edge)){
                          found = true;
                          break;
                      }
                  }

                  if (!found){
                      edges.push(edge.clone());
                  }
              }
          }
      };

      /**
       * Compute the normals of the faces. Will reuse existing Vec3 objects in the .faceNormals array if they exist.
       * @method computeNormals
       */
      ConvexPolyhedron.prototype.computeNormals = function(){
          this.faceNormals.length = this.faces.length;

          // Generate normals
          for(var i=0; i<this.faces.length; i++){

              // Check so all vertices exists for this face
              for(var j=0; j<this.faces[i].length; j++){
                  if(!this.vertices[this.faces[i][j]]){
                      throw new Error("Vertex "+this.faces[i][j]+" not found!");
                  }
              }

              var n = this.faceNormals[i] || new Vec3();
              this.getFaceNormal(i,n);
              n.negate(n);
              this.faceNormals[i] = n;
              // var vertex = this.vertices[this.faces[i][0]];
              // if(n.dot(vertex) < 0){
              //     console.error(".faceNormals[" + i + "] = Vec3("+n.toString()+") looks like it points into the shape? The vertices follow. Make sure they are ordered CCW around the normal, using the right hand rule.");
              //     for(var j=0; j<this.faces[i].length; j++){
              //         console.warn(".vertices["+this.faces[i][j]+"] = Vec3("+this.vertices[this.faces[i][j]].toString()+")");
              //     }
              // }
          }
      };

      /**
       * Get face normal given 3 vertices
       * @static
       * @method getFaceNormal
       * @param {Vec3} va
       * @param {Vec3} vb
       * @param {Vec3} vc
       * @param {Vec3} target
       */
      var cb = new Vec3();
      var ab = new Vec3();
      ConvexPolyhedron.computeNormal = function ( va, vb, vc, target ) {
          vb.vsub(va,ab);
          vc.vsub(vb,cb);
          cb.cross(ab,target);
          if ( !target.isZero() ) {
              target.normalize();
          }
      };

      /**
       * Compute the normal of a face from its vertices
       * @method getFaceNormal
       * @param  {Number} i
       * @param  {Vec3} target
       */
      ConvexPolyhedron.prototype.getFaceNormal = function(i,target){
          var f = this.faces[i];
          var va = this.vertices[f[0]];
          var vb = this.vertices[f[1]];
          var vc = this.vertices[f[2]];
          return ConvexPolyhedron.computeNormal(va,vb,vc,target);
      };

      /**
       * @method clipAgainstHull
       * @param {Vec3} posA
       * @param {Quaternion} quatA
       * @param {ConvexPolyhedron} hullB
       * @param {Vec3} posB
       * @param {Quaternion} quatB
       * @param {Vec3} separatingNormal
       * @param {Number} minDist Clamp distance
       * @param {Number} maxDist
       * @param {array} result The an array of contact point objects, see clipFaceAgainstHull
       * @see http://bullet.googlecode.com/svn/trunk/src/BulletCollision/NarrowPhaseCollision/btPolyhedralContactClipping.cpp
       */
      var cah_WorldNormal = new Vec3();
      ConvexPolyhedron.prototype.clipAgainstHull = function(posA,quatA,hullB,posB,quatB,separatingNormal,minDist,maxDist,result){
          var WorldNormal = cah_WorldNormal;
          var closestFaceB = -1;
          var dmax = -Number.MAX_VALUE;
          for(var face=0; face < hullB.faces.length; face++){
              WorldNormal.copy(hullB.faceNormals[face]);
              quatB.vmult(WorldNormal,WorldNormal);
              //posB.vadd(WorldNormal,WorldNormal);
              var d = WorldNormal.dot(separatingNormal);
              if (d > dmax){
                  dmax = d;
                  closestFaceB = face;
              }
          }
          var worldVertsB1 = [];
          var polyB = hullB.faces[closestFaceB];
          var numVertices = polyB.length;
          for(var e0=0; e0<numVertices; e0++){
              var b = hullB.vertices[polyB[e0]];
              var worldb = new Vec3();
              worldb.copy(b);
              quatB.vmult(worldb,worldb);
              posB.vadd(worldb,worldb);
              worldVertsB1.push(worldb);
          }

          if (closestFaceB>=0){
              this.clipFaceAgainstHull(separatingNormal,
                                       posA,
                                       quatA,
                                       worldVertsB1,
                                       minDist,
                                       maxDist,
                                       result);
          }
      };

      /**
       * Find the separating axis between this hull and another
       * @method findSeparatingAxis
       * @param {ConvexPolyhedron} hullB
       * @param {Vec3} posA
       * @param {Quaternion} quatA
       * @param {Vec3} posB
       * @param {Quaternion} quatB
       * @param {Vec3} target The target vector to save the axis in
       * @return {bool} Returns false if a separation is found, else true
       */
      var fsa_faceANormalWS3 = new Vec3(),
          fsa_Worldnormal1 = new Vec3(),
          fsa_deltaC = new Vec3(),
          fsa_worldEdge0 = new Vec3(),
          fsa_worldEdge1 = new Vec3(),
          fsa_Cross = new Vec3();
      ConvexPolyhedron.prototype.findSeparatingAxis = function(hullB,posA,quatA,posB,quatB,target, faceListA, faceListB){
          var faceANormalWS3 = fsa_faceANormalWS3,
              Worldnormal1 = fsa_Worldnormal1,
              deltaC = fsa_deltaC,
              worldEdge0 = fsa_worldEdge0,
              worldEdge1 = fsa_worldEdge1,
              Cross = fsa_Cross;

          var dmin = Number.MAX_VALUE;
          var hullA = this;

          if(!hullA.uniqueAxes){

              var numFacesA = faceListA ? faceListA.length : hullA.faces.length;

              // Test face normals from hullA
              for(var i=0; i<numFacesA; i++){
                  var fi = faceListA ? faceListA[i] : i;

                  // Get world face normal
                  faceANormalWS3.copy(hullA.faceNormals[fi]);
                  quatA.vmult(faceANormalWS3,faceANormalWS3);

                  var d = hullA.testSepAxis(faceANormalWS3, hullB, posA, quatA, posB, quatB);
                  if(d===false){
                      return false;
                  }

                  if(d<dmin){
                      dmin = d;
                      target.copy(faceANormalWS3);
                  }
              }

          } else {

              // Test unique axes
              for(var i = 0; i !== hullA.uniqueAxes.length; i++){

                  // Get world axis
                  quatA.vmult(hullA.uniqueAxes[i],faceANormalWS3);

                  var d = hullA.testSepAxis(faceANormalWS3, hullB, posA, quatA, posB, quatB);
                  if(d===false){
                      return false;
                  }

                  if(d<dmin){
                      dmin = d;
                      target.copy(faceANormalWS3);
                  }
              }
          }

          if(!hullB.uniqueAxes){

              // Test face normals from hullB
              var numFacesB = faceListB ? faceListB.length : hullB.faces.length;
              for(var i=0;i<numFacesB;i++){

                  var fi = faceListB ? faceListB[i] : i;

                  Worldnormal1.copy(hullB.faceNormals[fi]);
                  quatB.vmult(Worldnormal1,Worldnormal1);
                  var d = hullA.testSepAxis(Worldnormal1, hullB,posA,quatA,posB,quatB);
                  if(d===false){
                      return false;
                  }

                  if(d<dmin){
                      dmin = d;
                      target.copy(Worldnormal1);
                  }
              }
          } else {

              // Test unique axes in B
              for(var i = 0; i !== hullB.uniqueAxes.length; i++){
                  quatB.vmult(hullB.uniqueAxes[i],Worldnormal1);
                  var d = hullA.testSepAxis(Worldnormal1, hullB,posA,quatA,posB,quatB);
                  if(d===false){
                      return false;
                  }

                  if(d<dmin){
                      dmin = d;
                      target.copy(Worldnormal1);
                  }
              }
          }

          // Test edges
          for(var e0=0; e0 !== hullA.uniqueEdges.length; e0++){

              // Get world edge
              quatA.vmult(hullA.uniqueEdges[e0],worldEdge0);

              for(var e1=0; e1 !== hullB.uniqueEdges.length; e1++){

                  // Get world edge 2
                  quatB.vmult(hullB.uniqueEdges[e1], worldEdge1);
                  worldEdge0.cross(worldEdge1,Cross);

                  if(!Cross.almostZero()){
                      Cross.normalize();
                      var dist = hullA.testSepAxis(Cross, hullB, posA, quatA, posB, quatB);
                      if(dist === false){
                          return false;
                      }
                      if(dist < dmin){
                          dmin = dist;
                          target.copy(Cross);
                      }
                  }
              }
          }

          posB.vsub(posA,deltaC);
          if((deltaC.dot(target))>0.0){
              target.negate(target);
          }

          return true;
      };

      var maxminA=[], maxminB=[];

      /**
       * Test separating axis against two hulls. Both hulls are projected onto the axis and the overlap size is returned if there is one.
       * @method testSepAxis
       * @param {Vec3} axis
       * @param {ConvexPolyhedron} hullB
       * @param {Vec3} posA
       * @param {Quaternion} quatA
       * @param {Vec3} posB
       * @param {Quaternion} quatB
       * @return {number} The overlap depth, or FALSE if no penetration.
       */
      ConvexPolyhedron.prototype.testSepAxis = function(axis, hullB, posA, quatA, posB, quatB){
          var hullA=this;
          ConvexPolyhedron.project(hullA, axis, posA, quatA, maxminA);
          ConvexPolyhedron.project(hullB, axis, posB, quatB, maxminB);
          var maxA = maxminA[0];
          var minA = maxminA[1];
          var maxB = maxminB[0];
          var minB = maxminB[1];
          if(maxA<minB || maxB<minA){
              return false; // Separated
          }
          var d0 = maxA - minB;
          var d1 = maxB - minA;
          var depth = d0<d1 ? d0:d1;
          return depth;
      };

      var cli_aabbmin = new Vec3(),
          cli_aabbmax = new Vec3();

      /**
       * @method calculateLocalInertia
       * @param  {Number} mass
       * @param  {Vec3} target
       */
      ConvexPolyhedron.prototype.calculateLocalInertia = function(mass,target){
          // Approximate with box inertia
          // Exact inertia calculation is overkill, but see http://geometrictools.com/Documentation/PolyhedralMassProperties.pdf for the correct way to do it
          this.computeLocalAABB(cli_aabbmin,cli_aabbmax);
          var x = cli_aabbmax.x - cli_aabbmin.x,
              y = cli_aabbmax.y - cli_aabbmin.y,
              z = cli_aabbmax.z - cli_aabbmin.z;
          target.x = 1.0 / 12.0 * mass * ( 2*y*2*y + 2*z*2*z );
          target.y = 1.0 / 12.0 * mass * ( 2*x*2*x + 2*z*2*z );
          target.z = 1.0 / 12.0 * mass * ( 2*y*2*y + 2*x*2*x );
      };

      /**
       * @method getPlaneConstantOfFace
       * @param  {Number} face_i Index of the face
       * @return {Number}
       */
      ConvexPolyhedron.prototype.getPlaneConstantOfFace = function(face_i){
          var f = this.faces[face_i];
          var n = this.faceNormals[face_i];
          var v = this.vertices[f[0]];
          var c = -n.dot(v);
          return c;
      };

      /**
       * Clip a face against a hull.
       * @method clipFaceAgainstHull
       * @param {Vec3} separatingNormal
       * @param {Vec3} posA
       * @param {Quaternion} quatA
       * @param {Array} worldVertsB1 An array of Vec3 with vertices in the world frame.
       * @param {Number} minDist Distance clamping
       * @param {Number} maxDist
       * @param Array result Array to store resulting contact points in. Will be objects with properties: point, depth, normal. These are represented in world coordinates.
       */
      var cfah_faceANormalWS = new Vec3(),
          cfah_edge0 = new Vec3(),
          cfah_WorldEdge0 = new Vec3(),
          cfah_worldPlaneAnormal1 = new Vec3(),
          cfah_planeNormalWS1 = new Vec3(),
          cfah_worldA1 = new Vec3(),
          cfah_localPlaneNormal = new Vec3(),
          cfah_planeNormalWS = new Vec3();
      ConvexPolyhedron.prototype.clipFaceAgainstHull = function(separatingNormal, posA, quatA, worldVertsB1, minDist, maxDist,result){
          var faceANormalWS = cfah_faceANormalWS,
              edge0 = cfah_edge0,
              WorldEdge0 = cfah_WorldEdge0,
              worldPlaneAnormal1 = cfah_worldPlaneAnormal1,
              planeNormalWS1 = cfah_planeNormalWS1,
              worldA1 = cfah_worldA1,
              localPlaneNormal = cfah_localPlaneNormal,
              planeNormalWS = cfah_planeNormalWS;

          var hullA = this;
          var worldVertsB2 = [];
          var pVtxIn = worldVertsB1;
          var pVtxOut = worldVertsB2;
          // Find the face with normal closest to the separating axis
          var closestFaceA = -1;
          var dmin = Number.MAX_VALUE;
          for(var face=0; face<hullA.faces.length; face++){
              faceANormalWS.copy(hullA.faceNormals[face]);
              quatA.vmult(faceANormalWS,faceANormalWS);
              //posA.vadd(faceANormalWS,faceANormalWS);
              var d = faceANormalWS.dot(separatingNormal);
              if (d < dmin){
                  dmin = d;
                  closestFaceA = face;
              }
          }
          if (closestFaceA < 0){
              // console.log("--- did not find any closest face... ---");
              return;
          }
          //console.log("closest A: ",closestFaceA);
          // Get the face and construct connected faces
          var polyA = hullA.faces[closestFaceA];
          polyA.connectedFaces = [];
          for(var i=0; i<hullA.faces.length; i++){
              for(var j=0; j<hullA.faces[i].length; j++){
                  if(polyA.indexOf(hullA.faces[i][j])!==-1 /* Sharing a vertex*/ && i!==closestFaceA /* Not the one we are looking for connections from */ && polyA.connectedFaces.indexOf(i)===-1 /* Not already added */ ){
                      polyA.connectedFaces.push(i);
                  }
              }
          }
          // Clip the polygon to the back of the planes of all faces of hull A, that are adjacent to the witness face
          pVtxIn.length;
          var numVerticesA = polyA.length;
          for(var e0=0; e0<numVerticesA; e0++){
              var a = hullA.vertices[polyA[e0]];
              var b = hullA.vertices[polyA[(e0+1)%numVerticesA]];
              a.vsub(b,edge0);
              WorldEdge0.copy(edge0);
              quatA.vmult(WorldEdge0,WorldEdge0);
              posA.vadd(WorldEdge0,WorldEdge0);
              worldPlaneAnormal1.copy(this.faceNormals[closestFaceA]);//transA.getBasis()* btVector3(polyA.m_plane[0],polyA.m_plane[1],polyA.m_plane[2]);
              quatA.vmult(worldPlaneAnormal1,worldPlaneAnormal1);
              posA.vadd(worldPlaneAnormal1,worldPlaneAnormal1);
              WorldEdge0.cross(worldPlaneAnormal1,planeNormalWS1);
              planeNormalWS1.negate(planeNormalWS1);
              worldA1.copy(a);
              quatA.vmult(worldA1,worldA1);
              posA.vadd(worldA1,worldA1);
              -worldA1.dot(planeNormalWS1);
              var planeEqWS;
              {
                  var otherFace = polyA.connectedFaces[e0];
                  localPlaneNormal.copy(this.faceNormals[otherFace]);
                  var localPlaneEq = this.getPlaneConstantOfFace(otherFace);

                  planeNormalWS.copy(localPlaneNormal);
                  quatA.vmult(planeNormalWS,planeNormalWS);
                  //posA.vadd(planeNormalWS,planeNormalWS);
                  var planeEqWS = localPlaneEq - planeNormalWS.dot(posA);
              }

              // Clip face against our constructed plane
              this.clipFaceAgainstPlane(pVtxIn, pVtxOut, planeNormalWS, planeEqWS);

              // Throw away all clipped points, but save the reamining until next clip
              while(pVtxIn.length){
                  pVtxIn.shift();
              }
              while(pVtxOut.length){
                  pVtxIn.push(pVtxOut.shift());
              }
          }

          //console.log("Resulting points after clip:",pVtxIn);

          // only keep contact points that are behind the witness face
          localPlaneNormal.copy(this.faceNormals[closestFaceA]);

          var localPlaneEq = this.getPlaneConstantOfFace(closestFaceA);
          planeNormalWS.copy(localPlaneNormal);
          quatA.vmult(planeNormalWS,planeNormalWS);

          var planeEqWS = localPlaneEq - planeNormalWS.dot(posA);
          for (var i=0; i<pVtxIn.length; i++){
              var depth = planeNormalWS.dot(pVtxIn[i]) + planeEqWS; //???
              /*console.log("depth calc from normal=",planeNormalWS.toString()," and constant "+planeEqWS+" and vertex ",pVtxIn[i].toString()," gives "+depth);*/
              if (depth <=minDist){
                  // console.log("clamped: depth="+depth+" to minDist="+(minDist+""));
                  depth = minDist;
              }

              if (depth <=maxDist){
                  var point = pVtxIn[i];
                  if(depth<=0){
                      /*console.log("Got contact point ",point.toString(),
                        ", depth=",depth,
                        "contact normal=",separatingNormal.toString(),
                        "plane",planeNormalWS.toString(),
                        "planeConstant",planeEqWS);*/
                      var p = {
                          point:point,
                          normal:planeNormalWS,
                          depth: depth,
                      };
                      result.push(p);
                  }
              }
          }
      };

      /**
       * Clip a face in a hull against the back of a plane.
       * @method clipFaceAgainstPlane
       * @param {Array} inVertices
       * @param {Array} outVertices
       * @param {Vec3} planeNormal
       * @param {Number} planeConstant The constant in the mathematical plane equation
       */
      ConvexPolyhedron.prototype.clipFaceAgainstPlane = function(inVertices,outVertices, planeNormal, planeConstant){
          var n_dot_first, n_dot_last;
          var numVerts = inVertices.length;

          if(numVerts < 2){
              return outVertices;
          }

          var firstVertex = inVertices[inVertices.length-1],
              lastVertex =   inVertices[0];

          n_dot_first = planeNormal.dot(firstVertex) + planeConstant;

          for(var vi = 0; vi < numVerts; vi++){
              lastVertex = inVertices[vi];
              n_dot_last = planeNormal.dot(lastVertex) + planeConstant;
              if(n_dot_first < 0){
                  if(n_dot_last < 0){
                      // Start < 0, end < 0, so output lastVertex
                      var newv = new Vec3();
                      newv.copy(lastVertex);
                      outVertices.push(newv);
                  } else {
                      // Start < 0, end >= 0, so output intersection
                      var newv = new Vec3();
                      firstVertex.lerp(lastVertex,
                                       n_dot_first / (n_dot_first - n_dot_last),
                                       newv);
                      outVertices.push(newv);
                  }
              } else {
                  if(n_dot_last<0){
                      // Start >= 0, end < 0 so output intersection and end
                      var newv = new Vec3();
                      firstVertex.lerp(lastVertex,
                                       n_dot_first / (n_dot_first - n_dot_last),
                                       newv);
                      outVertices.push(newv);
                      outVertices.push(lastVertex);
                  }
              }
              firstVertex = lastVertex;
              n_dot_first = n_dot_last;
          }
          return outVertices;
      };

      // Updates .worldVertices and sets .worldVerticesNeedsUpdate to false.
      ConvexPolyhedron.prototype.computeWorldVertices = function(position,quat){
          var N = this.vertices.length;
          while(this.worldVertices.length < N){
              this.worldVertices.push( new Vec3() );
          }

          var verts = this.vertices,
              worldVerts = this.worldVertices;
          for(var i=0; i!==N; i++){
              quat.vmult( verts[i] , worldVerts[i] );
              position.vadd( worldVerts[i] , worldVerts[i] );
          }

          this.worldVerticesNeedsUpdate = false;
      };

      new Vec3();
      ConvexPolyhedron.prototype.computeLocalAABB = function(aabbmin,aabbmax){
          var n = this.vertices.length,
              vertices = this.vertices;


          aabbmin.set(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
          aabbmax.set(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);

          for(var i=0; i<n; i++){
              var v = vertices[i];
              if     (v.x < aabbmin.x){
                  aabbmin.x = v.x;
              } else if(v.x > aabbmax.x){
                  aabbmax.x = v.x;
              }
              if     (v.y < aabbmin.y){
                  aabbmin.y = v.y;
              } else if(v.y > aabbmax.y){
                  aabbmax.y = v.y;
              }
              if     (v.z < aabbmin.z){
                  aabbmin.z = v.z;
              } else if(v.z > aabbmax.z){
                  aabbmax.z = v.z;
              }
          }
      };

      /**
       * Updates .worldVertices and sets .worldVerticesNeedsUpdate to false.
       * @method computeWorldFaceNormals
       * @param  {Quaternion} quat
       */
      ConvexPolyhedron.prototype.computeWorldFaceNormals = function(quat){
          var N = this.faceNormals.length;
          while(this.worldFaceNormals.length < N){
              this.worldFaceNormals.push( new Vec3() );
          }

          var normals = this.faceNormals,
              worldNormals = this.worldFaceNormals;
          for(var i=0; i!==N; i++){
              quat.vmult( normals[i] , worldNormals[i] );
          }

          this.worldFaceNormalsNeedsUpdate = false;
      };

      /**
       * @method updateBoundingSphereRadius
       */
      ConvexPolyhedron.prototype.updateBoundingSphereRadius = function(){
          // Assume points are distributed with local (0,0,0) as center
          var max2 = 0;
          var verts = this.vertices;
          for(var i=0, N=verts.length; i!==N; i++) {
              var norm2 = verts[i].norm2();
              if(norm2 > max2){
                  max2 = norm2;
              }
          }
          this.boundingSphereRadius = Math.sqrt(max2);
      };

      var tempWorldVertex = new Vec3();

      /**
       * @method calculateWorldAABB
       * @param {Vec3}        pos
       * @param {Quaternion}  quat
       * @param {Vec3}        min
       * @param {Vec3}        max
       */
      ConvexPolyhedron.prototype.calculateWorldAABB = function(pos,quat,min,max){
          var n = this.vertices.length, verts = this.vertices;
          var minx,miny,minz,maxx,maxy,maxz;
          for(var i=0; i<n; i++){
              tempWorldVertex.copy(verts[i]);
              quat.vmult(tempWorldVertex,tempWorldVertex);
              pos.vadd(tempWorldVertex,tempWorldVertex);
              var v = tempWorldVertex;
              if     (v.x < minx || minx===undefined){
                  minx = v.x;
              } 
              
              if(v.x > maxx || maxx===undefined){
                  maxx = v.x;
              }

              if     (v.y < miny || miny===undefined){
                  miny = v.y;
              } 
              
              if(v.y > maxy || maxy===undefined){
                  maxy = v.y;
              }

              if     (v.z < minz || minz===undefined){
                  minz = v.z;
              }  
              
              if(v.z > maxz || maxz===undefined){
                  maxz = v.z;
              }
          }
          min.set(minx,miny,minz);
          max.set(maxx,maxy,maxz);
      };

      /**
       * Get approximate convex volume
       * @method volume
       * @return {Number}
       */
      ConvexPolyhedron.prototype.volume = function(){
          return 4.0 * Math.PI * this.boundingSphereRadius / 3.0;
      };

      /**
       * Get an average of all the vertices positions
       * @method getAveragePointLocal
       * @param  {Vec3} target
       * @return {Vec3}
       */
      ConvexPolyhedron.prototype.getAveragePointLocal = function(target){
          target = target || new Vec3();
          var n = this.vertices.length,
              verts = this.vertices;
          for(var i=0; i<n; i++){
              target.vadd(verts[i],target);
          }
          target.mult(1/n,target);
          return target;
      };

      /**
       * Transform all local points. Will change the .vertices
       * @method transformAllPoints
       * @param  {Vec3} offset
       * @param  {Quaternion} quat
       */
      ConvexPolyhedron.prototype.transformAllPoints = function(offset,quat){
          var n = this.vertices.length,
              verts = this.vertices;

          // Apply rotation
          if(quat){
              // Rotate vertices
              for(var i=0; i<n; i++){
                  var v = verts[i];
                  quat.vmult(v,v);
              }
              // Rotate face normals
              for(var i=0; i<this.faceNormals.length; i++){
                  var v = this.faceNormals[i];
                  quat.vmult(v,v);
              }
              /*
              // Rotate edges
              for(var i=0; i<this.uniqueEdges.length; i++){
                  var v = this.uniqueEdges[i];
                  quat.vmult(v,v);
              }*/
          }

          // Apply offset
          if(offset){
              for(var i=0; i<n; i++){
                  var v = verts[i];
                  v.vadd(offset,v);
              }
          }
      };

      /**
       * Checks whether p is inside the polyhedra. Must be in local coords. The point lies outside of the convex hull of the other points if and only if the direction of all the vectors from it to those other points are on less than one half of a sphere around it.
       * @method pointIsInside
       * @param  {Vec3} p      A point given in local coordinates
       * @return {Boolean}
       */
      var ConvexPolyhedron_pointIsInside = new Vec3();
      var ConvexPolyhedron_vToP = new Vec3();
      var ConvexPolyhedron_vToPointInside = new Vec3();
      ConvexPolyhedron.prototype.pointIsInside = function(p){
          var n = this.vertices.length,
              verts = this.vertices,
              faces = this.faces,
              normals = this.faceNormals;
          var positiveResult = null;
          var N = this.faces.length;
          var pointInside = ConvexPolyhedron_pointIsInside;
          this.getAveragePointLocal(pointInside);
          for(var i=0; i<N; i++){
              this.faces[i].length;
              var n = normals[i];
              var v = verts[faces[i][0]]; // We only need one point in the face

              // This dot product determines which side of the edge the point is
              var vToP = ConvexPolyhedron_vToP;
              p.vsub(v,vToP);
              var r1 = n.dot(vToP);

              var vToPointInside = ConvexPolyhedron_vToPointInside;
              pointInside.vsub(v,vToPointInside);
              var r2 = n.dot(vToPointInside);

              if((r1<0 && r2>0) || (r1>0 && r2<0)){
                  return false; // Encountered some other sign. Exit.
              }
          }

          // If we got here, all dot products were of the same sign.
          return positiveResult ? 1 : -1;
      };

      /**
       * Get max and min dot product of a convex hull at position (pos,quat) projected onto an axis. Results are saved in the array maxmin.
       * @static
       * @method project
       * @param {ConvexPolyhedron} hull
       * @param {Vec3} axis
       * @param {Vec3} pos
       * @param {Quaternion} quat
       * @param {array} result result[0] and result[1] will be set to maximum and minimum, respectively.
       */
      new Vec3();
      var project_localAxis = new Vec3();
      var project_localOrigin = new Vec3();
      ConvexPolyhedron.project = function(hull, axis, pos, quat, result){
          var n = hull.vertices.length,
              localAxis = project_localAxis,
              max = 0,
              min = 0,
              localOrigin = project_localOrigin,
              vs = hull.vertices;

          localOrigin.setZero();

          // Transform the axis to local
          Transform.vectorToLocalFrame(pos, quat, axis, localAxis);
          Transform.pointToLocalFrame(pos, quat, localOrigin, localOrigin);
          var add = localOrigin.dot(localAxis);

          min = max = vs[0].dot(localAxis);

          for(var i = 1; i < n; i++){
              var val = vs[i].dot(localAxis);

              if(val > max){
                  max = val;
              }

              if(val < min){
                  min = val;
              }
          }

          min -= add;
          max -= add;

          if(min > max){
              // Inconsistent - swap
              var temp = min;
              min = max;
              max = temp;
          }
          // Output
          result[0] = max;
          result[1] = min;
      };

      },{"../math/Quaternion":29,"../math/Transform":30,"../math/Vec3":31,"./Shape":44}],40:[function(_dereq_,module,exports){
      module.exports = Cylinder;

      _dereq_('./Shape');
      var Vec3 = _dereq_('../math/Vec3');
      _dereq_('../math/Quaternion');
      var ConvexPolyhedron = _dereq_('./ConvexPolyhedron');

      /**
       * @class Cylinder
       * @constructor
       * @extends ConvexPolyhedron
       * @author schteppe / https://github.com/schteppe
       * @param {Number} radiusTop
       * @param {Number} radiusBottom
       * @param {Number} height
       * @param {Number} numSegments The number of segments to build the cylinder out of
       */
      function Cylinder( radiusTop, radiusBottom, height , numSegments , isDirY) {
          if (isDirY) {
              var N = numSegments,
              cos = Math.cos,
              sin = Math.sin;
              var halfH = height / 2;
              var vertices = [];
              var indices = [];
              var tf = [0];
              var bf = [1];
              var axes = [];
              var theta = Math.PI * 2 / N;
              for (var i = 0; i < N; i++) {
                  vertices.push(new Vec3(radiusTop * cos(theta * i), halfH, radiusTop * sin(theta * i)));
                  vertices.push(new Vec3(radiusTop * cos(theta * i), -halfH, radiusTop * sin(theta * i)));
                  if (i < N - 1) {
                      indices.push([2 * i + 2, 2 * i + 3, 2 * i + 1, 2 * i]);
                      tf.push(2 * i + 2);
                      bf.push(2 * i + 3);
                  } else {
                      indices.push([0, 1, 2 * i + 1, 2 * i]);
                  }
                  if (N % 2 === 1 || i < N / 2) axes.push(new Vec3(cos(theta * (i + 0.5)), 0, sin(theta * (i + 0.5))));            
              }
              indices.push(bf);
              var temp = [];
              for (var i = 0; i < tf.length; i++) temp.push(tf[tf.length - i - 1]);    
              indices.push(temp);
              axes.push(new Vec3(0, 1, 0));
              ConvexPolyhedron.call(this, vertices, indices, axes);
              return;
          }
          var N = numSegments,
              verts = [],
              axes = [],
              faces = [],
              bottomface = [],
              topface = [],
              cos = Math.cos,
              sin = Math.sin;

          // First bottom point
          verts.push(new Vec3(radiusBottom*cos(0),
                                     radiusBottom*sin(0),
                                     -height*0.5));
          bottomface.push(0);

          // First top point
          verts.push(new Vec3(radiusTop*cos(0),
                                     radiusTop*sin(0),
                                     height*0.5));
          topface.push(1);

          for(var i=0; i<N; i++){
              var theta = 2*Math.PI/N * (i+1);
              var thetaN = 2*Math.PI/N * (i+0.5);
              if(i<N-1){
                  // Bottom
                  verts.push(new Vec3(radiusBottom*cos(theta),
                                             radiusBottom*sin(theta),
                                             -height*0.5));
                  bottomface.push(2*i+2);
                  // Top
                  verts.push(new Vec3(radiusTop*cos(theta),
                                             radiusTop*sin(theta),
                                             height*0.5));
                  topface.push(2*i+3);

                  // Face
                  faces.push([2*i+2, 2*i+3, 2*i+1,2*i]);
              } else {
                  faces.push([0,1, 2*i+1, 2*i]); // Connect
              }

              // Axis: we can cut off half of them if we have even number of segments
              if(N % 2 === 1 || i < N / 2){
                  axes.push(new Vec3(cos(thetaN), sin(thetaN), 0));
              }
          }
          faces.push(topface);
          axes.push(new Vec3(0,0,1));

          // Reorder bottom face
          var temp = [];
          for(var i=0; i<bottomface.length; i++){
              temp.push(bottomface[bottomface.length - i - 1]);
          }
          faces.push(temp);

          ConvexPolyhedron.call( this, verts, faces, axes );
      }

      Cylinder.prototype = new ConvexPolyhedron();

      },{"../math/Quaternion":29,"../math/Vec3":31,"./ConvexPolyhedron":39,"./Shape":44}],41:[function(_dereq_,module,exports){
      var Shape = _dereq_('./Shape');
      var ConvexPolyhedron = _dereq_('./ConvexPolyhedron');
      var Vec3 = _dereq_('../math/Vec3');
      var Utils = _dereq_('../utils/Utils');

      module.exports = Heightfield;

      /**
       * Heightfield shape class. Height data is given as an array. These data points are spread out evenly with a given distance.
       * @class Heightfield
       * @extends Shape
       * @constructor
       * @param {Array} data An array of Y values that will be used to construct the terrain.
       * @param {object} options
       * @param {Number} [options.minValue] Minimum value of the data points in the data array. Will be computed automatically if not given.
       * @param {Number} [options.maxValue] Maximum value.
       * @param {Number} [options.elementSize=0.1] World spacing between the data points in X direction.
       * @todo Should be possible to use along all axes, not just y
       * @todo should be possible to scale along all axes
       *
       * @example
       *     // Generate some height data (y-values).
       *     var data = [];
       *     for(var i = 0; i < 1000; i++){
       *         var y = 0.5 * Math.cos(0.2 * i);
       *         data.push(y);
       *     }
       *
       *     // Create the heightfield shape
       *     var heightfieldShape = new Heightfield(data, {
       *         elementSize: 1 // Distance between the data points in X and Y directions
       *     });
       *     var heightfieldBody = new Body();
       *     heightfieldBody.addShape(heightfieldShape);
       *     world.addBody(heightfieldBody);
       */
      function Heightfield(data, options){
          options = Utils.defaults(options, {
              maxValue : null,
              minValue : null,
              elementSize : 1
          });

          /**
           * An array of numbers, or height values, that are spread out along the x axis.
           * @property {array} data
           */
          this.data = data;

          /**
           * Max value of the data
           * @property {number} maxValue
           */
          this.maxValue = options.maxValue;

          /**
           * Max value of the data
           * @property {number} minValue
           */
          this.minValue = options.minValue;

          /**
           * The width of each element
           * @property {number} elementSize
           * @todo elementSizeX and Y
           */
          this.elementSize = options.elementSize;

          if(options.minValue === null){
              this.updateMinValue();
          }
          if(options.maxValue === null){
              this.updateMaxValue();
          }

          this.cacheEnabled = true;

          Shape.call(this, {
              type: Shape.types.HEIGHTFIELD
          });

          this.pillarConvex = new ConvexPolyhedron();
          this.pillarOffset = new Vec3();

          this.updateBoundingSphereRadius();

          // "i_j_isUpper" => { convex: ..., offset: ... }
          // for example:
          // _cachedPillars["0_2_1"]
          this._cachedPillars = {};
      }
      Heightfield.prototype = new Shape();

      /**
       * Call whenever you change the data array.
       * @method update
       */
      Heightfield.prototype.update = function(){
          this._cachedPillars = {};
      };

      /**
       * Update the .minValue property
       * @method updateMinValue
       */
      Heightfield.prototype.updateMinValue = function(){
          var data = this.data;
          var minValue = data[0][0];
          for(var i=0; i !== data.length; i++){
              for(var j=0; j !== data[i].length; j++){
                  var v = data[i][j];
                  if(v < minValue){
                      minValue = v;
                  }
              }
          }
          this.minValue = minValue;
      };

      /**
       * Update the .maxValue property
       * @method updateMaxValue
       */
      Heightfield.prototype.updateMaxValue = function(){
          var data = this.data;
          var maxValue = data[0][0];
          for(var i=0; i !== data.length; i++){
              for(var j=0; j !== data[i].length; j++){
                  var v = data[i][j];
                  if(v > maxValue){
                      maxValue = v;
                  }
              }
          }
          this.maxValue = maxValue;
      };

      /**
       * Set the height value at an index. Don't forget to update maxValue and minValue after you're done.
       * @method setHeightValueAtIndex
       * @param {integer} xi
       * @param {integer} yi
       * @param {number} value
       */
      Heightfield.prototype.setHeightValueAtIndex = function(xi, yi, value){
          var data = this.data;
          data[xi][yi] = value;

          // Invalidate cache
          this.clearCachedConvexTrianglePillar(xi, yi, false);
          if(xi > 0){
              this.clearCachedConvexTrianglePillar(xi - 1, yi, true);
              this.clearCachedConvexTrianglePillar(xi - 1, yi, false);
          }
          if(yi > 0){
              this.clearCachedConvexTrianglePillar(xi, yi - 1, true);
              this.clearCachedConvexTrianglePillar(xi, yi - 1, false);
          }
          if(yi > 0 && xi > 0){
              this.clearCachedConvexTrianglePillar(xi - 1, yi - 1, true);
          }
      };

      /**
       * Get max/min in a rectangle in the matrix data
       * @method getRectMinMax
       * @param  {integer} iMinX
       * @param  {integer} iMinY
       * @param  {integer} iMaxX
       * @param  {integer} iMaxY
       * @param  {array} [result] An array to store the results in.
       * @return {array} The result array, if it was passed in. Minimum will be at position 0 and max at 1.
       */
      Heightfield.prototype.getRectMinMax = function (iMinX, iMinY, iMaxX, iMaxY, result) {
          result = result || [];

          // Get max and min of the data
          var data = this.data,
              max = this.minValue; // Set first value
          for(var i = iMinX; i <= iMaxX; i++){
              for(var j = iMinY; j <= iMaxY; j++){
                  var height = data[i][j];
                  if(height > max){
                      max = height;
                  }
              }
          }

          result[0] = this.minValue;
          result[1] = max;
      };



      /**
       * Get the index of a local position on the heightfield. The indexes indicate the rectangles, so if your terrain is made of N x N height data points, you will have rectangle indexes ranging from 0 to N-1.
       * @method getIndexOfPosition
       * @param  {number} x
       * @param  {number} y
       * @param  {array} result Two-element array
       * @param  {boolean} clamp If the position should be clamped to the heightfield edge.
       * @return {boolean}
       */
      Heightfield.prototype.getIndexOfPosition = function (x, y, result, clamp) {

          // Get the index of the data points to test against
          var w = this.elementSize;
          var data = this.data;
          var xi = Math.floor(x / w);
          var yi = Math.floor(y / w);

          result[0] = xi;
          result[1] = yi;

          if(clamp){
              // Clamp index to edges
              if(xi < 0){ xi = 0; }
              if(yi < 0){ yi = 0; }
              if(xi >= data.length - 1){ xi = data.length - 1; }
              if(yi >= data[0].length - 1){ yi = data[0].length - 1; }
          }

          // Bail out if we are out of the terrain
          if(xi < 0 || yi < 0 || xi >= data.length-1 || yi >= data[0].length-1){
              return false;
          }

          return true;
      };


      var getHeightAt_idx = [];
      var getHeightAt_weights = new Vec3();
      var getHeightAt_a = new Vec3();
      var getHeightAt_b = new Vec3();
      var getHeightAt_c = new Vec3();

      Heightfield.prototype.getTriangleAt = function(x, y, edgeClamp, a, b, c){
          var idx = getHeightAt_idx;
          this.getIndexOfPosition(x, y, idx, edgeClamp);
          var xi = idx[0];
          var yi = idx[1];

          var data = this.data;
          if(edgeClamp){
              xi = Math.min(data.length - 2, Math.max(0, xi));
              yi = Math.min(data[0].length - 2, Math.max(0, yi));
          }

          var elementSize = this.elementSize;
          var lowerDist2 = Math.pow(x / elementSize - xi, 2) + Math.pow(y / elementSize - yi, 2);
          var upperDist2 = Math.pow(x / elementSize - (xi + 1), 2) + Math.pow(y / elementSize - (yi + 1), 2);
          var upper = lowerDist2 > upperDist2;
          this.getTriangle(xi, yi, upper, a, b, c);
          return upper;
      };

      var getNormalAt_a = new Vec3();
      var getNormalAt_b = new Vec3();
      var getNormalAt_c = new Vec3();
      var getNormalAt_e0 = new Vec3();
      var getNormalAt_e1 = new Vec3();
      Heightfield.prototype.getNormalAt = function(x, y, edgeClamp, result){
          var a = getNormalAt_a;
          var b = getNormalAt_b;
          var c = getNormalAt_c;
          var e0 = getNormalAt_e0;
          var e1 = getNormalAt_e1;
          this.getTriangleAt(x, y, edgeClamp, a, b, c);
          b.vsub(a, e0);
          c.vsub(a, e1);
          e0.cross(e1, result);
          result.normalize();
      };


      /**
       * Get an AABB of a square in the heightfield
       * @param  {number} xi
       * @param  {number} yi
       * @param  {AABB} result
       */
      Heightfield.prototype.getAabbAtIndex = function(xi, yi, result){
          var data = this.data;
          var elementSize = this.elementSize;

          result.lowerBound.set(
              xi * elementSize,
              yi * elementSize,
              data[xi][yi]
          );
          result.upperBound.set(
              (xi + 1) * elementSize,
              (yi + 1) * elementSize,
              data[xi + 1][yi + 1]
          );
      };


      /**
       * Get the height in the heightfield at a given position
       * @param  {number} x
       * @param  {number} y
       * @param  {boolean} edgeClamp
       * @return {number}
       */
      Heightfield.prototype.getHeightAt = function(x, y, edgeClamp){
          var data = this.data;
          var a = getHeightAt_a;
          var b = getHeightAt_b;
          var c = getHeightAt_c;
          var idx = getHeightAt_idx;

          this.getIndexOfPosition(x, y, idx, edgeClamp);
          var xi = idx[0];
          var yi = idx[1];
          if(edgeClamp){
              xi = Math.min(data.length - 2, Math.max(0, xi));
              yi = Math.min(data[0].length - 2, Math.max(0, yi));
          }
          var upper = this.getTriangleAt(x, y, edgeClamp, a, b, c);
          barycentricWeights(x, y, a.x, a.y, b.x, b.y, c.x, c.y, getHeightAt_weights);

          var w = getHeightAt_weights;

          if(upper){

              // Top triangle verts
              return data[xi + 1][yi + 1] * w.x + data[xi][yi + 1] * w.y + data[xi + 1][yi] * w.z;

          } else {

              // Top triangle verts
              return data[xi][yi] * w.x + data[xi + 1][yi] * w.y + data[xi][yi + 1] * w.z;
          }
      };

      // from https://en.wikipedia.org/wiki/Barycentric_coordinate_system
      function barycentricWeights(x, y, ax, ay, bx, by, cx, cy, result){
          result.x = ((by - cy) * (x - cx) + (cx - bx) * (y - cy)) / ((by - cy) * (ax - cx) + (cx - bx) * (ay - cy));
          result.y = ((cy - ay) * (x - cx) + (ax - cx) * (y - cy)) / ((by - cy) * (ax - cx) + (cx - bx) * (ay - cy));
          result.z = 1 - result.x - result.y;
      }

      Heightfield.prototype.getCacheConvexTrianglePillarKey = function(xi, yi, getUpperTriangle){
          return xi + '_' + yi + '_' + (getUpperTriangle ? 1 : 0);
      };

      Heightfield.prototype.getCachedConvexTrianglePillar = function(xi, yi, getUpperTriangle){
          return this._cachedPillars[this.getCacheConvexTrianglePillarKey(xi, yi, getUpperTriangle)];
      };

      Heightfield.prototype.setCachedConvexTrianglePillar = function(xi, yi, getUpperTriangle, convex, offset){
          this._cachedPillars[this.getCacheConvexTrianglePillarKey(xi, yi, getUpperTriangle)] = {
              convex: convex,
              offset: offset
          };
      };

      Heightfield.prototype.clearCachedConvexTrianglePillar = function(xi, yi, getUpperTriangle){
          delete this._cachedPillars[this.getCacheConvexTrianglePillarKey(xi, yi, getUpperTriangle)];
      };

      /**
       * Get a triangle from the heightfield
       * @param  {number} xi
       * @param  {number} yi
       * @param  {boolean} upper
       * @param  {Vec3} a
       * @param  {Vec3} b
       * @param  {Vec3} c
       */
      Heightfield.prototype.getTriangle = function(xi, yi, upper, a, b, c){
          var data = this.data;
          var elementSize = this.elementSize;

          if(upper){

              // Top triangle verts
              a.set(
                  (xi + 1) * elementSize,
                  (yi + 1) * elementSize,
                  data[xi + 1][yi + 1]
              );
              b.set(
                  xi * elementSize,
                  (yi + 1) * elementSize,
                  data[xi][yi + 1]
              );
              c.set(
                  (xi + 1) * elementSize,
                  yi * elementSize,
                  data[xi + 1][yi]
              );

          } else {

              // Top triangle verts
              a.set(
                  xi * elementSize,
                  yi * elementSize,
                  data[xi][yi]
              );
              b.set(
                  (xi + 1) * elementSize,
                  yi * elementSize,
                  data[xi + 1][yi]
              );
              c.set(
                  xi * elementSize,
                  (yi + 1) * elementSize,
                  data[xi][yi + 1]
              );
          }
      };

      /**
       * Get a triangle in the terrain in the form of a triangular convex shape.
       * @method getConvexTrianglePillar
       * @param  {integer} i
       * @param  {integer} j
       * @param  {boolean} getUpperTriangle
       */
      Heightfield.prototype.getConvexTrianglePillar = function(xi, yi, getUpperTriangle){
          var result = this.pillarConvex;
          var offsetResult = this.pillarOffset;

          if(this.cacheEnabled){
              var data = this.getCachedConvexTrianglePillar(xi, yi, getUpperTriangle);
              if(data){
                  this.pillarConvex = data.convex;
                  this.pillarOffset = data.offset;
                  return;
              }

              result = new ConvexPolyhedron();
              offsetResult = new Vec3();

              this.pillarConvex = result;
              this.pillarOffset = offsetResult;
          }

          var data = this.data;
          var elementSize = this.elementSize;
          var faces = result.faces;

          // Reuse verts if possible
          result.vertices.length = 6;
          for (var i = 0; i < 6; i++) {
              if(!result.vertices[i]){
                  result.vertices[i] = new Vec3();
              }
          }

          // Reuse faces if possible
          faces.length = 5;
          for (var i = 0; i < 5; i++) {
              if(!faces[i]){
                  faces[i] = [];
              }
          }

          var verts = result.vertices;

          var h = (Math.min(
              data[xi][yi],
              data[xi+1][yi],
              data[xi][yi+1],
              data[xi+1][yi+1]
          ) - this.minValue ) / 2 + this.minValue;

          if (!getUpperTriangle) {

              // Center of the triangle pillar - all polygons are given relative to this one
              offsetResult.set(
                  (xi + 0.25) * elementSize, // sort of center of a triangle
                  (yi + 0.25) * elementSize,
                  h // vertical center
              );

              // Top triangle verts
              verts[0].set(
                  -0.25 * elementSize,
                  -0.25 * elementSize,
                  data[xi][yi] - h
              );
              verts[1].set(
                  0.75 * elementSize,
                  -0.25 * elementSize,
                  data[xi + 1][yi] - h
              );
              verts[2].set(
                  -0.25 * elementSize,
                  0.75 * elementSize,
                  data[xi][yi + 1] - h
              );

              // bottom triangle verts
              verts[3].set(
                  -0.25 * elementSize,
                  -0.25 * elementSize,
                  -h-1
              );
              verts[4].set(
                  0.75 * elementSize,
                  -0.25 * elementSize,
                  -h-1
              );
              verts[5].set(
                  -0.25 * elementSize,
                  0.75  * elementSize,
                  -h-1
              );

              // top triangle
              faces[0][0] = 0;
              faces[0][1] = 1;
              faces[0][2] = 2;

              // bottom triangle
              faces[1][0] = 5;
              faces[1][1] = 4;
              faces[1][2] = 3;

              // -x facing quad
              faces[2][0] = 0;
              faces[2][1] = 2;
              faces[2][2] = 5;
              faces[2][3] = 3;

              // -y facing quad
              faces[3][0] = 1;
              faces[3][1] = 0;
              faces[3][2] = 3;
              faces[3][3] = 4;

              // +xy facing quad
              faces[4][0] = 4;
              faces[4][1] = 5;
              faces[4][2] = 2;
              faces[4][3] = 1;


          } else {

              // Center of the triangle pillar - all polygons are given relative to this one
              offsetResult.set(
                  (xi + 0.75) * elementSize, // sort of center of a triangle
                  (yi + 0.75) * elementSize,
                  h // vertical center
              );

              // Top triangle verts
              verts[0].set(
                  0.25 * elementSize,
                  0.25 * elementSize,
                  data[xi + 1][yi + 1] - h
              );
              verts[1].set(
                  -0.75 * elementSize,
                  0.25 * elementSize,
                  data[xi][yi + 1] - h
              );
              verts[2].set(
                  0.25 * elementSize,
                  -0.75 * elementSize,
                  data[xi + 1][yi] - h
              );

              // bottom triangle verts
              verts[3].set(
                  0.25 * elementSize,
                  0.25 * elementSize,
                  - h-1
              );
              verts[4].set(
                  -0.75 * elementSize,
                  0.25 * elementSize,
                  - h-1
              );
              verts[5].set(
                  0.25 * elementSize,
                  -0.75 * elementSize,
                  - h-1
              );

              // Top triangle
              faces[0][0] = 0;
              faces[0][1] = 1;
              faces[0][2] = 2;

              // bottom triangle
              faces[1][0] = 5;
              faces[1][1] = 4;
              faces[1][2] = 3;

              // +x facing quad
              faces[2][0] = 2;
              faces[2][1] = 5;
              faces[2][2] = 3;
              faces[2][3] = 0;

              // +y facing quad
              faces[3][0] = 3;
              faces[3][1] = 4;
              faces[3][2] = 1;
              faces[3][3] = 0;

              // -xy facing quad
              faces[4][0] = 1;
              faces[4][1] = 4;
              faces[4][2] = 5;
              faces[4][3] = 2;
          }

          result.computeNormals();
          result.computeEdges();
          result.updateBoundingSphereRadius();

          this.setCachedConvexTrianglePillar(xi, yi, getUpperTriangle, result, offsetResult);
      };

      Heightfield.prototype.calculateLocalInertia = function(mass, target){
          target = target || new Vec3();
          target.set(0, 0, 0);
          return target;
      };

      Heightfield.prototype.volume = function(){
          return Number.MAX_VALUE; // The terrain is infinite
      };

      Heightfield.prototype.calculateWorldAABB = function(pos, quat, min, max){
          // TODO: do it properly
          min.set(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
          max.set(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
      };

      Heightfield.prototype.updateBoundingSphereRadius = function(){
          // Use the bounding box of the min/max values
          var data = this.data,
              s = this.elementSize;
          this.boundingSphereRadius = new Vec3(data.length * s, data[0].length * s, Math.max(Math.abs(this.maxValue), Math.abs(this.minValue))).norm();
      };

      /**
       * Sets the height values from an image. Currently only supported in browser.
       * @method setHeightsFromImage
       * @param {Image} image
       * @param {Vec3} scale
       */
      Heightfield.prototype.setHeightsFromImage = function(image, scale){
          var canvas = document.createElement('canvas');
          canvas.width = image.width;
          canvas.height = image.height;
          var context = canvas.getContext('2d');
          context.drawImage(image, 0, 0);
          var imageData = context.getImageData(0, 0, image.width, image.height);

          var matrix = this.data;
          matrix.length = 0;
          this.elementSize = Math.abs(scale.x) / imageData.width;
          for(var i=0; i<imageData.height; i++){
              var row = [];
              for(var j=0; j<imageData.width; j++){
                  var a = imageData.data[(i*imageData.height + j) * 4];
                  var b = imageData.data[(i*imageData.height + j) * 4 + 1];
                  var c = imageData.data[(i*imageData.height + j) * 4 + 2];
                  var height = (a + b + c) / 4 / 255 * scale.z;
                  if(scale.x < 0){
                      row.push(height);
                  } else {
                      row.unshift(height);
                  }
              }
              if(scale.y < 0){
                  matrix.unshift(row);
              } else {
                  matrix.push(row);
              }
          }
          this.updateMaxValue();
          this.updateMinValue();
          this.update();
      };
      },{"../math/Vec3":31,"../utils/Utils":54,"./ConvexPolyhedron":39,"./Shape":44}],42:[function(_dereq_,module,exports){
      module.exports = Particle;

      var Shape = _dereq_('./Shape');
      var Vec3 = _dereq_('../math/Vec3');

      /**
       * Particle shape.
       * @class Particle
       * @constructor
       * @author schteppe
       * @extends Shape
       */
      function Particle(){
          Shape.call(this, {
              type: Shape.types.PARTICLE
          });
      }
      Particle.prototype = new Shape();
      Particle.prototype.constructor = Particle;

      /**
       * @method calculateLocalInertia
       * @param  {Number} mass
       * @param  {Vec3} target
       * @return {Vec3}
       */
      Particle.prototype.calculateLocalInertia = function(mass,target){
          target = target || new Vec3();
          target.set(0, 0, 0);
          return target;
      };

      Particle.prototype.volume = function(){
          return 0;
      };

      Particle.prototype.updateBoundingSphereRadius = function(){
          this.boundingSphereRadius = 0;
      };

      Particle.prototype.calculateWorldAABB = function(pos,quat,min,max){
          // Get each axis max
          min.copy(pos);
          max.copy(pos);
      };

      },{"../math/Vec3":31,"./Shape":44}],43:[function(_dereq_,module,exports){
      module.exports = Plane;

      var Shape = _dereq_('./Shape');
      var Vec3 = _dereq_('../math/Vec3');

      /**
       * A plane, facing in the Z direction. The plane has its surface at z=0 and everything below z=0 is assumed to be solid plane. To make the plane face in some other direction than z, you must put it inside a Body and rotate that body. See the demos.
       * @class Plane
       * @constructor
       * @extends Shape
       * @author schteppe
       */
      function Plane(){
          Shape.call(this, {
              type: Shape.types.PLANE
          });

          // World oriented normal
          this.worldNormal = new Vec3();
          this.worldNormalNeedsUpdate = true;

          this.boundingSphereRadius = Number.MAX_VALUE;
      }
      Plane.prototype = new Shape();
      Plane.prototype.constructor = Plane;

      Plane.prototype.computeWorldNormal = function(quat){
          var n = this.worldNormal;
          n.set(0,0,1);
          quat.vmult(n,n);
          this.worldNormalNeedsUpdate = false;
      };

      Plane.prototype.calculateLocalInertia = function(mass,target){
          target = target || new Vec3();
          return target;
      };

      Plane.prototype.volume = function(){
          return Number.MAX_VALUE; // The plane is infinite...
      };

      var tempNormal = new Vec3();
      Plane.prototype.calculateWorldAABB = function(pos, quat, min, max){
          // The plane AABB is infinite, except if the normal is pointing along any axis
          tempNormal.set(0,0,1); // Default plane normal is z
          quat.vmult(tempNormal,tempNormal);
          var maxVal = Number.MAX_VALUE;
          min.set(-maxVal, -maxVal, -maxVal);
          max.set(maxVal, maxVal, maxVal);

          if(tempNormal.x === 1){ max.x = pos.x; }
          if(tempNormal.y === 1){ max.y = pos.y; }
          if(tempNormal.z === 1){ max.z = pos.z; }

          if(tempNormal.x === -1){ min.x = pos.x; }
          if(tempNormal.y === -1){ min.y = pos.y; }
          if(tempNormal.z === -1){ min.z = pos.z; }
      };

      Plane.prototype.updateBoundingSphereRadius = function(){
          this.boundingSphereRadius = Number.MAX_VALUE;
      };
      },{"../math/Vec3":31,"./Shape":44}],44:[function(_dereq_,module,exports){
      module.exports = Shape;

      var EventTarget = _dereq_('../utils/EventTarget');
      var Shape = _dereq_('./Shape');
      _dereq_('../math/Vec3');
      _dereq_('../math/Quaternion');
      _dereq_('../material/Material');

      /**
       * Base class for shapes
       * @class Shape
       * @constructor
       * @param {object} [options]
       * @param {number} [options.collisionFilterGroup=1]
       * @param {number} [options.collisionFilterMask=-1]
       * @param {number} [options.collisionResponse=true]
       * @param {number} [options.material=null]
       * @author schteppe
       */
      function Shape(options){
          options = options || {};

          EventTarget.apply(this);
          /**
           * Identifyer of the Shape.
           * @property {number} id
           */
          this.id = Shape.idCounter++;

          /**
           * The type of this shape. Must be set to an int > 0 by subclasses.
           * @property type
           * @type {Number}
           * @see Shape.types
           */
          this.type = options.type || 0;

          /**
           * The local bounding sphere radius of this shape.
           * @property {Number} boundingSphereRadius
           */
          this.boundingSphereRadius = 0;

          /**
           * Whether to produce contact forces when in contact with other bodies. Note that contacts will be generated, but they will be disabled.
           * @property {boolean} collisionResponse
           */
          this.collisionResponse = options.collisionResponse ? options.collisionResponse : true;

          /**
           * @property {Number} collisionFilterGroup
           */
          this.collisionFilterGroup = options.collisionFilterGroup !== undefined ? options.collisionFilterGroup : 1;

          /**
           * @property {Number} collisionFilterMask
           */
          this.collisionFilterMask = options.collisionFilterMask !== undefined ? options.collisionFilterMask : -1;

          /**
           * @property {Material} material
           */
          this.material = options.material ? options.material : null;

          /**
           * @property {Body} body
           */
          this.body = null;
      }
      Shape.prototype = new EventTarget();
      Shape.prototype.constructor = Shape;

      /**
       * Computes the bounding sphere radius. The result is stored in the property .boundingSphereRadius
       * @method updateBoundingSphereRadius
       */
      Shape.prototype.updateBoundingSphereRadius = function(){
          throw "computeBoundingSphereRadius() not implemented for shape type "+this.type;
      };

      /**
       * Get the volume of this shape
       * @method volume
       * @return {Number}
       */
      Shape.prototype.volume = function(){
          throw "volume() not implemented for shape type "+this.type;
      };

      /**
       * Calculates the inertia in the local frame for this shape.
       * @method calculateLocalInertia
       * @param {Number} mass
       * @param {Vec3} target
       * @see http://en.wikipedia.org/wiki/List_of_moments_of_inertia
       */
      Shape.prototype.calculateLocalInertia = function(mass,target){
          throw "calculateLocalInertia() not implemented for shape type "+this.type;
      };

      Shape.idCounter = 0;

      /**
       * The available shape types.
       * @static
       * @property types
       * @type {Object}
       */
      Shape.types = {
          SPHERE:1,
          PLANE:2,
          BOX:4,
          COMPOUND:8,
          CONVEXPOLYHEDRON:16,
          HEIGHTFIELD:32,
          PARTICLE:64,
          CYLINDER:128,
          TRIMESH:256
      };


      },{"../material/Material":26,"../math/Quaternion":29,"../math/Vec3":31,"../utils/EventTarget":50,"./Shape":44}],45:[function(_dereq_,module,exports){
      module.exports = Sphere;

      var Shape = _dereq_('./Shape');
      var Vec3 = _dereq_('../math/Vec3');

      /**
       * Spherical shape
       * @class Sphere
       * @constructor
       * @extends Shape
       * @param {Number} radius The radius of the sphere, a non-negative number.
       * @author schteppe / http://github.com/schteppe
       */
      function Sphere(radius){
          Shape.call(this, {
              type: Shape.types.SPHERE
          });

          /**
           * @property {Number} radius
           */
          this.radius = radius !== undefined ? radius : 1.0;

          if(this.radius < 0){
              throw new Error('The sphere radius cannot be negative.');
          }

          this.updateBoundingSphereRadius();
      }
      Sphere.prototype = new Shape();
      Sphere.prototype.constructor = Sphere;

      Sphere.prototype.calculateLocalInertia = function(mass,target){
          target = target || new Vec3();
          var I = 2.0*mass*this.radius*this.radius/5.0;
          target.x = I;
          target.y = I;
          target.z = I;
          return target;
      };

      Sphere.prototype.volume = function(){
          return 4.0 * Math.PI * this.radius / 3.0;
      };

      Sphere.prototype.updateBoundingSphereRadius = function(){
          this.boundingSphereRadius = this.radius;
      };

      Sphere.prototype.calculateWorldAABB = function(pos,quat,min,max){
          var r = this.radius;
          var axes = ['x','y','z'];
          for(var i=0; i<axes.length; i++){
              var ax = axes[i];
              min[ax] = pos[ax] - r;
              max[ax] = pos[ax] + r;
          }
      };

      },{"../math/Vec3":31,"./Shape":44}],46:[function(_dereq_,module,exports){
      module.exports = Trimesh;

      var Shape = _dereq_('./Shape');
      var Vec3 = _dereq_('../math/Vec3');
      _dereq_('../math/Quaternion');
      var Transform = _dereq_('../math/Transform');
      var AABB = _dereq_('../collision/AABB');
      var Octree = _dereq_('../utils/Octree');

      /**
       * @class Trimesh
       * @constructor
       * @param {array} vertices
       * @param {array} indices
       * @extends Shape
       * @example
       *     // How to make a mesh with a single triangle
       *     var vertices = [
       *         0, 0, 0, // vertex 0
       *         1, 0, 0, // vertex 1
       *         0, 1, 0  // vertex 2
       *     ];
       *     var indices = [
       *         0, 1, 2  // triangle 0
       *     ];
       *     var trimeshShape = new Trimesh(vertices, indices);
       */
      function Trimesh(vertices, indices) {
          Shape.call(this, {
              type: Shape.types.TRIMESH
          });

          /**
           * @property vertices
           * @type {Array}
           */
          this.vertices = new Float32Array(vertices);

          /**
           * Array of integers, indicating which vertices each triangle consists of. The length of this array is thus 3 times the number of triangles.
           * @property indices
           * @type {Array}
           */
          this.indices = new Int16Array(indices);

          /**
           * The normals data.
           * @property normals
           * @type {Array}
           */
          this.normals = new Float32Array(indices.length);

          /**
           * The local AABB of the mesh.
           * @property aabb
           * @type {Array}
           */
          this.aabb = new AABB();

          /**
           * References to vertex pairs, making up all unique edges in the trimesh.
           * @property {array} edges
           */
          this.edges = null;

          /**
           * Local scaling of the mesh. Use .setScale() to set it.
           * @property {Vec3} scale
           */
          this.scale = new Vec3(1, 1, 1);

          /**
           * The indexed triangles. Use .updateTree() to update it.
           * @property {Octree} tree
           */
          this.tree = new Octree();

          this.updateEdges();
          this.updateNormals();
          this.updateAABB();
          this.updateBoundingSphereRadius();
          this.updateTree();
      }
      Trimesh.prototype = new Shape();
      Trimesh.prototype.constructor = Trimesh;

      var computeNormals_n = new Vec3();

      /**
       * @method updateTree
       */
      Trimesh.prototype.updateTree = function(){
          var tree = this.tree;

          tree.reset();
          tree.aabb.copy(this.aabb);
          var scale = this.scale; // The local mesh AABB is scaled, but the octree AABB should be unscaled
          tree.aabb.lowerBound.x *= 1 / scale.x;
          tree.aabb.lowerBound.y *= 1 / scale.y;
          tree.aabb.lowerBound.z *= 1 / scale.z;
          tree.aabb.upperBound.x *= 1 / scale.x;
          tree.aabb.upperBound.y *= 1 / scale.y;
          tree.aabb.upperBound.z *= 1 / scale.z;

          // Insert all triangles
          var triangleAABB = new AABB();
          var a = new Vec3();
          var b = new Vec3();
          var c = new Vec3();
          var points = [a, b, c];
          for (var i = 0; i < this.indices.length / 3; i++) {
              //this.getTriangleVertices(i, a, b, c);

              // Get unscaled triangle verts
              var i3 = i * 3;
              this._getUnscaledVertex(this.indices[i3], a);
              this._getUnscaledVertex(this.indices[i3 + 1], b);
              this._getUnscaledVertex(this.indices[i3 + 2], c);

              triangleAABB.setFromPoints(points);
              tree.insert(triangleAABB, i);
          }
          tree.removeEmptyNodes();
      };

      var unscaledAABB = new AABB();

      /**
       * Get triangles in a local AABB from the trimesh.
       * @method getTrianglesInAABB
       * @param  {AABB} aabb
       * @param  {array} result An array of integers, referencing the queried triangles.
       */
      Trimesh.prototype.getTrianglesInAABB = function(aabb, result){
          unscaledAABB.copy(aabb);

          // Scale it to local
          var scale = this.scale;
          var isx = scale.x;
          var isy = scale.y;
          var isz = scale.z;
          var l = unscaledAABB.lowerBound;
          var u = unscaledAABB.upperBound;
          l.x /= isx;
          l.y /= isy;
          l.z /= isz;
          u.x /= isx;
          u.y /= isy;
          u.z /= isz;

          return this.tree.aabbQuery(unscaledAABB, result);
      };

      /**
       * @method setScale
       * @param {Vec3} scale
       */
      Trimesh.prototype.setScale = function(scale){
          var wasUniform = this.scale.x === this.scale.y === this.scale.z;
          var isUniform = scale.x === scale.y === scale.z;

          if(!(wasUniform && isUniform)){
              // Non-uniform scaling. Need to update normals.
              this.updateNormals();
          }
          this.scale.copy(scale);
          this.updateAABB();
          this.updateBoundingSphereRadius();
      };

      /**
       * Compute the normals of the faces. Will save in the .normals array.
       * @method updateNormals
       */
      Trimesh.prototype.updateNormals = function(){
          var n = computeNormals_n;

          // Generate normals
          var normals = this.normals;
          for(var i=0; i < this.indices.length / 3; i++){
              var i3 = i * 3;

              var a = this.indices[i3],
                  b = this.indices[i3 + 1],
                  c = this.indices[i3 + 2];

              this.getVertex(a, va);
              this.getVertex(b, vb);
              this.getVertex(c, vc);

              Trimesh.computeNormal(vb, va, vc, n);

              normals[i3] = n.x;
              normals[i3 + 1] = n.y;
              normals[i3 + 2] = n.z;
          }
      };

      /**
       * Update the .edges property
       * @method updateEdges
       */
      Trimesh.prototype.updateEdges = function(){
          var edges = {};
          var add = function(indexA, indexB){
              var key = a < b ? a + '_' + b : b + '_' + a;
              edges[key] = true;
          };
          for(var i=0; i < this.indices.length / 3; i++){
              var i3 = i * 3;
              var a = this.indices[i3],
                  b = this.indices[i3 + 1];
                  this.indices[i3 + 2];
              add();
              add();
              add();
          }
          var keys = Object.keys(edges);
          this.edges = new Int16Array(keys.length * 2);
          for (var i = 0; i < keys.length; i++) {
              var indices = keys[i].split('_');
              this.edges[2 * i] = parseInt(indices[0], 10);
              this.edges[2 * i + 1] = parseInt(indices[1], 10);
          }
      };

      /**
       * Get an edge vertex
       * @method getEdgeVertex
       * @param  {number} edgeIndex
       * @param  {number} firstOrSecond 0 or 1, depending on which one of the vertices you need.
       * @param  {Vec3} vertexStore Where to store the result
       */
      Trimesh.prototype.getEdgeVertex = function(edgeIndex, firstOrSecond, vertexStore){
          var vertexIndex = this.edges[edgeIndex * 2 + (firstOrSecond ? 1 : 0)];
          this.getVertex(vertexIndex, vertexStore);
      };

      var getEdgeVector_va = new Vec3();
      var getEdgeVector_vb = new Vec3();

      /**
       * Get a vector along an edge.
       * @method getEdgeVector
       * @param  {number} edgeIndex
       * @param  {Vec3} vectorStore
       */
      Trimesh.prototype.getEdgeVector = function(edgeIndex, vectorStore){
          var va = getEdgeVector_va;
          var vb = getEdgeVector_vb;
          this.getEdgeVertex(edgeIndex, 0, va);
          this.getEdgeVertex(edgeIndex, 1, vb);
          vb.vsub(va, vectorStore);
      };

      /**
       * Get face normal given 3 vertices
       * @static
       * @method computeNormal
       * @param {Vec3} va
       * @param {Vec3} vb
       * @param {Vec3} vc
       * @param {Vec3} target
       */
      var cb = new Vec3();
      var ab = new Vec3();
      Trimesh.computeNormal = function ( va, vb, vc, target ) {
          vb.vsub(va,ab);
          vc.vsub(vb,cb);
          cb.cross(ab,target);
          if ( !target.isZero() ) {
              target.normalize();
          }
      };

      var va = new Vec3();
      var vb = new Vec3();
      var vc = new Vec3();

      /**
       * Get vertex i.
       * @method getVertex
       * @param  {number} i
       * @param  {Vec3} out
       * @return {Vec3} The "out" vector object
       */
      Trimesh.prototype.getVertex = function(i, out){
          var scale = this.scale;
          this._getUnscaledVertex(i, out);
          out.x *= scale.x;
          out.y *= scale.y;
          out.z *= scale.z;
          return out;
      };

      /**
       * Get raw vertex i
       * @private
       * @method _getUnscaledVertex
       * @param  {number} i
       * @param  {Vec3} out
       * @return {Vec3} The "out" vector object
       */
      Trimesh.prototype._getUnscaledVertex = function(i, out){
          var i3 = i * 3;
          var vertices = this.vertices;
          return out.set(
              vertices[i3],
              vertices[i3 + 1],
              vertices[i3 + 2]
          );
      };

      /**
       * Get a vertex from the trimesh,transformed by the given position and quaternion.
       * @method getWorldVertex
       * @param  {number} i
       * @param  {Vec3} pos
       * @param  {Quaternion} quat
       * @param  {Vec3} out
       * @return {Vec3} The "out" vector object
       */
      Trimesh.prototype.getWorldVertex = function(i, pos, quat, out){
          this.getVertex(i, out);
          Transform.pointToWorldFrame(pos, quat, out, out);
          return out;
      };

      /**
       * Get the three vertices for triangle i.
       * @method getTriangleVertices
       * @param  {number} i
       * @param  {Vec3} a
       * @param  {Vec3} b
       * @param  {Vec3} c
       */
      Trimesh.prototype.getTriangleVertices = function(i, a, b, c){
          var i3 = i * 3;
          this.getVertex(this.indices[i3], a);
          this.getVertex(this.indices[i3 + 1], b);
          this.getVertex(this.indices[i3 + 2], c);
      };

      /**
       * Compute the normal of triangle i.
       * @method getNormal
       * @param  {Number} i
       * @param  {Vec3} target
       * @return {Vec3} The "target" vector object
       */
      Trimesh.prototype.getNormal = function(i, target){
          var i3 = i * 3;
          return target.set(
              this.normals[i3],
              this.normals[i3 + 1],
              this.normals[i3 + 2]
          );
      };

      var cli_aabb = new AABB();

      /**
       * @method calculateLocalInertia
       * @param  {Number} mass
       * @param  {Vec3} target
       * @return {Vec3} The "target" vector object
       */
      Trimesh.prototype.calculateLocalInertia = function(mass,target){
          // Approximate with box inertia
          // Exact inertia calculation is overkill, but see http://geometrictools.com/Documentation/PolyhedralMassProperties.pdf for the correct way to do it
          this.computeLocalAABB(cli_aabb);
          var x = cli_aabb.upperBound.x - cli_aabb.lowerBound.x,
              y = cli_aabb.upperBound.y - cli_aabb.lowerBound.y,
              z = cli_aabb.upperBound.z - cli_aabb.lowerBound.z;
          return target.set(
              1.0 / 12.0 * mass * ( 2*y*2*y + 2*z*2*z ),
              1.0 / 12.0 * mass * ( 2*x*2*x + 2*z*2*z ),
              1.0 / 12.0 * mass * ( 2*y*2*y + 2*x*2*x )
          );
      };

      var computeLocalAABB_worldVert = new Vec3();

      /**
       * Compute the local AABB for the trimesh
       * @method computeLocalAABB
       * @param  {AABB} aabb
       */
      Trimesh.prototype.computeLocalAABB = function(aabb){
          var l = aabb.lowerBound,
              u = aabb.upperBound,
              n = this.vertices.length/3,
              v = computeLocalAABB_worldVert;
          if (n===0) return;
          this.getVertex(0, v);
          l.copy(v);
          u.copy(v);

          for(var i=0; i !== n; i++){
              this.getVertex(i, v);

              if(v.x < l.x){
                  l.x = v.x;
              } else if(v.x > u.x){
                  u.x = v.x;
              }

              if(v.y < l.y){
                  l.y = v.y;
              } else if(v.y > u.y){
                  u.y = v.y;
              }

              if(v.z < l.z){
                  l.z = v.z;
              } else if(v.z > u.z){
                  u.z = v.z;
              }
          }
      };


      /**
       * Update the .aabb property
       * @method updateAABB
       */
      Trimesh.prototype.updateAABB = function(){
          this.computeLocalAABB(this.aabb);
      };

      /**
       * Will update the .boundingSphereRadius property
       * @method updateBoundingSphereRadius
       */
      Trimesh.prototype.updateBoundingSphereRadius = function(){
          // Assume points are distributed with local (0,0,0) as center
          var max2 = 0;
          var vertices = this.vertices;
          var v = new Vec3();
          for(var i=0, N=vertices.length / 3; i !== N; i++) {
              this.getVertex(i, v);
              var norm2 = v.norm2();
              if(norm2 > max2){
                  max2 = norm2;
              }
          }
          this.boundingSphereRadius = Math.sqrt(max2);
      };

      new Vec3();
      var calculateWorldAABB_frame = new Transform();
      var calculateWorldAABB_aabb = new AABB();

      /**
       * @method calculateWorldAABB
       * @param {Vec3}        pos
       * @param {Quaternion}  quat
       * @param {Vec3}        min
       * @param {Vec3}        max
       */
      Trimesh.prototype.calculateWorldAABB = function(pos,quat,min,max){
          /*
          var n = this.vertices.length / 3,
              verts = this.vertices;
          var minx,miny,minz,maxx,maxy,maxz;

          var v = tempWorldVertex;
          for(var i=0; i<n; i++){
              this.getVertex(i, v);
              quat.vmult(v, v);
              pos.vadd(v, v);
              if (v.x < minx || minx===undefined){
                  minx = v.x;
              } else if(v.x > maxx || maxx===undefined){
                  maxx = v.x;
              }

              if (v.y < miny || miny===undefined){
                  miny = v.y;
              } else if(v.y > maxy || maxy===undefined){
                  maxy = v.y;
              }

              if (v.z < minz || minz===undefined){
                  minz = v.z;
              } else if(v.z > maxz || maxz===undefined){
                  maxz = v.z;
              }
          }
          min.set(minx,miny,minz);
          max.set(maxx,maxy,maxz);
          */

          // Faster approximation using local AABB
          var frame = calculateWorldAABB_frame;
          var result = calculateWorldAABB_aabb;
          frame.position = pos;
          frame.quaternion = quat;
          this.aabb.toWorldFrame(frame, result);
          min.copy(result.lowerBound);
          max.copy(result.upperBound);
      };

      /**
       * Get approximate volume
       * @method volume
       * @return {Number}
       */
      Trimesh.prototype.volume = function(){
          return 4.0 * Math.PI * this.boundingSphereRadius / 3.0;
      };

      /**
       * Create a Trimesh instance, shaped as a torus.
       * @static
       * @method createTorus
       * @param  {number} [radius=1]
       * @param  {number} [tube=0.5]
       * @param  {number} [radialSegments=8]
       * @param  {number} [tubularSegments=6]
       * @param  {number} [arc=6.283185307179586]
       * @return {Trimesh} A torus
       */
      Trimesh.createTorus = function (radius, tube, radialSegments, tubularSegments, arc) {
          radius = radius || 1;
          tube = tube || 0.5;
          radialSegments = radialSegments || 8;
          tubularSegments = tubularSegments || 6;
          arc = arc || Math.PI * 2;

          var vertices = [];
          var indices = [];

          for ( var j = 0; j <= radialSegments; j ++ ) {
              for ( var i = 0; i <= tubularSegments; i ++ ) {
                  var u = i / tubularSegments * arc;
                  var v = j / radialSegments * Math.PI * 2;

                  var x = ( radius + tube * Math.cos( v ) ) * Math.cos( u );
                  var y = ( radius + tube * Math.cos( v ) ) * Math.sin( u );
                  var z = tube * Math.sin( v );

                  vertices.push( x, y, z );
              }
          }

          for ( var j = 1; j <= radialSegments; j ++ ) {
              for ( var i = 1; i <= tubularSegments; i ++ ) {
                  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;

                  indices.push(a, b, d);
                  indices.push(b, c, d);
              }
          }

          return new Trimesh(vertices, indices);
      };

      },{"../collision/AABB":3,"../math/Quaternion":29,"../math/Transform":30,"../math/Vec3":31,"../utils/Octree":51,"./Shape":44}],47:[function(_dereq_,module,exports){
      module.exports = GSSolver;

      _dereq_('../math/Vec3');
      _dereq_('../math/Quaternion');
      var Solver = _dereq_('./Solver');

      /**
       * Constraint equation Gauss-Seidel solver.
       * @class GSSolver
       * @constructor
       * @todo The spook parameters should be specified for each constraint, not globally.
       * @author schteppe / https://github.com/schteppe
       * @see https://www8.cs.umu.se/kurser/5DV058/VT09/lectures/spooknotes.pdf
       * @extends Solver
       */
      function GSSolver(){
          Solver.call(this);

          /**
           * The number of solver iterations determines quality of the constraints in the world. The more iterations, the more correct simulation. More iterations need more computations though. If you have a large gravity force in your world, you will need more iterations.
           * @property iterations
           * @type {Number}
           * @todo write more about solver and iterations in the wiki
           */
          this.iterations = 10;

          /**
           * When tolerance is reached, the system is assumed to be converged.
           * @property tolerance
           * @type {Number}
           */
          this.tolerance = 1e-7;
      }
      GSSolver.prototype = new Solver();

      var GSSolver_solve_lambda = []; // Just temporary number holders that we want to reuse each solve.
      var GSSolver_solve_invCs = [];
      var GSSolver_solve_Bs = [];
      GSSolver.prototype.solve = function(dt,world){
          var iter = 0,
              maxIter = this.iterations,
              tolSquared = this.tolerance*this.tolerance,
              equations = this.equations,
              Neq = equations.length,
              bodies = world.bodies,
              Nbodies = bodies.length,
              h = dt,
              B, invC, deltalambda, deltalambdaTot, GWlambda, lambdaj;

          // Update solve mass
          if(Neq !== 0){
              for(var i=0; i!==Nbodies; i++){
                  bodies[i].updateSolveMassProperties();
              }
          }

          // Things that does not change during iteration can be computed once
          var invCs = GSSolver_solve_invCs,
              Bs = GSSolver_solve_Bs,
              lambda = GSSolver_solve_lambda;
          invCs.length = Neq;
          Bs.length = Neq;
          lambda.length = Neq;
          for(var i=0; i!==Neq; i++){
              var c = equations[i];
              lambda[i] = 0.0;
              Bs[i] = c.computeB(h);
              invCs[i] = 1.0 / c.computeC();
          }

          if(Neq !== 0){

              // Reset vlambda
              for(var i=0; i!==Nbodies; i++){
                  var b=bodies[i],
                      vlambda=b.vlambda,
                      wlambda=b.wlambda;
                  vlambda.set(0,0,0);
                  wlambda.set(0,0,0);
              }

              // Iterate over equations
              for(iter=0; iter!==maxIter; iter++){

                  // Accumulate the total error for each iteration.
                  deltalambdaTot = 0.0;

                  for(var j=0; j!==Neq; j++){

                      var c = equations[j];

                      // Compute iteration
                      B = Bs[j];
                      invC = invCs[j];
                      lambdaj = lambda[j];
                      GWlambda = c.computeGWlambda();
                      deltalambda = invC * ( B - GWlambda - c.eps * lambdaj );

                      // Clamp if we are not within the min/max interval
                      if(lambdaj + deltalambda < c.minForce){
                          deltalambda = c.minForce - lambdaj;
                      } else if(lambdaj + deltalambda > c.maxForce){
                          deltalambda = c.maxForce - lambdaj;
                      }
                      lambda[j] += deltalambda;

                      deltalambdaTot += deltalambda > 0.0 ? deltalambda : -deltalambda; // abs(deltalambda)

                      c.addToWlambda(deltalambda);
                  }

                  // If the total error is small enough - stop iterate
                  if(deltalambdaTot*deltalambdaTot < tolSquared){
                      break;
                  }
              }

              // Add result to velocity
              for(var i=0; i!==Nbodies; i++){
                  var b=bodies[i],
                      v=b.velocity,
                      w=b.angularVelocity;

                  b.vlambda.vmul(b.linearFactor, b.vlambda);
                  v.vadd(b.vlambda, v);

                  b.wlambda.vmul(b.angularFactor, b.wlambda);
                  w.vadd(b.wlambda, w);
              }

              // Set the .multiplier property of each equation
              var l = equations.length;
              var invDt = 1 / h;
              while(l--){
                  equations[l].multiplier = lambda[l] * invDt;
              }
          }

          return iter;
      };

      },{"../math/Quaternion":29,"../math/Vec3":31,"./Solver":48}],48:[function(_dereq_,module,exports){
      module.exports = Solver;

      /**
       * Constraint equation solver base class.
       * @class Solver
       * @constructor
       * @author schteppe / https://github.com/schteppe
       */
      function Solver(){
          /**
           * All equations to be solved
           * @property {Array} equations
           */
          this.equations = [];
      }

      /**
       * Should be implemented in subclasses!
       * @method solve
       * @param  {Number} dt
       * @param  {World} world
       */
      Solver.prototype.solve = function(dt,world){
          // Should return the number of iterations done!
          return 0;
      };

      /**
       * Add an equation
       * @method addEquation
       * @param {Equation} eq
       */
      Solver.prototype.addEquation = function(eq){
          if (eq.enabled) {
              this.equations.push(eq);
          }
      };

      /**
       * Remove an equation
       * @method removeEquation
       * @param {Equation} eq
       */
      Solver.prototype.removeEquation = function(eq){
          var eqs = this.equations;
          var i = eqs.indexOf(eq);
          if(i !== -1){
              eqs.splice(i,1);
          }
      };

      /**
       * Add all equations
       * @method removeAllEquations
       */
      Solver.prototype.removeAllEquations = function(){
          this.equations.length = 0;
      };


      },{}],49:[function(_dereq_,module,exports){
      module.exports = SplitSolver;

      _dereq_('../math/Vec3');
      _dereq_('../math/Quaternion');
      var Solver = _dereq_('./Solver');
      var Body = _dereq_('../objects/Body');

      /**
       * Splits the equations into islands and solves them independently. Can improve performance.
       * @class SplitSolver
       * @constructor
       * @extends Solver
       * @param {Solver} subsolver
       */
      function SplitSolver(subsolver){
          Solver.call(this);
          this.iterations = 10;
          this.tolerance = 1e-7;
          this.subsolver = subsolver;
          this.nodes = [];
          this.nodePool = [];

          // Create needed nodes, reuse if possible
          while(this.nodePool.length < 128){
              this.nodePool.push(this.createNode());
          }
      }
      SplitSolver.prototype = new Solver();

      // Returns the number of subsystems
      var SplitSolver_solve_nodes = []; // All allocated node objects
      var SplitSolver_solve_eqs = [];   // Temp array
      var SplitSolver_solve_dummyWorld = {bodies:[]}; // Temp object

      var STATIC = Body.STATIC;
      function getUnvisitedNode(nodes){
          var Nnodes = nodes.length;
          for(var i=0; i!==Nnodes; i++){
              var node = nodes[i];
              if(!node.visited && !(node.body.type & STATIC)){
                  return node;
              }
          }
          return false;
      }

      var queue = [];
      function bfs(root,visitFunc,bds,eqs){
          queue.push(root);
          root.visited = true;
          visitFunc(root,bds,eqs);
          while(queue.length) {
              var node = queue.pop();
              // Loop over unvisited child nodes
              var child;
              while((child = getUnvisitedNode(node.children))) {
                  child.visited = true;
                  visitFunc(child,bds,eqs);
                  queue.push(child);
              }
          }
      }

      function visitFunc(node,bds,eqs){
          bds.push(node.body);
          var Neqs = node.eqs.length;
          for(var i=0; i!==Neqs; i++){
              var eq = node.eqs[i];
              if(eqs.indexOf(eq) === -1){
                  eqs.push(eq);
              }
          }
      }

      SplitSolver.prototype.createNode = function(){
          return { body:null, children:[], eqs:[], visited:false };
      };

      /**
       * Solve the subsystems
       * @method solve
       * @param  {Number} dt
       * @param  {World} world
       */
      SplitSolver.prototype.solve = function(dt,world){
          var nodes=SplitSolver_solve_nodes,
              nodePool=this.nodePool,
              bodies=world.bodies,
              equations=this.equations,
              Neq=equations.length,
              Nbodies=bodies.length,
              subsolver=this.subsolver;

          // Create needed nodes, reuse if possible
          while(nodePool.length < Nbodies){
              nodePool.push(this.createNode());
          }
          nodes.length = Nbodies;
          for (var i = 0; i < Nbodies; i++) {
              nodes[i] = nodePool[i];
          }

          // Reset node values
          for(var i=0; i!==Nbodies; i++){
              var node = nodes[i];
              node.body = bodies[i];
              node.children.length = 0;
              node.eqs.length = 0;
              node.visited = false;
          }
          for(var k=0; k!==Neq; k++){
              var eq=equations[k],
                  i=bodies.indexOf(eq.bi),
                  j=bodies.indexOf(eq.bj),
                  ni=nodes[i],
                  nj=nodes[j];
              ni.children.push(nj);
              ni.eqs.push(eq);
              nj.children.push(ni);
              nj.eqs.push(eq);
          }

          var child, n=0, eqs=SplitSolver_solve_eqs;

          subsolver.tolerance = this.tolerance;
          subsolver.iterations = this.iterations;

          var dummyWorld = SplitSolver_solve_dummyWorld;
          while((child = getUnvisitedNode(nodes))){
              eqs.length = 0;
              dummyWorld.bodies.length = 0;
              bfs(child, visitFunc, dummyWorld.bodies, eqs);

              var Neqs = eqs.length;

              eqs = eqs.sort(sortById);

              for(var i=0; i!==Neqs; i++){
                  subsolver.addEquation(eqs[i]);
              }

              subsolver.solve(dt,dummyWorld);
              subsolver.removeAllEquations();
              n++;
          }

          return n;
      };

      function sortById(a, b){
          return b.id - a.id;
      }
      },{"../math/Quaternion":29,"../math/Vec3":31,"../objects/Body":32,"./Solver":48}],50:[function(_dereq_,module,exports){
      /**
       * Base class for objects that dispatches events.
       * @class EventTarget
       * @constructor
       */
      var EventTarget = function () {

      };

      module.exports = EventTarget;

      EventTarget.prototype = {
          constructor: EventTarget,

          /**
           * Add an event listener
           * @method addEventListener
           * @param  {String} type
           * @param  {Function} listener
           * @return {EventTarget} The self object, for chainability.
           */
          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 );
              }
              return this;
          },

          /**
           * Check if an event listener is added
           * @method hasEventListener
           * @param  {String} type
           * @param  {Function} listener
           * @return {Boolean}
           */
          hasEventListener: function ( type, listener ) {
              if ( this._listeners === undefined ){ return false; }
              var listeners = this._listeners;
              if ( listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1 ) {
                  return true;
              }
              return false;
          },

          /**
           * Check if any event listener of the given type is added
           * @method hasAnyEventListener
           * @param  {String} type
           * @return {Boolean}
           */
          hasAnyEventListener: function ( type ) {
              if ( this._listeners === undefined ){ return false; }
              var listeners = this._listeners;
              return ( listeners[ type ] !== undefined );
          },

          /**
           * Remove an event listener
           * @method removeEventListener
           * @param  {String} type
           * @param  {Function} listener
           * @return {EventTarget} The self object, for chainability.
           */
          removeEventListener: function ( type, listener ) {
              if ( this._listeners === undefined ){ return this; }
              var listeners = this._listeners;
              if ( listeners[type] === undefined ){ return this; }
              var index = listeners[ type ].indexOf( listener );
              if ( index !== - 1 ) {
                  listeners[ type ].splice( index, 1 );
              }
              return this;
          },

          /**
           * Emit an event.
           * @method dispatchEvent
           * @param  {Object} event
           * @param  {String} event.type
           * @return {EventTarget} The self object, for chainability.
           */
          dispatchEvent: function ( event ) {
              if ( this._listeners === undefined ){ return this; }
              var listeners = this._listeners;
              var listenerArray = listeners[ event.type ];
              if ( listenerArray !== undefined ) {
                  event.target = this;
                  for ( var i = 0, l = listenerArray.length; i < l; i ++ ) {
                      listenerArray[ i ].call( this, event );
                  }
              }
              return this;
          }
      };

      },{}],51:[function(_dereq_,module,exports){
      var AABB = _dereq_('../collision/AABB');
      var Vec3 = _dereq_('../math/Vec3');

      module.exports = Octree;

      /**
       * @class OctreeNode
       * @param {object} [options]
       * @param {Octree} [options.root]
       * @param {AABB} [options.aabb]
       */
      function OctreeNode(options){
          options = options || {};

          /**
           * The root node
           * @property {OctreeNode} root
           */
          this.root = options.root || null;

          /**
           * Boundary of this node
           * @property {AABB} aabb
           */
          this.aabb = options.aabb ? options.aabb.clone() : new AABB();

          /**
           * Contained data at the current node level.
           * @property {Array} data
           */
          this.data = [];

          /**
           * Children to this node
           * @property {Array} children
           */
          this.children = [];
      }

      /**
       * @class Octree
       * @param {AABB} aabb The total AABB of the tree
       * @param {object} [options]
       * @param {number} [options.maxDepth=8]
       * @extends OctreeNode
       */
      function Octree(aabb, options){
          options = options || {};
          options.root = null;
          options.aabb = aabb;
          OctreeNode.call(this, options);

          /**
           * Maximum subdivision depth
           * @property {number} maxDepth
           */
          this.maxDepth = typeof(options.maxDepth) !== 'undefined' ? options.maxDepth : 8;
      }
      Octree.prototype = new OctreeNode();

      OctreeNode.prototype.reset = function(aabb, options){
          this.children.length = this.data.length = 0;
      };

      /**
       * Insert data into this node
       * @method insert
       * @param  {AABB} aabb
       * @param  {object} elementData
       * @return {boolean} True if successful, otherwise false
       */
      OctreeNode.prototype.insert = function(aabb, elementData, level){
          var nodeData = this.data;
          level = level || 0;

          // Ignore objects that do not belong in this node
          if (!this.aabb.contains(aabb)){
              return false; // object cannot be added
          }

          var children = this.children;

          if(level < (this.maxDepth || this.root.maxDepth)){
              // Subdivide if there are no children yet
              var subdivided = false;
              if (!children.length){
                  this.subdivide();
                  subdivided = true;
              }

              // add to whichever node will accept it
              for (var i = 0; i !== 8; i++) {
                  if (children[i].insert(aabb, elementData, level + 1)){
                      return true;
                  }
              }

              if(subdivided){
                  // No children accepted! Might as well just remove em since they contain none
                  children.length = 0;
              }
          }

          // Too deep, or children didnt want it. add it in current node
          nodeData.push(elementData);

          return true;
      };

      var halfDiagonal = new Vec3();

      /**
       * Create 8 equally sized children nodes and put them in the .children array.
       * @method subdivide
       */
      OctreeNode.prototype.subdivide = function() {
          var aabb = this.aabb;
          var l = aabb.lowerBound;
          var u = aabb.upperBound;

          var children = this.children;

          children.push(
              new OctreeNode({ aabb: new AABB({ lowerBound: new Vec3(0,0,0) }) }),
              new OctreeNode({ aabb: new AABB({ lowerBound: new Vec3(1,0,0) }) }),
              new OctreeNode({ aabb: new AABB({ lowerBound: new Vec3(1,1,0) }) }),
              new OctreeNode({ aabb: new AABB({ lowerBound: new Vec3(1,1,1) }) }),
              new OctreeNode({ aabb: new AABB({ lowerBound: new Vec3(0,1,1) }) }),
              new OctreeNode({ aabb: new AABB({ lowerBound: new Vec3(0,0,1) }) }),
              new OctreeNode({ aabb: new AABB({ lowerBound: new Vec3(1,0,1) }) }),
              new OctreeNode({ aabb: new AABB({ lowerBound: new Vec3(0,1,0) }) })
          );

          u.vsub(l, halfDiagonal);
          halfDiagonal.scale(0.5, halfDiagonal);

          var root = this.root || this;

          for (var i = 0; i !== 8; i++) {
              var child = children[i];

              // Set current node as root
              child.root = root;

              // Compute bounds
              var lowerBound = child.aabb.lowerBound;
              lowerBound.x *= halfDiagonal.x;
              lowerBound.y *= halfDiagonal.y;
              lowerBound.z *= halfDiagonal.z;

              lowerBound.vadd(l, lowerBound);

              // Upper bound is always lower bound + halfDiagonal
              lowerBound.vadd(halfDiagonal, child.aabb.upperBound);
          }
      };

      /**
       * Get all data, potentially within an AABB
       * @method aabbQuery
       * @param  {AABB} aabb
       * @param  {array} result
       * @return {array} The "result" object
       */
      OctreeNode.prototype.aabbQuery = function(aabb, result) {

          this.data;

          // abort if the range does not intersect this node
          // if (!this.aabb.overlaps(aabb)){
          //     return result;
          // }

          // Add objects at this level
          // Array.prototype.push.apply(result, nodeData);

          // Add child data
          // @todo unwrap recursion into a queue / loop, that's faster in JS
          this.children;


          // for (var i = 0, N = this.children.length; i !== N; i++) {
          //     children[i].aabbQuery(aabb, result);
          // }

          var queue = [this];
          while (queue.length) {
              var node = queue.pop();
              if (node.aabb.overlaps(aabb)){
                  Array.prototype.push.apply(result, node.data);
              }
              Array.prototype.push.apply(queue, node.children);
          }

          return result;
      };

      var tmpAABB = new AABB();

      /**
       * Get all data, potentially intersected by a ray.
       * @method rayQuery
       * @param  {Ray} ray
       * @param  {Transform} treeTransform
       * @param  {array} result
       * @return {array} The "result" object
       */
      OctreeNode.prototype.rayQuery = function(ray, treeTransform, result) {

          // Use aabb query for now.
          // @todo implement real ray query which needs less lookups
          ray.getAABB(tmpAABB);
          tmpAABB.toLocalFrame(treeTransform, tmpAABB);
          this.aabbQuery(tmpAABB, result);

          return result;
      };

      /**
       * @method removeEmptyNodes
       */
      OctreeNode.prototype.removeEmptyNodes = function() {
          for (var i = this.children.length - 1; i >= 0; i--) {
              this.children[i].removeEmptyNodes();
              if(!this.children[i].children.length && !this.children[i].data.length){
                  this.children.splice(i, 1);
              }
          }
      };

      },{"../collision/AABB":3,"../math/Vec3":31}],52:[function(_dereq_,module,exports){
      module.exports = Pool;

      /**
       * For pooling objects that can be reused.
       * @class Pool
       * @constructor
       */
      function Pool(){
          /**
           * The pooled objects
           * @property {Array} objects
           */
          this.objects = [];

          /**
           * Constructor of the objects
           * @property {mixed} type
           */
          this.type = Object;
      }

      /**
       * Release an object after use
       * @method release
       * @param {Object} obj
       */
      Pool.prototype.release = function(){
          var Nargs = arguments.length;
          for(var i=0; i!==Nargs; i++){
              this.objects.push(arguments[i]);
          }
          return this;
      };

      /**
       * Get an object
       * @method get
       * @return {mixed}
       */
      Pool.prototype.get = function(){
          if(this.objects.length===0){
              return this.constructObject();
          } else {
              return this.objects.pop();
          }
      };

      /**
       * Construct an object. Should be implmented in each subclass.
       * @method constructObject
       * @return {mixed}
       */
      Pool.prototype.constructObject = function(){
          throw new Error("constructObject() not implemented in this Pool subclass yet!");
      };

      /**
       * @method resize
       * @param {number} size
       * @return {Pool} Self, for chaining
       */
      Pool.prototype.resize = function (size) {
          var objects = this.objects;

          while (objects.length > size) {
              objects.pop();
          }

          while (objects.length < size) {
              objects.push(this.constructObject());
          }

          return this;
      };


      },{}],53:[function(_dereq_,module,exports){
      module.exports = TupleDictionary;

      /**
       * @class TupleDictionary
       * @constructor
       */
      function TupleDictionary() {

          /**
           * The data storage
           * @property data
           * @type {Object}
           */
          this.data = { keys:[] };
      }

      /**
       * @method get
       * @param  {Number} i
       * @param  {Number} j
       * @return {Object}
       */
      TupleDictionary.prototype.get = function(i, j) {
          if (i > j) {
              // swap
              var temp = j;
              j = i;
              i = temp;
          }
          return this.data[i+'-'+j];
      };

      /**
       * @method set
       * @param  {Number} i
       * @param  {Number} j
       * @param {Object} value
       */
      TupleDictionary.prototype.set = function(i, j, value) {
          if (i > j) {
              var temp = j;
              j = i;
              i = temp;
          }
          var key = i+'-'+j;

          // Check if key already exists
          if(!this.get(i,j)){
              this.data.keys.push(key);
          }

          this.data[key] = value;
          return this.data[key];
      };

      /**
       * @method del
       * @param  {Number} i
       * @param  {Number} j
       * @returns {Boolean} is remove
       */
      TupleDictionary.prototype.del = function(i, j) {
          if (i > j) {
              var temp = j;
              j = i;
              i = temp;
          }
          var key = i+'-'+j;
          var index = this.data.keys.indexOf(key);
          if (index >= 0) {
              this.data.keys.splice(index, 1);
              delete this.data[key];
              return true;
          }
          return false;
      };

      /**
       * @method reset
       */
      TupleDictionary.prototype.reset = function() {
          this.data = { keys:[] };
      };

      /**
       * @method getLength
       */
      TupleDictionary.prototype.getLength = function() {
          return  this.data.keys.length;
      };

      /**
       * @method getKeyByIndex
       * @param {Number} index
       */
      TupleDictionary.prototype.getKeyByIndex = function(index) {
          return  this.data.keys[index];
      };

      /**
       * @method getDataByKey
       * @param {Number} Key
       */
      TupleDictionary.prototype.getDataByKey = function(Key) {
          return  this.data[Key];
      };
      },{}],54:[function(_dereq_,module,exports){
      function Utils(){}

      module.exports = Utils;

      /**
       * Extend an options object with default values.
       * @static
       * @method defaults
       * @param  {object} options The options object. May be falsy: in this case, a new object is created and returned.
       * @param  {object} defaults An object containing default values.
       * @return {object} The modified options object.
       */
      Utils.defaults = function(options, defaults){
          options = options || {};

          for(var key in defaults){
              if(!(key in options)){
                  options[key] = defaults[key];
              }
          }

          return options;
      };

      },{}],55:[function(_dereq_,module,exports){
      module.exports = Vec3Pool;

      var Vec3 = _dereq_('../math/Vec3');
      var Pool = _dereq_('./Pool');

      /**
       * @class Vec3Pool
       * @constructor
       * @extends Pool
       */
      function Vec3Pool(){
          Pool.call(this);
          this.type = Vec3;
      }
      Vec3Pool.prototype = new Pool();

      /**
       * Construct a vector
       * @method constructObject
       * @return {Vec3}
       */
      Vec3Pool.prototype.constructObject = function(){
          return new Vec3();
      };

      },{"../math/Vec3":31,"./Pool":52}],56:[function(_dereq_,module,exports){
      module.exports = Narrowphase;

      var AABB = _dereq_('../collision/AABB');
      _dereq_('../objects/Body');
      var Shape = _dereq_('../shapes/Shape');
      var Ray = _dereq_('../collision/Ray');
      var Vec3 = _dereq_('../math/Vec3');
      var Transform = _dereq_('../math/Transform');
      _dereq_('../shapes/ConvexPolyhedron');
      var Quaternion = _dereq_('../math/Quaternion');
      _dereq_('../solver/Solver');
      var Vec3Pool = _dereq_('../utils/Vec3Pool');
      var ContactEquation = _dereq_('../equations/ContactEquation');
      var FrictionEquation = _dereq_('../equations/FrictionEquation');

      /**
       * Helper class for the World. Generates ContactEquations.
       * @class Narrowphase
       * @constructor
       * @todo Sphere-ConvexPolyhedron contacts
       * @todo Contact reduction
       * @todo  should move methods to prototype
       */
      function Narrowphase(world){

          /**
           * Internal storage of pooled contact points.
           * @property {Array} contactPointPool
           */
          this.contactPointPool = [];

          this.frictionEquationPool = [];

          this.result = [];
          this.frictionResult = [];

          /**
           * Pooled vectors.
           * @property {Vec3Pool} v3pool
           */
          this.v3pool = new Vec3Pool();

          this.world = world;
          this.currentContactMaterial = null;

          /**
           * @property {Boolean} enableFrictionReduction
           */
          this.enableFrictionReduction = false;
      }

      /**
       * Make a contact object, by using the internal pool or creating a new one.
       * @method createContactEquation
       * @param {Body} bi
       * @param {Body} bj
       * @param {Shape} si
       * @param {Shape} sj
       * @param {Shape} overrideShapeA
       * @param {Shape} overrideShapeB
       * @return {ContactEquation}
       */
      Narrowphase.prototype.createContactEquation = function(bi, bj, si, sj, overrideShapeA, overrideShapeB){
          var c;
          if(this.contactPointPool.length){
              c = this.contactPointPool.pop();
              c.bi = bi;
              c.bj = bj;
          } else {
              c = new ContactEquation(bi, bj);
          }

          c.enabled = bi.collisionResponse && bj.collisionResponse && si.collisionResponse && sj.collisionResponse;

          var cm = this.currentContactMaterial;
          var relaxation = cm.contactEquationRelaxation;
          c.restitution = cm.restitution;

          var matA = si.material || bi.material;
          var matB = sj.material || bj.material;
          if(matA && matB){
              if(matA.restitution >= 0 && matB.restitution >= 0) {
                  c.restitution = matA.restitution * matB.restitution;
              }
              var oR = matA.correctInelastic || matB.correctInelastic;
              if (oR) relaxation *= oR;
          }

          c.setSpookParams(
              cm.contactEquationStiffness,
              relaxation,
              this.world.dt
          );

          c.si = overrideShapeA || si;
          c.sj = overrideShapeB || sj;

          return c;
      };

      Narrowphase.prototype.createFrictionEquationsFromContact = function(contactEquation, outArray){
          var bodyA = contactEquation.bi;
          var bodyB = contactEquation.bj;
          var shapeA = contactEquation.si;
          var shapeB = contactEquation.sj;

          var world = this.world;
          var cm = this.currentContactMaterial;

          // If friction or restitution were specified in the material, use them
          var friction = cm.friction;
          var matA = shapeA.material || bodyA.material;
          var matB = shapeB.material || bodyB.material;
          if(matA && matB && matA.friction >= 0 && matB.friction >= 0){
              friction = matA.friction * matB.friction;
          }

          if(friction > 0){

              // Create 2 tangent equations
              var mug = friction * world.gravity.length();
              var reducedMass = (bodyA.invMass + bodyB.invMass);
              if(reducedMass > 0){
                  reducedMass = 1/reducedMass;
              }
              var pool = this.frictionEquationPool;
              var c1 = pool.length ? pool.pop() : new FrictionEquation(bodyA,bodyB,mug*reducedMass);
              var c2 = pool.length ? pool.pop() : new FrictionEquation(bodyA,bodyB,mug*reducedMass);

              c1.bi = c2.bi = bodyA;
              c1.bj = c2.bj = bodyB;
              c1.minForce = c2.minForce = -mug*reducedMass;
              c1.maxForce = c2.maxForce = mug*reducedMass;

              // Copy over the relative vectors
              c1.ri.copy(contactEquation.ri);
              c1.rj.copy(contactEquation.rj);
              c2.ri.copy(contactEquation.ri);
              c2.rj.copy(contactEquation.rj);

              // Construct tangents
              contactEquation.ni.tangents(c1.t, c2.t);

              // Set spook params
              c1.setSpookParams(cm.frictionEquationStiffness, cm.frictionEquationRelaxation, world.dt);
              c2.setSpookParams(cm.frictionEquationStiffness, cm.frictionEquationRelaxation, world.dt);

              c1.enabled = c2.enabled = contactEquation.enabled;

              outArray.push(c1, c2);

              return true;
          }

          return false;
      };

      var averageNormal = new Vec3();
      var averageContactPointA = new Vec3();
      var averageContactPointB = new Vec3();

      // Take the average N latest contact point on the plane.
      Narrowphase.prototype.createFrictionFromAverage = function(numContacts){
          // The last contactEquation
          var c = this.result[this.result.length - 1];

          // Create the result: two "average" friction equations
          if (!this.createFrictionEquationsFromContact(c, this.frictionResult) || numContacts === 1) {
              return;
          }

          var f1 = this.frictionResult[this.frictionResult.length - 2];
          var f2 = this.frictionResult[this.frictionResult.length - 1];

          averageNormal.setZero();
          averageContactPointA.setZero();
          averageContactPointB.setZero();

          var bodyA = c.bi;
          c.bj;
          for(var i=0; i!==numContacts; i++){
              c = this.result[this.result.length - 1 - i];
              if(c.bodyA !== bodyA){
                  averageNormal.vadd(c.ni, averageNormal);
                  averageContactPointA.vadd(c.ri, averageContactPointA);
                  averageContactPointB.vadd(c.rj, averageContactPointB);
              } else {
                  averageNormal.vsub(c.ni, averageNormal);
                  averageContactPointA.vadd(c.rj, averageContactPointA);
                  averageContactPointB.vadd(c.ri, averageContactPointB);
              }
          }

          var invNumContacts = 1 / numContacts;
          averageContactPointA.scale(invNumContacts, f1.ri);
          averageContactPointB.scale(invNumContacts, f1.rj);
          f2.ri.copy(f1.ri); // Should be the same
          f2.rj.copy(f1.rj);
          averageNormal.normalize();
          averageNormal.tangents(f1.t, f2.t);
          // return eq;
      };


      var tmpVec1 = new Vec3();
      var tmpVec2 = new Vec3();
      var tmpQuat1 = new Quaternion();
      var tmpQuat2 = new Quaternion();

      /**
       * Generate all contacts between a list of body pairs
       * @method getContacts
       * @param {array} p1 Array of body indices
       * @param {array} p2 Array of body indices
       * @param {World} world
       * @param {array} result Array to store generated contacts
       * @param {array} oldcontacts Optional. Array of reusable contact objects
       */
      Narrowphase.prototype.getContacts = function(p1, p2, world, result, oldcontacts, frictionResult, frictionPool){
          // Save old contact objects
          this.contactPointPool = oldcontacts;
          this.frictionEquationPool = frictionPool;
          this.result = result;
          this.frictionResult = frictionResult;

          var qi = tmpQuat1;
          var qj = tmpQuat2;
          var xi = tmpVec1;
          var xj = tmpVec2;

          for(var k=0, N=p1.length; k!==N; k++){

              // Get current collision bodies
              var bi = p1[k],
                  bj = p2[k];

              // Get contact material
              var bodyContactMaterial = null;
              if(bi.material && bj.material){
                  bodyContactMaterial = world.getContactMaterial(bi.material,bj.material) || null;
              }

              // Allow get kinematic contact
              var justTest = ( bi.collisionResponse == false || bj.collisionResponse == false 
                  // || (
                  //     (bi.type & Body.KINEMATIC) && (bj.type & Body.STATIC)
                  // ) || (
                  //     (bi.type & Body.STATIC) && (bj.type & Body.KINEMATIC)
                  // ) || (
                  //     (bi.type & Body.KINEMATIC) && (bj.type & Body.KINEMATIC)
                  // )
              );

              for (var i = 0; i < bi.shapes.length; i++) {
                  bi.quaternion.mult(bi.shapeOrientations[i], qi);
                  bi.quaternion.vmult(bi.shapeOffsets[i], xi);
                  xi.vadd(bi.position, xi);
                  var si = bi.shapes[i];

                  for (var j = 0; j < bj.shapes.length; j++) {

                      // Compute world transform of shapes
                      bj.quaternion.mult(bj.shapeOrientations[j], qj);
                      bj.quaternion.vmult(bj.shapeOffsets[j], xj);
                      xj.vadd(bj.position, xj);
                      var sj = bj.shapes[j];

                      if(!((si.collisionFilterMask & sj.collisionFilterGroup) && (sj.collisionFilterMask & si.collisionFilterGroup))){
                          continue;
                      }

                      if(xi.distanceTo(xj) > si.boundingSphereRadius + sj.boundingSphereRadius){
                          continue;
                      }

                      // is trigger ? ,trigger test
                      justTest |= (si.collisionResponse == false) || (sj.collisionResponse == false);

                      // Get collision material
                      var shapeContactMaterial = null;
                      if(si.material && sj.material){
                          shapeContactMaterial = world.getContactMaterial(si.material,sj.material) || null;
                      }

                      this.currentContactMaterial = shapeContactMaterial || bodyContactMaterial || world.defaultContactMaterial;

                      // Get contacts
                      var resolver = this[si.type | sj.type];
                      if(resolver){
                          var retval = false;
                          if (si.type < sj.type) {
                              retval = resolver.call(this, si, sj, xi, xj, qi, qj, bi, bj, si, sj, justTest);
                          } else {
                              retval = resolver.call(this, sj, si, xj, xi, qj, qi, bj, bi, si, sj, justTest);
                          }

                          if(retval && justTest){
                              // Register overlap
                              world.shapeOverlapKeeper.set(si.id, sj.id);
                              world.bodyOverlapKeeper.set(bi.id, bj.id);
                              var data = {si:si, sj:sj};
                              world.triggerDic.set(si.id, sj.id, data);
                              world.oldTriggerDic.set(si.id, sj.id, data);
                          }
                      }
                  }
              }
          }
      };

      Narrowphase.prototype[Shape.types.BOX | Shape.types.BOX] =
      Narrowphase.prototype.boxBox = function(si,sj,xi,xj,qi,qj,bi,bj,rsi,rsj,justTest){
          si.convexPolyhedronRepresentation.material = si.material;
          sj.convexPolyhedronRepresentation.material = sj.material;
          si.convexPolyhedronRepresentation.collisionResponse = si.collisionResponse;
          sj.convexPolyhedronRepresentation.collisionResponse = sj.collisionResponse;
          return this.convexConvex(si.convexPolyhedronRepresentation,sj.convexPolyhedronRepresentation,xi,xj,qi,qj,bi,bj,si,sj,justTest);
      };

      Narrowphase.prototype[Shape.types.BOX | Shape.types.CONVEXPOLYHEDRON] =
      Narrowphase.prototype.boxConvex = function(si,sj,xi,xj,qi,qj,bi,bj,rsi,rsj,justTest){
          si.convexPolyhedronRepresentation.material = si.material;
          si.convexPolyhedronRepresentation.collisionResponse = si.collisionResponse;
          return this.convexConvex(si.convexPolyhedronRepresentation,sj,xi,xj,qi,qj,bi,bj,si,sj,justTest);
      };

      Narrowphase.prototype[Shape.types.BOX | Shape.types.PARTICLE] =
      Narrowphase.prototype.boxParticle = function(si,sj,xi,xj,qi,qj,bi,bj,rsi,rsj,justTest){
          si.convexPolyhedronRepresentation.material = si.material;
          si.convexPolyhedronRepresentation.collisionResponse = si.collisionResponse;
          return this.convexParticle(si.convexPolyhedronRepresentation,sj,xi,xj,qi,qj,bi,bj,si,sj,justTest);
      };

      /**
       * @method sphereSphere
       * @param  {Shape}      si
       * @param  {Shape}      sj
       * @param  {Vec3}       xi
       * @param  {Vec3}       xj
       * @param  {Quaternion} qi
       * @param  {Quaternion} qj
       * @param  {Body}       bi
       * @param  {Body}       bj
       */
      Narrowphase.prototype[Shape.types.SPHERE] =
      Narrowphase.prototype.sphereSphere = function(si,sj,xi,xj,qi,qj,bi,bj,rsi,rsj,justTest){
          if(justTest){
              return xi.distanceSquared(xj) < Math.pow(si.radius + sj.radius, 2);
          }

          // We will have only one contact in this case
          var r = this.createContactEquation(bi,bj,si,sj,rsi,rsj);

          // Contact normal
          xj.vsub(xi, r.ni);
          r.ni.normalize();

          // Contact point locations
          r.ri.copy(r.ni);
          r.rj.copy(r.ni);
          r.ri.mult(si.radius, r.ri);
          r.rj.mult(-sj.radius, r.rj);

          r.ri.vadd(xi, r.ri);
          r.ri.vsub(bi.position, r.ri);

          r.rj.vadd(xj, r.rj);
          r.rj.vsub(bj.position, r.rj);

          this.result.push(r);

          this.createFrictionEquationsFromContact(r, this.frictionResult);
      };

      /**
       * @method planeTrimesh
       * @param  {Shape}      si
       * @param  {Shape}      sj
       * @param  {Vec3}       xi
       * @param  {Vec3}       xj
       * @param  {Quaternion} qi
       * @param  {Quaternion} qj
       * @param  {Body}       bi
       * @param  {Body}       bj
       */
      var planeTrimesh_normal = new Vec3();
      var planeTrimesh_relpos = new Vec3();
      var planeTrimesh_projected = new Vec3();
      Narrowphase.prototype[Shape.types.PLANE | Shape.types.TRIMESH] =
      Narrowphase.prototype.planeTrimesh = function(
          planeShape,
          trimeshShape,
          planePos,
          trimeshPos,
          planeQuat,
          trimeshQuat,
          planeBody,
          trimeshBody,
          rsi,
          rsj,
          justTest
      ){
          // Make contacts!
          var v = new Vec3();

          var normal = planeTrimesh_normal;
          normal.set(0,0,1);
          planeQuat.vmult(normal,normal); // Turn normal according to plane

          for(var i=0; i<trimeshShape.vertices.length / 3; i++){

              // Get world vertex from trimesh
              trimeshShape.getVertex(i, v);

              // Safe up
              var v2 = new Vec3();
              v2.copy(v);
              Transform.pointToWorldFrame(trimeshPos, trimeshQuat, v2, v);

              // Check plane side
              var relpos = planeTrimesh_relpos;
              v.vsub(planePos, relpos);
              var dot = normal.dot(relpos);

              if(dot <= 0.0){
                  if(justTest){
                      return true;
                  }

                  var r = this.createContactEquation(planeBody,trimeshBody,planeShape,trimeshShape,rsi,rsj);

                  r.ni.copy(normal); // Contact normal is the plane normal

                  // Get vertex position projected on plane
                  var projected = planeTrimesh_projected;
                  normal.scale(relpos.dot(normal), projected);
                  v.vsub(projected,projected);

                  // ri is the projected world position minus plane position
                  r.ri.copy(projected);
                  r.ri.vsub(planeBody.position, r.ri);

                  r.rj.copy(v);
                  r.rj.vsub(trimeshBody.position, r.rj);

                  // Store result
                  this.result.push(r);
                  this.createFrictionEquationsFromContact(r, this.frictionResult);
              }
          }
      };

      /**
       * @method sphereTrimesh
       * @param  {Shape}      sphereShape
       * @param  {Shape}      trimeshShape
       * @param  {Vec3}       spherePos
       * @param  {Vec3}       trimeshPos
       * @param  {Quaternion} sphereQuat
       * @param  {Quaternion} trimeshQuat
       * @param  {Body}       sphereBody
       * @param  {Body}       trimeshBody
       */
      var sphereTrimesh_normal = new Vec3();
      var sphereTrimesh_relpos = new Vec3();
      new Vec3();
      var sphereTrimesh_v = new Vec3();
      var sphereTrimesh_v2 = new Vec3();
      var sphereTrimesh_edgeVertexA = new Vec3();
      var sphereTrimesh_edgeVertexB = new Vec3();
      var sphereTrimesh_edgeVector = new Vec3();
      var sphereTrimesh_edgeVectorUnit = new Vec3();
      var sphereTrimesh_localSpherePos = new Vec3();
      var sphereTrimesh_tmp = new Vec3();
      var sphereTrimesh_va = new Vec3();
      var sphereTrimesh_vb = new Vec3();
      var sphereTrimesh_vc = new Vec3();
      var sphereTrimesh_localSphereAABB = new AABB();
      var sphereTrimesh_triangles = [];
      Narrowphase.prototype[Shape.types.SPHERE | Shape.types.TRIMESH] =
      Narrowphase.prototype.sphereTrimesh = function (
          sphereShape,
          trimeshShape,
          spherePos,
          trimeshPos,
          sphereQuat,
          trimeshQuat,
          sphereBody,
          trimeshBody,
          rsi,
          rsj,
          justTest
      ) {

          var edgeVertexA = sphereTrimesh_edgeVertexA;
          var edgeVertexB = sphereTrimesh_edgeVertexB;
          var edgeVector = sphereTrimesh_edgeVector;
          var edgeVectorUnit = sphereTrimesh_edgeVectorUnit;
          var localSpherePos = sphereTrimesh_localSpherePos;
          var tmp = sphereTrimesh_tmp;
          var localSphereAABB = sphereTrimesh_localSphereAABB;
          var v2 = sphereTrimesh_v2;
          var relpos = sphereTrimesh_relpos;
          var triangles = sphereTrimesh_triangles;

          // Convert sphere position to local in the trimesh
          Transform.pointToLocalFrame(trimeshPos, trimeshQuat, spherePos, localSpherePos);

          // Get the aabb of the sphere locally in the trimesh
          var sphereRadius = sphereShape.radius;
          localSphereAABB.lowerBound.set(
              localSpherePos.x - sphereRadius,
              localSpherePos.y - sphereRadius,
              localSpherePos.z - sphereRadius
          );
          localSphereAABB.upperBound.set(
              localSpherePos.x + sphereRadius,
              localSpherePos.y + sphereRadius,
              localSpherePos.z + sphereRadius
          );

          trimeshShape.getTrianglesInAABB(localSphereAABB, triangles);
          //for (var i = 0; i < trimeshShape.indices.length / 3; i++) triangles.push(i); // All

          // Vertices
          var v = sphereTrimesh_v;
          var radiusSquared = sphereShape.radius * sphereShape.radius;
          for(var i=0; i<triangles.length; i++){
              for (var j = 0; j < 3; j++) {

                  trimeshShape.getVertex(trimeshShape.indices[triangles[i] * 3 + j], v);

                  // Check vertex overlap in sphere
                  v.vsub(localSpherePos, relpos);

                  if(relpos.norm2() <= radiusSquared){

                      // Safe up
                      v2.copy(v);
                      Transform.pointToWorldFrame(trimeshPos, trimeshQuat, v2, v);

                      v.vsub(spherePos, relpos);

                      if(justTest){
                          return true;
                      }

                      var r = this.createContactEquation(sphereBody,trimeshBody,sphereShape,trimeshShape,rsi,rsj);
                      r.ni.copy(relpos);
                      r.ni.normalize();

                      // ri is the vector from sphere center to the sphere surface
                      r.ri.copy(r.ni);
                      r.ri.scale(sphereShape.radius, r.ri);
                      r.ri.vadd(spherePos, r.ri);
                      r.ri.vsub(sphereBody.position, r.ri);

                      r.rj.copy(v);
                      r.rj.vsub(trimeshBody.position, r.rj);

                      // Store result
                      this.result.push(r);
                      this.createFrictionEquationsFromContact(r, this.frictionResult);
                  }
              }
          }

          // Check all edges
          for(var i=0; i<triangles.length; i++){
              for (var j = 0; j < 3; j++) {

                  trimeshShape.getVertex(trimeshShape.indices[triangles[i] * 3 + j], edgeVertexA);
                  trimeshShape.getVertex(trimeshShape.indices[triangles[i] * 3 + ((j+1)%3)], edgeVertexB);
                  edgeVertexB.vsub(edgeVertexA, edgeVector);

                  // Project sphere position to the edge
                  localSpherePos.vsub(edgeVertexB, tmp);
                  var positionAlongEdgeB = tmp.dot(edgeVector);

                  localSpherePos.vsub(edgeVertexA, tmp);
                  var positionAlongEdgeA = tmp.dot(edgeVector);

                  if(positionAlongEdgeA > 0 && positionAlongEdgeB < 0){

                      // Now check the orthogonal distance from edge to sphere center
                      localSpherePos.vsub(edgeVertexA, tmp);

                      edgeVectorUnit.copy(edgeVector);
                      edgeVectorUnit.normalize();
                      positionAlongEdgeA = tmp.dot(edgeVectorUnit);

                      edgeVectorUnit.scale(positionAlongEdgeA, tmp);
                      tmp.vadd(edgeVertexA, tmp);

                      // tmp is now the sphere center position projected to the edge, defined locally in the trimesh frame
                      var dist = tmp.distanceTo(localSpherePos);
                      if(dist < sphereShape.radius){

                          if(justTest){
                              return true;
                          }

                          var r = this.createContactEquation(sphereBody, trimeshBody, sphereShape, trimeshShape,rsi,rsj);

                          tmp.vsub(localSpherePos, r.ni);
                          r.ni.normalize();
                          r.ni.scale(sphereShape.radius, r.ri);

                          Transform.pointToWorldFrame(trimeshPos, trimeshQuat, tmp, tmp);
                          tmp.vsub(trimeshBody.position, r.rj);

                          Transform.vectorToWorldFrame(trimeshQuat, r.ni, r.ni);
                          Transform.vectorToWorldFrame(trimeshQuat, r.ri, r.ri);

                          this.result.push(r);
                          this.createFrictionEquationsFromContact(r, this.frictionResult);
                      }
                  }
              }
          }

          // Triangle faces
          var va = sphereTrimesh_va;
          var vb = sphereTrimesh_vb;
          var vc = sphereTrimesh_vc;
          var normal = sphereTrimesh_normal;
          for(var i=0, N = triangles.length; i !== N; i++){
              trimeshShape.getTriangleVertices(triangles[i], va, vb, vc);
              trimeshShape.getNormal(triangles[i], normal);
              localSpherePos.vsub(va, tmp);
              var dist = tmp.dot(normal);
              normal.scale(dist, tmp);
              localSpherePos.vsub(tmp, tmp);

              // tmp is now the sphere position projected to the triangle plane
              dist = tmp.distanceTo(localSpherePos);
              if(Ray.pointInTriangle(tmp, va, vb, vc) && dist < sphereShape.radius){
                  if(justTest){
                      return true;
                  }
                  var r = this.createContactEquation(sphereBody, trimeshBody, sphereShape, trimeshShape,rsi,rsj);

                  tmp.vsub(localSpherePos, r.ni);
                  r.ni.normalize();
                  r.ni.scale(sphereShape.radius, r.ri);

                  Transform.pointToWorldFrame(trimeshPos, trimeshQuat, tmp, tmp);
                  tmp.vsub(trimeshBody.position, r.rj);

                  Transform.vectorToWorldFrame(trimeshQuat, r.ni, r.ni);
                  Transform.vectorToWorldFrame(trimeshQuat, r.ri, r.ri);

                  this.result.push(r);
                  this.createFrictionEquationsFromContact(r, this.frictionResult);
              }
          }

          triangles.length = 0;
      };

      var point_on_plane_to_sphere = new Vec3();
      var plane_to_sphere_ortho = new Vec3();
      var p_s_ni = new Vec3(); 
      var p_s_ri = new Vec3();
      var p_s_rj = new Vec3(); 
      /**
       * @method spherePlane
       * @param  {Shape}      si
       * @param  {Shape}      sj
       * @param  {Vec3}       xi
       * @param  {Vec3}       xj
       * @param  {Quaternion} qi
       * @param  {Quaternion} qj
       * @param  {Body}       bi
       * @param  {Body}       bj
       */
      Narrowphase.prototype[Shape.types.SPHERE | Shape.types.PLANE] =
      Narrowphase.prototype.spherePlane = function(si,sj,xi,xj,qi,qj,bi,bj,rsi,rsj,justTest){
          // Contact normal
          p_s_ni.set(0,0,1);
          qj.vmult(p_s_ni, p_s_ni);
          p_s_ni.negate(p_s_ni); // body i is the sphere, flip normal
          p_s_ni.normalize(); // Needed?

          // Vector from sphere center to contact point
          p_s_ni.mult(si.radius, p_s_ri);

          // Project down sphere on plane
          xi.vsub(xj, point_on_plane_to_sphere);
          p_s_ni.mult(p_s_ni.dot(point_on_plane_to_sphere), plane_to_sphere_ortho);
          point_on_plane_to_sphere.vsub(plane_to_sphere_ortho, p_s_rj); // The sphere position projected to plane

          if(-point_on_plane_to_sphere.dot(p_s_ni) <= si.radius){

              if(justTest){
                  return true;
              }

              // We will have one contact in this case
              var r = this.createContactEquation(bi,bj,si,sj,rsi,rsj);
              // Make it relative to the body
              r.ni.copy(p_s_ni);r.ri.copy(p_s_ri);r.rj.copy(p_s_rj);
              var ri = r.ri;
              var rj = r.rj;
              ri.vadd(xi, ri);
              ri.vsub(bi.position, ri);
              rj.vadd(xj, rj);
              rj.vsub(bj.position, rj);

              this.result.push(r);
              this.createFrictionEquationsFromContact(r, this.frictionResult);
          }
          return false;
      };

      // See http://bulletphysics.com/Bullet/BulletFull/SphereTriangleDetector_8cpp_source.html
      var pointInPolygon_edge = new Vec3();
      var pointInPolygon_edge_x_normal = new Vec3();
      var pointInPolygon_vtp = new Vec3();
      function pointInPolygon(verts, normal, p){
          var positiveResult = null;
          var N = verts.length;
          for(var i=0; i!==N; i++){
              var v = verts[i];

              // Get edge to the next vertex
              var edge = pointInPolygon_edge;
              verts[(i+1) % (N)].vsub(v,edge);

              // Get cross product between polygon normal and the edge
              var edge_x_normal = pointInPolygon_edge_x_normal;
              //var edge_x_normal = new Vec3();
              edge.cross(normal,edge_x_normal);

              // Get vector between point and current vertex
              var vertex_to_p = pointInPolygon_vtp;
              p.vsub(v,vertex_to_p);

              // This dot product determines which side of the edge the point is
              var r = edge_x_normal.dot(vertex_to_p);

              // If all such dot products have same sign, we are inside the polygon.
              if(positiveResult===null || (r>0 && positiveResult===true) || (r<=0 && positiveResult===false)){
                  if(positiveResult===null){
                      positiveResult = r>0;
                  }
                  continue;
              } else {
                  return false; // Encountered some other sign. Exit.
              }
          }

          // If we got here, all dot products were of the same sign.
          return true;
      }

      var box_to_sphere = new Vec3();
      var sphereBox_ns = new Vec3();
      var sphereBox_ns1 = new Vec3();
      var sphereBox_ns2 = new Vec3();
      var sphereBox_sides = [new Vec3(),new Vec3(),new Vec3(),new Vec3(),new Vec3(),new Vec3()];
      var sphereBox_sphere_to_corner = new Vec3();
      var sphereBox_side_ns = new Vec3();
      var sphereBox_side_ns1 = new Vec3();
      var sphereBox_side_ns2 = new Vec3();

      /**
       * @method sphereBox
       * @param  {Shape}      si
       * @param  {Shape}      sj
       * @param  {Vec3}       xi
       * @param  {Vec3}       xj
       * @param  {Quaternion} qi
       * @param  {Quaternion} qj
       * @param  {Body}       bi
       * @param  {Body}       bj
       */
      Narrowphase.prototype[Shape.types.SPHERE | Shape.types.BOX] =
      Narrowphase.prototype.sphereBox = function(si,sj,xi,xj,qi,qj,bi,bj,rsi,rsj,justTest){
          var v3pool = this.v3pool;

          // we refer to the box as body j
          var sides = sphereBox_sides;
          xi.vsub(xj,box_to_sphere);
          sj.getSideNormals(sides,qj);
          var R =     si.radius;

          // Check side (plane) intersections
          var found = false;

          // Store the resulting side penetration info
          var side_ns = sphereBox_side_ns;
          var side_ns1 = sphereBox_side_ns1;
          var side_ns2 = sphereBox_side_ns2;
          var side_h = null;
          var side_penetrations = 0;
          var side_dot1 = 0;
          var side_dot2 = 0;
          var side_distance = null;
          for(var idx=0,nsides=sides.length; idx!==nsides && found===false; idx++){
              // Get the plane side normal (ns)
              var ns = sphereBox_ns;
              ns.copy(sides[idx]);

              var h = ns.norm();
              ns.normalize();

              // The normal/distance dot product tells which side of the plane we are
              var dot = box_to_sphere.dot(ns);

              if(dot<h+R && dot>0){
                  // Intersects plane. Now check the other two dimensions
                  var ns1 = sphereBox_ns1;
                  var ns2 = sphereBox_ns2;
                  ns1.copy(sides[(idx+1)%3]);
                  ns2.copy(sides[(idx+2)%3]);
                  var h1 = ns1.norm();
                  var h2 = ns2.norm();
                  ns1.normalize();
                  ns2.normalize();
                  var dot1 = box_to_sphere.dot(ns1);
                  var dot2 = box_to_sphere.dot(ns2);
                  if(dot1<h1 && dot1>-h1 && dot2<h2 && dot2>-h2){
                      var dist = Math.abs(dot-h-R);
                      if(side_distance===null || dist < side_distance){
                          side_distance = dist;
                          side_dot1 = dot1;
                          side_dot2 = dot2;
                          side_h = h;
                          side_ns.copy(ns);
                          side_ns1.copy(ns1);
                          side_ns2.copy(ns2);
                          side_penetrations++;

                          if(justTest){
                              return true;
                          }
                      }
                  }
              }
          }
          if(side_penetrations){
              found = true;
              var r = this.createContactEquation(bi,bj,si,sj,rsi,rsj);
              side_ns.mult(-R,r.ri); // Sphere r
              r.ni.copy(side_ns);
              r.ni.negate(r.ni); // Normal should be out of sphere
              side_ns.mult(side_h,side_ns);
              side_ns1.mult(side_dot1,side_ns1);
              side_ns.vadd(side_ns1,side_ns);
              side_ns2.mult(side_dot2,side_ns2);
              side_ns.vadd(side_ns2,r.rj);

              // Make relative to bodies
              r.ri.vadd(xi, r.ri);
              r.ri.vsub(bi.position, r.ri);
              r.rj.vadd(xj, r.rj);
              r.rj.vsub(bj.position, r.rj);

              this.result.push(r);
              this.createFrictionEquationsFromContact(r, this.frictionResult);
          }

          // Check corners
          var rj = v3pool.get();
          var sphere_to_corner = sphereBox_sphere_to_corner;
          for(var j=0; j!==2 && !found; j++){
              for(var k=0; k!==2 && !found; k++){
                  for(var l=0; l!==2 && !found; l++){
                      rj.set(0,0,0);
                      if(j){
                          rj.vadd(sides[0],rj);
                      } else {
                          rj.vsub(sides[0],rj);
                      }
                      if(k){
                          rj.vadd(sides[1],rj);
                      } else {
                          rj.vsub(sides[1],rj);
                      }
                      if(l){
                          rj.vadd(sides[2],rj);
                      } else {
                          rj.vsub(sides[2],rj);
                      }

                      // World position of corner
                      xj.vadd(rj,sphere_to_corner);
                      sphere_to_corner.vsub(xi,sphere_to_corner);

                      if(sphere_to_corner.norm2() < R*R){
                          if(justTest){
                              return true;
                          }
                          found = true;
                          var r = this.createContactEquation(bi,bj,si,sj,rsi,rsj);
                          r.ri.copy(sphere_to_corner);
                          r.ri.normalize();
                          r.ni.copy(r.ri);
                          r.ri.mult(R,r.ri);
                          r.rj.copy(rj);

                          // Make relative to bodies
                          r.ri.vadd(xi, r.ri);
                          r.ri.vsub(bi.position, r.ri);
                          r.rj.vadd(xj, r.rj);
                          r.rj.vsub(bj.position, r.rj);

                          this.result.push(r);
                          this.createFrictionEquationsFromContact(r, this.frictionResult);
                      }
                  }
              }
          }
          v3pool.release(rj);
          rj = null;

          // Check edges
          var edgeTangent = v3pool.get();
          var edgeCenter = v3pool.get();
          var r = v3pool.get(); // r = edge center to sphere center
          var orthogonal = v3pool.get();
          var dist = v3pool.get();
          var Nsides = sides.length;
          for(var j=0; j!==Nsides && !found; j++){
              for(var k=0; k!==Nsides && !found; k++){
                  if(j%3 !== k%3){
                      // Get edge tangent
                      sides[k].cross(sides[j],edgeTangent);
                      edgeTangent.normalize();
                      sides[j].vadd(sides[k], edgeCenter);
                      r.copy(xi);
                      r.vsub(edgeCenter,r);
                      r.vsub(xj,r);
                      var orthonorm = r.dot(edgeTangent); // distance from edge center to sphere center in the tangent direction
                      edgeTangent.mult(orthonorm,orthogonal); // Vector from edge center to sphere center in the tangent direction

                      // Find the third side orthogonal to this one
                      var l = 0;
                      while(l===j%3 || l===k%3){
                          l++;
                      }

                      // vec from edge center to sphere projected to the plane orthogonal to the edge tangent
                      dist.copy(xi);
                      dist.vsub(orthogonal,dist);
                      dist.vsub(edgeCenter,dist);
                      dist.vsub(xj,dist);

                      // Distances in tangent direction and distance in the plane orthogonal to it
                      var tdist = Math.abs(orthonorm);
                      var ndist = dist.norm();

                      if(tdist < sides[l].norm() && ndist<R){
                          if(justTest){
                              return true;
                          }
                          found = true;
                          var res = this.createContactEquation(bi,bj,si,sj,rsi,rsj);
                          edgeCenter.vadd(orthogonal,res.rj); // box rj
                          res.rj.copy(res.rj);
                          dist.negate(res.ni);
                          res.ni.normalize();

                          res.ri.copy(res.rj);
                          res.ri.vadd(xj,res.ri);
                          res.ri.vsub(xi,res.ri);
                          res.ri.normalize();
                          res.ri.mult(R,res.ri);

                          // Make relative to bodies
                          res.ri.vadd(xi, res.ri);
                          res.ri.vsub(bi.position, res.ri);
                          res.rj.vadd(xj, res.rj);
                          res.rj.vsub(bj.position, res.rj);

                          this.result.push(res);
                          this.createFrictionEquationsFromContact(res, this.frictionResult);
                      }
                  }
              }
          }
          v3pool.release(edgeTangent,edgeCenter,r,orthogonal,dist);
      };

      var convex_to_sphere = new Vec3();
      var sphereConvex_edge = new Vec3();
      var sphereConvex_edgeUnit = new Vec3();
      var sphereConvex_sphereToCorner = new Vec3();
      var sphereConvex_worldCorner = new Vec3();
      var sphereConvex_worldNormal = new Vec3();
      var sphereConvex_worldPoint = new Vec3();
      var sphereConvex_worldSpherePointClosestToPlane = new Vec3();
      var sphereConvex_penetrationVec = new Vec3();
      var sphereConvex_sphereToWorldPoint = new Vec3();

      /**
       * @method sphereConvex
       * @param  {Shape}      si
       * @param  {Shape}      sj
       * @param  {Vec3}       xi
       * @param  {Vec3}       xj
       * @param  {Quaternion} qi
       * @param  {Quaternion} qj
       * @param  {Body}       bi
       * @param  {Body}       bj
       */
      Narrowphase.prototype[Shape.types.SPHERE | Shape.types.CONVEXPOLYHEDRON] =
      Narrowphase.prototype.sphereConvex = function(si,sj,xi,xj,qi,qj,bi,bj,rsi,rsj,justTest){
          var v3pool = this.v3pool;
          xi.vsub(xj,convex_to_sphere);
          var normals = sj.faceNormals;
          var faces = sj.faces;
          var verts = sj.vertices;
          var R =     si.radius;

          // if(convex_to_sphere.norm2() > si.boundingSphereRadius + sj.boundingSphereRadius){
          //     return;
          // }

          // Check corners
          for(var i=0; i!==verts.length; i++){
              var v = verts[i];

              // World position of corner
              var worldCorner = sphereConvex_worldCorner;
              qj.vmult(v,worldCorner);
              xj.vadd(worldCorner,worldCorner);
              var sphere_to_corner = sphereConvex_sphereToCorner;
              worldCorner.vsub(xi, sphere_to_corner);
              if(sphere_to_corner.norm2() < R * R){
                  if(justTest){
                      return true;
                  }
                  found = true;
                  var r = this.createContactEquation(bi,bj,si,sj,rsi,rsj);
                  r.ri.copy(sphere_to_corner);
                  r.ri.normalize();
                  r.ni.copy(r.ri);
                  r.ri.mult(R,r.ri);
                  worldCorner.vsub(xj,r.rj);

                  // Should be relative to the body.
                  r.ri.vadd(xi, r.ri);
                  r.ri.vsub(bi.position, r.ri);

                  // Should be relative to the body.
                  r.rj.vadd(xj, r.rj);
                  r.rj.vsub(bj.position, r.rj);

                  this.result.push(r);
                  this.createFrictionEquationsFromContact(r, this.frictionResult);
                  return;
              }
          }

          // Check side (plane) intersections
          var found = false;
          for(var i=0, nfaces=faces.length; i!==nfaces && found===false; i++){
              var normal = normals[i];
              var face = faces[i];

              // Get world-transformed normal of the face
              var worldNormal = sphereConvex_worldNormal;
              qj.vmult(normal,worldNormal);

              // Get a world vertex from the face
              var worldPoint = sphereConvex_worldPoint;
              qj.vmult(verts[face[0]],worldPoint);
              worldPoint.vadd(xj,worldPoint);

              // Get a point on the sphere, closest to the face normal
              var worldSpherePointClosestToPlane = sphereConvex_worldSpherePointClosestToPlane;
              worldNormal.mult(-R, worldSpherePointClosestToPlane);
              xi.vadd(worldSpherePointClosestToPlane, worldSpherePointClosestToPlane);

              // Vector from a face point to the closest point on the sphere
              var penetrationVec = sphereConvex_penetrationVec;
              worldSpherePointClosestToPlane.vsub(worldPoint,penetrationVec);

              // The penetration. Negative value means overlap.
              var penetration = penetrationVec.dot(worldNormal);

              var worldPointToSphere = sphereConvex_sphereToWorldPoint;
              xi.vsub(worldPoint, worldPointToSphere);

              if(penetration < 0 && worldPointToSphere.dot(worldNormal)>0){
                  // Intersects plane. Now check if the sphere is inside the face polygon
                  var faceVerts = []; // Face vertices, in world coords
                  for(var j=0, Nverts=face.length; j!==Nverts; j++){
                      var worldVertex = v3pool.get();
                      qj.vmult(verts[face[j]], worldVertex);
                      xj.vadd(worldVertex,worldVertex);
                      faceVerts.push(worldVertex);
                  }

                  if(pointInPolygon(faceVerts,worldNormal,xi)){ // Is the sphere center in the face polygon?
                      if(justTest){
                          return true;
                      }
                      found = true;
                      var r = this.createContactEquation(bi,bj,si,sj,rsi,rsj);

                      worldNormal.mult(-R, r.ri); // Contact offset, from sphere center to contact
                      worldNormal.negate(r.ni); // Normal pointing out of sphere

                      var penetrationVec2 = v3pool.get();
                      worldNormal.mult(-penetration, penetrationVec2);
                      var penetrationSpherePoint = v3pool.get();
                      worldNormal.mult(-R, penetrationSpherePoint);

                      //xi.vsub(xj).vadd(penetrationSpherePoint).vadd(penetrationVec2 , r.rj);
                      xi.vsub(xj,r.rj);
                      r.rj.vadd(penetrationSpherePoint,r.rj);
                      r.rj.vadd(penetrationVec2 , r.rj);

                      // Should be relative to the body.
                      r.rj.vadd(xj, r.rj);
                      r.rj.vsub(bj.position, r.rj);

                      // Should be relative to the body.
                      r.ri.vadd(xi, r.ri);
                      r.ri.vsub(bi.position, r.ri);

                      v3pool.release(penetrationVec2);
                      v3pool.release(penetrationSpherePoint);

                      this.result.push(r);
                      this.createFrictionEquationsFromContact(r, this.frictionResult);

                      // Release world vertices
                      for(var j=0, Nfaceverts=faceVerts.length; j!==Nfaceverts; j++){
                          v3pool.release(faceVerts[j]);
                      }

                      return; // We only expect *one* face contact
                  } else {
                      // Edge?
                      for(var j=0; j!==face.length; j++){

                          // Get two world transformed vertices
                          var v1 = v3pool.get();
                          var v2 = v3pool.get();
                          qj.vmult(verts[face[(j+1)%face.length]], v1);
                          qj.vmult(verts[face[(j+2)%face.length]], v2);
                          xj.vadd(v1, v1);
                          xj.vadd(v2, v2);

                          // Construct edge vector
                          var edge = sphereConvex_edge;
                          v2.vsub(v1,edge);

                          // Construct the same vector, but normalized
                          var edgeUnit = sphereConvex_edgeUnit;
                          edge.unit(edgeUnit);

                          // p is xi projected onto the edge
                          var p = v3pool.get();
                          var v1_to_xi = v3pool.get();
                          xi.vsub(v1, v1_to_xi);
                          var dot = v1_to_xi.dot(edgeUnit);
                          edgeUnit.mult(dot, p);
                          p.vadd(v1, p);

                          // Compute a vector from p to the center of the sphere
                          var xi_to_p = v3pool.get();
                          p.vsub(xi, xi_to_p);

                          // Collision if the edge-sphere distance is less than the radius
                          // AND if p is in between v1 and v2
                          if(dot > 0 && dot*dot<edge.norm2() && xi_to_p.norm2() < R*R){ // Collision if the edge-sphere distance is less than the radius
                              // Edge contact!
                              if(justTest){
                                  return true;
                              }
                              var r = this.createContactEquation(bi,bj,si,sj,rsi,rsj);
                              p.vsub(xj,r.rj);

                              p.vsub(xi,r.ni);
                              r.ni.normalize();

                              r.ni.mult(R,r.ri);

                              // Should be relative to the body.
                              r.rj.vadd(xj, r.rj);
                              r.rj.vsub(bj.position, r.rj);

                              // Should be relative to the body.
                              r.ri.vadd(xi, r.ri);
                              r.ri.vsub(bi.position, r.ri);

                              this.result.push(r);
                              this.createFrictionEquationsFromContact(r, this.frictionResult);

                              // Release world vertices
                              for(var j=0, Nfaceverts=faceVerts.length; j!==Nfaceverts; j++){
                                  v3pool.release(faceVerts[j]);
                              }

                              v3pool.release(v1);
                              v3pool.release(v2);
                              v3pool.release(p);
                              v3pool.release(xi_to_p);
                              v3pool.release(v1_to_xi);

                              return;
                          }

                          v3pool.release(v1);
                          v3pool.release(v2);
                          v3pool.release(p);
                          v3pool.release(xi_to_p);
                          v3pool.release(v1_to_xi);
                      }
                  }

                  // Release world vertices
                  for(var j=0, Nfaceverts=faceVerts.length; j!==Nfaceverts; j++){
                      v3pool.release(faceVerts[j]);
                  }
              }
          }
      };

      new Vec3();
      new Vec3();

      /**
       * @method planeBox
       * @param  {Array}      result
       * @param  {Shape}      si
       * @param  {Shape}      sj
       * @param  {Vec3}       xi
       * @param  {Vec3}       xj
       * @param  {Quaternion} qi
       * @param  {Quaternion} qj
       * @param  {Body}       bi
       * @param  {Body}       bj
       */
      Narrowphase.prototype[Shape.types.PLANE | Shape.types.BOX] =
      Narrowphase.prototype.planeBox = function(si,sj,xi,xj,qi,qj,bi,bj,rsi,rsj,justTest){
          sj.convexPolyhedronRepresentation.material = sj.material;
          sj.convexPolyhedronRepresentation.collisionResponse = sj.collisionResponse;
          sj.convexPolyhedronRepresentation.id = sj.id;
          return this.planeConvex(si,sj.convexPolyhedronRepresentation,xi,xj,qi,qj,bi,bj,si,sj,justTest);
      };

      var planeConvex_v = new Vec3();
      var planeConvex_normal = new Vec3();
      var planeConvex_relpos = new Vec3();
      var planeConvex_projected = new Vec3();

      /**
       * @method planeConvex
       * @param  {Shape}      si
       * @param  {Shape}      sj
       * @param  {Vec3}       xi
       * @param  {Vec3}       xj
       * @param  {Quaternion} qi
       * @param  {Quaternion} qj
       * @param  {Body}       bi
       * @param  {Body}       bj
       */
      Narrowphase.prototype[Shape.types.PLANE | Shape.types.CONVEXPOLYHEDRON] =
      Narrowphase.prototype.planeConvex = function(
          planeShape,
          convexShape,
          planePosition,
          convexPosition,
          planeQuat,
          convexQuat,
          planeBody,
          convexBody,
          si,
          sj,
          justTest
      ){
          // Simply return the points behind the plane.
          var worldVertex = planeConvex_v,
              worldNormal = planeConvex_normal;
          worldNormal.set(0,0,1);
          planeQuat.vmult(worldNormal,worldNormal); // Turn normal according to plane orientation

          var numContacts = 0;
          var relpos = planeConvex_relpos;
          for(var i = 0; i !== convexShape.vertices.length; i++){

              // Get world convex vertex
              worldVertex.copy(convexShape.vertices[i]);
              convexQuat.vmult(worldVertex, worldVertex);
              convexPosition.vadd(worldVertex, worldVertex);
              worldVertex.vsub(planePosition, relpos);

              var dot = worldNormal.dot(relpos);
              if(dot <= 0.0){
                  if(justTest){
                      return true;
                  }

                  var r = this.createContactEquation(planeBody, convexBody, planeShape, convexShape, si, sj);

                  // Get vertex position projected on plane
                  var projected = planeConvex_projected;
                  worldNormal.mult(worldNormal.dot(relpos),projected);
                  worldVertex.vsub(projected, projected);
                  projected.vsub(planePosition, r.ri); // From plane to vertex projected on plane

                  r.ni.copy(worldNormal); // Contact normal is the plane normal out from plane

                  // rj is now just the vector from the convex center to the vertex
                  worldVertex.vsub(convexPosition, r.rj);

                  // Make it relative to the body
                  r.ri.vadd(planePosition, r.ri);
                  r.ri.vsub(planeBody.position, r.ri);
                  r.rj.vadd(convexPosition, r.rj);
                  r.rj.vsub(convexBody.position, r.rj);

                  this.result.push(r);
                  numContacts++;
                  if(!this.enableFrictionReduction){
                      this.createFrictionEquationsFromContact(r, this.frictionResult);
                  }
              }
          }

          if(this.enableFrictionReduction && numContacts){
              this.createFrictionFromAverage(numContacts);
          }
      };

      var convexConvex_sepAxis = new Vec3();
      var convexConvex_q = new Vec3();

      /**
       * @method convexConvex
       * @param  {Shape}      si
       * @param  {Shape}      sj
       * @param  {Vec3}       xi
       * @param  {Vec3}       xj
       * @param  {Quaternion} qi
       * @param  {Quaternion} qj
       * @param  {Body}       bi
       * @param  {Body}       bj
       */
      Narrowphase.prototype[Shape.types.CONVEXPOLYHEDRON] =
      Narrowphase.prototype.convexConvex = function(si,sj,xi,xj,qi,qj,bi,bj,rsi,rsj,justTest,faceListA,faceListB){
          var sepAxis = convexConvex_sepAxis;

          if(xi.distanceTo(xj) > si.boundingSphereRadius + sj.boundingSphereRadius){
              return;
          }

          if(si.findSeparatingAxis(sj,xi,qi,xj,qj,sepAxis,faceListA,faceListB)){
              var res = [];
              var q = convexConvex_q;
              si.clipAgainstHull(xi,qi,sj,xj,qj,sepAxis,-100,100,res);
              var numContacts = 0;
              for(var j = 0; j !== res.length; j++){
                  if(justTest){
                      return true;
                  }
                  var r = this.createContactEquation(bi,bj,si,sj,rsi,rsj),
                      ri = r.ri,
                      rj = r.rj;
                  sepAxis.negate(r.ni);
                  res[j].normal.negate(q);
                  q.mult(res[j].depth, q);
                  res[j].point.vadd(q, ri);
                  rj.copy(res[j].point);

                  // Contact points are in world coordinates. Transform back to relative
                  ri.vsub(xi,ri);
                  rj.vsub(xj,rj);

                  // Make relative to bodies
                  ri.vadd(xi, ri);
                  ri.vsub(bi.position, ri);
                  rj.vadd(xj, rj);
                  rj.vsub(bj.position, rj);

                  this.result.push(r);
                  numContacts++;
                  if(!this.enableFrictionReduction){
                      this.createFrictionEquationsFromContact(r, this.frictionResult);
                  }
              }
              if(this.enableFrictionReduction && numContacts){
                  this.createFrictionFromAverage(numContacts);
              }
          }
      };


      /**
       * @method convexTrimesh
       * @param  {Array}      result
       * @param  {Shape}      si
       * @param  {Shape}      sj
       * @param  {Vec3}       xi
       * @param  {Vec3}       xj
       * @param  {Quaternion} qi
       * @param  {Quaternion} qj
       * @param  {Body}       bi
       * @param  {Body}       bj
       */
      // Narrowphase.prototype[Shape.types.CONVEXPOLYHEDRON | Shape.types.TRIMESH] =
      // Narrowphase.prototype.convexTrimesh = function(si,sj,xi,xj,qi,qj,bi,bj,rsi,rsj,justTest,faceListA,faceListB){
      //     var sepAxis = convexConvex_sepAxis;

      //     if(xi.distanceTo(xj) > si.boundingSphereRadius + sj.boundingSphereRadius){
      //         return;
      //     }

      //     // Construct a temp hull for each triangle
      //     var hullB = new ConvexPolyhedron();

      //     hullB.faces = [[0,1,2]];
      //     var va = new Vec3();
      //     var vb = new Vec3();
      //     var vc = new Vec3();
      //     hullB.vertices = [
      //         va,
      //         vb,
      //         vc
      //     ];

      //     for (var i = 0; i < sj.indices.length / 3; i++) {

      //         var triangleNormal = new Vec3();
      //         sj.getNormal(i, triangleNormal);
      //         hullB.faceNormals = [triangleNormal];

      //         sj.getTriangleVertices(i, va, vb, vc);

      //         var d = si.testSepAxis(triangleNormal, hullB, xi, qi, xj, qj);
      //         if(!d){
      //             triangleNormal.scale(-1, triangleNormal);
      //             d = si.testSepAxis(triangleNormal, hullB, xi, qi, xj, qj);

      //             if(!d){
      //                 continue;
      //             }
      //         }

      //         var res = [];
      //         var q = convexConvex_q;
      //         si.clipAgainstHull(xi,qi,hullB,xj,qj,triangleNormal,-100,100,res);
      //         if(res.length == 0) return false;
      //         if(justTest) return true;
      //         for(var j = 0; j !== res.length; j++){
      //             var r = this.createContactEquation(bi,bj,si,sj,rsi,rsj),
      //                 ri = r.ri,
      //                 rj = r.rj;
      //             r.ni.copy(triangleNormal);
      //             r.ni.negate(r.ni);
      //             res[j].normal.negate(q);
      //             q.mult(res[j].depth, q);
      //             res[j].point.vadd(q, ri);
      //             rj.copy(res[j].point);

      //             // Contact points are in world coordinates. Transform back to relative
      //             ri.vsub(xi,ri);
      //             rj.vsub(xj,rj);

      //             // Make relative to bodies
      //             ri.vadd(xi, ri);
      //             ri.vsub(bi.position, ri);
      //             rj.vadd(xj, rj);
      //             rj.vsub(bj.position, rj);

      //             result.push(r);
      //         }
      //     }
      // };

      var particlePlane_normal = new Vec3();
      var particlePlane_relpos = new Vec3();
      var particlePlane_projected = new Vec3();

      /**
       * @method particlePlane
       * @param  {Array}      result
       * @param  {Shape}      si
       * @param  {Shape}      sj
       * @param  {Vec3}       xi
       * @param  {Vec3}       xj
       * @param  {Quaternion} qi
       * @param  {Quaternion} qj
       * @param  {Body}       bi
       * @param  {Body}       bj
       */
      Narrowphase.prototype[Shape.types.PLANE | Shape.types.PARTICLE] =
      Narrowphase.prototype.planeParticle = function(sj,si,xj,xi,qj,qi,bj,bi,rsi,rsj,justTest){
          var normal = particlePlane_normal;
          normal.set(0,0,1);
          bj.quaternion.vmult(normal,normal); // Turn normal according to plane orientation
          var relpos = particlePlane_relpos;
          xi.vsub(bj.position,relpos);
          var dot = normal.dot(relpos);
          if(dot <= 0.0){

              if(justTest){
                  return true;
              }

              var r = this.createContactEquation(bi,bj,si,sj,rsi,rsj);
              r.ni.copy(normal); // Contact normal is the plane normal
              r.ni.negate(r.ni);
              r.ri.set(0,0,0); // Center of particle

              // Get particle position projected on plane
              var projected = particlePlane_projected;
              normal.mult(normal.dot(xi),projected);
              xi.vsub(projected,projected);
              //projected.vadd(bj.position,projected);

              // rj is now the projected world position minus plane position
              r.rj.copy(projected);
              this.result.push(r);
              this.createFrictionEquationsFromContact(r, this.frictionResult);
          }
      };

      var particleSphere_normal = new Vec3();

      /**
       * @method particleSphere
       * @param  {Array}      result
       * @param  {Shape}      si
       * @param  {Shape}      sj
       * @param  {Vec3}       xi
       * @param  {Vec3}       xj
       * @param  {Quaternion} qi
       * @param  {Quaternion} qj
       * @param  {Body}       bi
       * @param  {Body}       bj
       */
      Narrowphase.prototype[Shape.types.PARTICLE | Shape.types.SPHERE] =
      Narrowphase.prototype.sphereParticle = function(sj,si,xj,xi,qj,qi,bj,bi,rsi,rsj,justTest){
          // The normal is the unit vector from sphere center to particle center
          var normal = particleSphere_normal;
          normal.set(0,0,1);
          xi.vsub(xj,normal);
          var lengthSquared = normal.norm2();

          if(lengthSquared <= sj.radius * sj.radius){
              if(justTest){
                  return true;
              }
              var r = this.createContactEquation(bi,bj,si,sj,rsi,rsj);
              normal.normalize();
              r.rj.copy(normal);
              r.rj.mult(sj.radius,r.rj);
              r.ni.copy(normal); // Contact normal
              r.ni.negate(r.ni);
              r.ri.set(0,0,0); // Center of particle
              this.result.push(r);
              this.createFrictionEquationsFromContact(r, this.frictionResult);
          }
      };

      // WIP
      var cqj = new Quaternion();
      var convexParticle_local = new Vec3();
      new Vec3();
      var convexParticle_penetratedFaceNormal = new Vec3();
      var convexParticle_vertexToParticle = new Vec3();
      var convexParticle_worldPenetrationVec = new Vec3();

      /**
       * @method convexParticle
       * @param  {Array}      result
       * @param  {Shape}      si
       * @param  {Shape}      sj
       * @param  {Vec3}       xi
       * @param  {Vec3}       xj
       * @param  {Quaternion} qi
       * @param  {Quaternion} qj
       * @param  {Body}       bi
       * @param  {Body}       bj
       */
      Narrowphase.prototype[Shape.types.PARTICLE | Shape.types.CONVEXPOLYHEDRON] =
      Narrowphase.prototype.convexParticle = function(sj,si,xj,xi,qj,qi,bj,bi,rsi,rsj,justTest){
          var penetratedFaceIndex = -1;
          var penetratedFaceNormal = convexParticle_penetratedFaceNormal;
          var worldPenetrationVec = convexParticle_worldPenetrationVec;
          var minPenetration = null;

          // Convert particle position xi to local coords in the convex
          var local = convexParticle_local;
          local.copy(xi);
          local.vsub(xj,local); // Convert position to relative the convex origin
          qj.conjugate(cqj);
          cqj.vmult(local,local);

          if(sj.pointIsInside(local)){

              if(sj.worldVerticesNeedsUpdate){
                  sj.computeWorldVertices(xj,qj);
              }
              if(sj.worldFaceNormalsNeedsUpdate){
                  sj.computeWorldFaceNormals(qj);
              }

              // For each world polygon in the polyhedra
              for(var i=0,nfaces=sj.faces.length; i!==nfaces; i++){

                  // Construct world face vertices
                  var verts = [ sj.worldVertices[ sj.faces[i][0] ] ];
                  var normal = sj.worldFaceNormals[i];

                  // Check how much the particle penetrates the polygon plane.
                  xi.vsub(verts[0],convexParticle_vertexToParticle);
                  var penetration = -normal.dot(convexParticle_vertexToParticle);
                  if(minPenetration===null || Math.abs(penetration)<Math.abs(minPenetration)){

                      if(justTest){
                          return true;
                      }

                      minPenetration = penetration;
                      penetratedFaceIndex = i;
                      penetratedFaceNormal.copy(normal);
                  }
              }

              if(penetratedFaceIndex!==-1){
                  // Setup contact
                  var r = this.createContactEquation(bi,bj,si,sj,rsi,rsj);
                  penetratedFaceNormal.mult(minPenetration, worldPenetrationVec);

                  // rj is the particle position projected to the face
                  worldPenetrationVec.vadd(xi,worldPenetrationVec);
                  worldPenetrationVec.vsub(xj,worldPenetrationVec);
                  r.rj.copy(worldPenetrationVec);
                  //var projectedToFace = xi.vsub(xj).vadd(worldPenetrationVec);
                  //projectedToFace.copy(r.rj);

                  //qj.vmult(r.rj,r.rj);
                  penetratedFaceNormal.negate( r.ni ); // Contact normal
                  r.ri.set(0,0,0); // Center of particle

                  var ri = r.ri,
                      rj = r.rj;

                  // Make relative to bodies
                  ri.vadd(xi, ri);
                  ri.vsub(bi.position, ri);
                  rj.vadd(xj, rj);
                  rj.vsub(bj.position, rj);

                  this.result.push(r);
                  this.createFrictionEquationsFromContact(r, this.frictionResult);
              } else {
                  console.warn("Point found inside convex, but did not find penetrating face!");
              }
          }
      };

      Narrowphase.prototype[Shape.types.BOX | Shape.types.HEIGHTFIELD] =
      Narrowphase.prototype.boxHeightfield = function (si,sj,xi,xj,qi,qj,bi,bj,rsi,rsj,justTest){
          si.convexPolyhedronRepresentation.material = si.material;
          si.convexPolyhedronRepresentation.collisionResponse = si.collisionResponse;
          return this.convexHeightfield(si.convexPolyhedronRepresentation,sj,xi,xj,qi,qj,bi,bj,si,sj,justTest);
      };

      var convexHeightfield_tmp1 = new Vec3();
      var convexHeightfield_tmp2 = new Vec3();
      var convexHeightfield_faceList = [0];

      /**
       * @method convexHeightfield
       */
      Narrowphase.prototype[Shape.types.CONVEXPOLYHEDRON | Shape.types.HEIGHTFIELD] =
      Narrowphase.prototype.convexHeightfield = function (
          convexShape,
          hfShape,
          convexPos,
          hfPos,
          convexQuat,
          hfQuat,
          convexBody,
          hfBody,
          rsi,
          rsj,
          justTest
      ){
          var data = hfShape.data,
              w = hfShape.elementSize,
              radius = convexShape.boundingSphereRadius,
              worldPillarOffset = convexHeightfield_tmp2,
              faceList = convexHeightfield_faceList;

          // Get sphere position to heightfield local!
          var localConvexPos = convexHeightfield_tmp1;
          Transform.pointToLocalFrame(hfPos, hfQuat, convexPos, localConvexPos);

          // Get the index of the data points to test against
          var iMinX = Math.floor((localConvexPos.x - radius) / w) - 1,
              iMaxX = Math.ceil((localConvexPos.x + radius) / w) + 1,
              iMinY = Math.floor((localConvexPos.y - radius) / w) - 1,
              iMaxY = Math.ceil((localConvexPos.y + radius) / w) + 1;

          // Bail out if we are out of the terrain
          if(iMaxX < 0 || iMaxY < 0 || iMinX > data.length || iMinY > data[0].length){
              return;
          }

          // Clamp index to edges
          if(iMinX < 0){ iMinX = 0; }
          if(iMaxX < 0){ iMaxX = 0; }
          if(iMinY < 0){ iMinY = 0; }
          if(iMaxY < 0){ iMaxY = 0; }
          if(iMinX >= data.length){ iMinX = data.length - 1; }
          if(iMaxX >= data.length){ iMaxX = data.length - 1; }
          if(iMaxY >= data[0].length){ iMaxY = data[0].length - 1; }
          if(iMinY >= data[0].length){ iMinY = data[0].length - 1; }

          var minMax = [];
          hfShape.getRectMinMax(iMinX, iMinY, iMaxX, iMaxY, minMax);
          var min = minMax[0];
          var max = minMax[1];

          // Bail out if we're cant touch the bounding height box
          if(localConvexPos.z - radius > max || localConvexPos.z + radius < min){
              return;
          }

          for(var i = iMinX; i < iMaxX; i++){
              for(var j = iMinY; j < iMaxY; j++){

                  var intersecting = false;

                  // Lower triangle
                  hfShape.getConvexTrianglePillar(i, j, false);
                  Transform.pointToWorldFrame(hfPos, hfQuat, hfShape.pillarOffset, worldPillarOffset);
                  if (convexPos.distanceTo(worldPillarOffset) < hfShape.pillarConvex.boundingSphereRadius + convexShape.boundingSphereRadius) {
                      intersecting = this.convexConvex(convexShape, hfShape.pillarConvex, convexPos, worldPillarOffset, convexQuat, hfQuat, convexBody, hfBody, rsi, rsj, justTest, faceList, null);
                  }

                  if(justTest && intersecting){
                      return true;
                  }

                  // Upper triangle
                  hfShape.getConvexTrianglePillar(i, j, true);
                  Transform.pointToWorldFrame(hfPos, hfQuat, hfShape.pillarOffset, worldPillarOffset);
                  if (convexPos.distanceTo(worldPillarOffset) < hfShape.pillarConvex.boundingSphereRadius + convexShape.boundingSphereRadius) {
                      intersecting = this.convexConvex(convexShape, hfShape.pillarConvex, convexPos, worldPillarOffset, convexQuat, hfQuat, convexBody, hfBody, rsi, rsj, justTest, faceList, null);
                  }

                  if(justTest && intersecting){
                      return true;
                  }
              }
          }
      };

      var sphereHeightfield_tmp1 = new Vec3();
      var sphereHeightfield_tmp2 = new Vec3();

      /**
       * @method sphereHeightfield
       */
      Narrowphase.prototype[Shape.types.SPHERE | Shape.types.HEIGHTFIELD] =
      Narrowphase.prototype.sphereHeightfield = function (
          sphereShape,
          hfShape,
          spherePos,
          hfPos,
          sphereQuat,
          hfQuat,
          sphereBody,
          hfBody,
          rsi,
          rsj,
          justTest
      ){
          var data = hfShape.data,
              radius = sphereShape.radius,
              w = hfShape.elementSize,
              worldPillarOffset = sphereHeightfield_tmp2;

          // Get sphere position to heightfield local!
          var localSpherePos = sphereHeightfield_tmp1;
          Transform.pointToLocalFrame(hfPos, hfQuat, spherePos, localSpherePos);

          // Get the index of the data points to test against
          var iMinX = Math.floor((localSpherePos.x - radius) / w) - 1,
              iMaxX = Math.ceil((localSpherePos.x + radius) / w) + 1,
              iMinY = Math.floor((localSpherePos.y - radius) / w) - 1,
              iMaxY = Math.ceil((localSpherePos.y + radius) / w) + 1;

          // Bail out if we are out of the terrain
          if(iMaxX < 0 || iMaxY < 0 || iMinX > data.length || iMinY > data[0].length){
              return;
          }

          // Clamp index to edges
          if(iMinX < 0){ iMinX = 0; }
          if(iMaxX < 0){ iMaxX = 0; }
          if(iMinY < 0){ iMinY = 0; }
          if(iMaxY < 0){ iMaxY = 0; }
          if(iMinX >= data.length){ iMinX = data.length - 1; }
          if(iMaxX >= data.length){ iMaxX = data.length - 1; }
          if(iMaxY >= data[0].length){ iMaxY = data[0].length - 1; }
          if(iMinY >= data[0].length){ iMinY = data[0].length - 1; }

          var minMax = [];
          hfShape.getRectMinMax(iMinX, iMinY, iMaxX, iMaxY, minMax);
          var min = minMax[0];
          var max = minMax[1];

          // Bail out if we're cant touch the bounding height box
          if(localSpherePos.z - radius > max || localSpherePos.z + radius < min){
              return;
          }

          var result = this.result;
          for(var i = iMinX; i < iMaxX; i++){
              for(var j = iMinY; j < iMaxY; j++){

                  var numContactsBefore = result.length;

                  var intersecting = false;

                  // Lower triangle
                  hfShape.getConvexTrianglePillar(i, j, false);
                  Transform.pointToWorldFrame(hfPos, hfQuat, hfShape.pillarOffset, worldPillarOffset);
                  if (spherePos.distanceTo(worldPillarOffset) < hfShape.pillarConvex.boundingSphereRadius + sphereShape.boundingSphereRadius) {
                      intersecting = this.sphereConvex(sphereShape, hfShape.pillarConvex, spherePos, worldPillarOffset, sphereQuat, hfQuat, sphereBody, hfBody, sphereShape, hfShape, justTest);
                  }

                  if(justTest && intersecting){
                      return true;
                  }

                  // Upper triangle
                  hfShape.getConvexTrianglePillar(i, j, true);
                  Transform.pointToWorldFrame(hfPos, hfQuat, hfShape.pillarOffset, worldPillarOffset);
                  if (spherePos.distanceTo(worldPillarOffset) < hfShape.pillarConvex.boundingSphereRadius + sphereShape.boundingSphereRadius) {
                      intersecting = this.sphereConvex(sphereShape, hfShape.pillarConvex, spherePos, worldPillarOffset, sphereQuat, hfQuat, sphereBody, hfBody, sphereShape, hfShape, justTest);
                  }

                  if(justTest && intersecting){
                      return true;
                  }

                  var numContacts = result.length - numContactsBefore;

                  if(numContacts > 2){
                      return;
                  }
                  /*
                  // Skip all but 1
                  for (var k = 0; k < numContacts - 1; k++) {
                      result.pop();
                  }
                  */
              }
          }
      };

      },{"../collision/AABB":3,"../collision/Ray":10,"../equations/ContactEquation":20,"../equations/FrictionEquation":22,"../math/Quaternion":29,"../math/Transform":30,"../math/Vec3":31,"../objects/Body":32,"../shapes/ConvexPolyhedron":39,"../shapes/Shape":44,"../solver/Solver":48,"../utils/Vec3Pool":55}],57:[function(_dereq_,module,exports){
      /* global performance */

      module.exports = World;

      _dereq_('../shapes/Shape');
      var Vec3 = _dereq_('../math/Vec3');
      var Quaternion = _dereq_('../math/Quaternion');
      var GSSolver = _dereq_('../solver/GSSolver');
      _dereq_('../equations/ContactEquation');
      _dereq_('../equations/FrictionEquation');
      var Narrowphase = _dereq_('./Narrowphase');
      var EventTarget = _dereq_('../utils/EventTarget');
      var ArrayCollisionMatrix = _dereq_('../collision/ArrayCollisionMatrix');
      var ObjectCollisionMatrix = _dereq_('../collision/ObjectCollisionMatrix');
      var OverlapKeeper = _dereq_('../collision/OverlapKeeper');
      var Material = _dereq_('../material/Material');
      var ContactMaterial = _dereq_('../material/ContactMaterial');
      var Body = _dereq_('../objects/Body');
      var TupleDictionary = _dereq_('../utils/TupleDictionary');
      var RaycastResult = _dereq_('../collision/RaycastResult');
      var AABB = _dereq_('../collision/AABB');
      var Ray = _dereq_('../collision/Ray');
      var NaiveBroadphase = _dereq_('../collision/NaiveBroadphase');

      /**
       * The physics world
       * @class World
       * @constructor
       * @extends EventTarget
       * @param {object} [options]
       * @param {Vec3} [options.gravity]
       * @param {boolean} [options.allowSleep]
       * @param {Broadphase} [options.broadphase]
       * @param {Solver} [options.solver]
       * @param {boolean} [options.quatNormalizeFast]
       * @param {number} [options.quatNormalizeSkip]
       */
      function World(options){
          options = options || {};
          EventTarget.apply(this);

          /**
           * Currently / last used timestep. Is set to -1 if not available. This value is updated before each internal step, which means that it is "fresh" inside event callbacks.
           * @property {Number} dt
           */
          this.dt = -1;

          /**
           * Makes bodies go to sleep when they've been inactive
           * @property allowSleep
           * @type {Boolean}
           * @default false
           */
          this.allowSleep = !!options.allowSleep;

          /**
           * All the current contacts (instances of ContactEquation) in the world.
           * @property contacts
           * @type {Array}
           */
          this.contacts = [];
          this.frictionEquations = [];

          /**
           * How often to normalize quaternions. Set to 0 for every step, 1 for every second etc.. A larger value increases performance. If bodies tend to explode, set to a smaller value (zero to be sure nothing can go wrong).
           * @property quatNormalizeSkip
           * @type {Number}
           * @default 0
           */
          this.quatNormalizeSkip = options.quatNormalizeSkip !== undefined ? options.quatNormalizeSkip : 0;

          /**
           * Set to true to use fast quaternion normalization. It is often enough accurate to use. If bodies tend to explode, set to false.
           * @property quatNormalizeFast
           * @type {Boolean}
           * @see Quaternion.normalizeFast
           * @see Quaternion.normalize
           * @default false
           */
          this.quatNormalizeFast = options.quatNormalizeFast !== undefined ? options.quatNormalizeFast : false;

          /**
           * The wall-clock time since simulation start
           * @property time
           * @type {Number}
           */
          this.time = 0.0;

          /**
           * Number of timesteps taken since start
           * @property stepnumber
           * @type {Number}
           */
          this.stepnumber = 0;

          /// Default and last timestep sizes
          this.default_dt = 1/60;

          this.nextId = 0;
          /**
           * @property gravity
           * @type {Vec3}
           */
          this.gravity = new Vec3();
          if(options.gravity){
              this.gravity.copy(options.gravity);
          }

          /**
           * The broadphase algorithm to use. Default is NaiveBroadphase
           * @property broadphase
           * @type {Broadphase}
           */
          this.broadphase = options.broadphase !== undefined ? options.broadphase : new NaiveBroadphase();

          /**
           * @property bodies
           * @type {Array}
           */
          this.bodies = [];

          /**
           * The solver algorithm to use. Default is GSSolver
           * @property solver
           * @type {Solver}
           */
          this.solver = options.solver !== undefined ? options.solver : new GSSolver();

          /**
           * @property constraints
           * @type {Array}
           */
          this.constraints = [];

          /**
           * @property narrowphase
           * @type {Narrowphase}
           */
          this.narrowphase = new Narrowphase(this);

          /**
           * @property {ArrayCollisionMatrix} collisionMatrix
      	 * @type {ArrayCollisionMatrix}
      	 */
      	this.collisionMatrix = new ArrayCollisionMatrix();

          /**
           * CollisionMatrix from the previous step.
           * @property {ArrayCollisionMatrix} collisionMatrixPrevious
      	 * @type {ArrayCollisionMatrix}
      	 */
      	this.collisionMatrixPrevious = new ArrayCollisionMatrix();

          this.bodyOverlapKeeper = new OverlapKeeper();
          this.shapeOverlapKeeper = new OverlapKeeper();

          /**
           * All added materials
           * @property materials
           * @type {Array}
           */
          this.materials = [];

          /**
           * @property contactmaterials
           * @type {Array}
           */
          this.contactmaterials = [];

          /**
           * Used to look up a ContactMaterial given two instances of Material.
           * @property {TupleDictionary} contactMaterialTable
           */
          this.contactMaterialTable = new TupleDictionary();

          this.defaultMaterial = new Material("default");

          /**
           * This contact material is used if no suitable contactmaterial is found for a contact.
           * @property defaultContactMaterial
           * @type {ContactMaterial}
           */
          this.defaultContactMaterial = new ContactMaterial(this.defaultMaterial, this.defaultMaterial, { friction: 0.3, restitution: 0.0 });

          /**
           * @property doProfiling
           * @type {Boolean}
           */
          this.doProfiling = false;

          /**
           * @property profile
           * @type {Object}
           */
          this.profile = {
              solve:0,
              makeContactConstraints:0,
              broadphase:0,
              integrate:0,
              narrowphase:0,
          };

          /**
           * Time accumulator for interpolation. See http://gafferongames.com/game-physics/fix-your-timestep/
           * @property {Number} accumulator
           */
          this.accumulator = 0;

          /**
           * @property subsystems
           * @type {Array}
           */
          this.subsystems = [];

          /**
           * Dispatched after a body has been added to the world.
           * @event addBody
           * @param {Body} body The body that has been added to the world.
           */
          this.addBodyEvent = {
              type:"addBody",
              body : null
          };

          /**
           * Dispatched after a body has been removed from the world.
           * @event removeBody
           * @param {Body} body The body that has been removed from the world.
           */
          this.removeBodyEvent = {
              type:"removeBody",
              body : null
          };

          this.idToBodyMap = {};

          this.broadphase.setWorld(this);
          this.substeps = 0;
          this.cm = new ObjectCollisionMatrix();
          this.tm = new ObjectCollisionMatrix();
          this.triggerDic = new TupleDictionary();
          this.oldTriggerDic = new TupleDictionary();
          this.contactsDic = new TupleDictionary();
          this.oldContactsDic = new TupleDictionary();
      }
      World.idToBodyMap = {};
      World.idToShapeMap = {};
      World.integrateKinematic = false;
      World.ccdSphereAdvance = false;
      World.prototype = new EventTarget();

      // Temp stuff
      new AABB();
      var tmpRay = new Ray();

      /**
       * Get the contact material between materials m1 and m2
       * @method getContactMaterial
       * @param {Material} m1
       * @param {Material} m2
       * @return {ContactMaterial} The contact material if it was found.
       */
      World.prototype.getContactMaterial = function(m1,m2){
          return this.contactMaterialTable.get(m1.id,m2.id); //this.contactmaterials[this.mats2cmat[i+j*this.materials.length]];
      };

      /**
       * Get number of objects in the world.
       * @method numObjects
       * @return {Number}
       * @deprecated
       */
      World.prototype.numObjects = function(){
          return this.bodies.length;
      };

      /**
       * Store old collision state info
       * @method collisionMatrixTick
       */
      World.prototype.collisionMatrixTick = function(){
      	var temp = this.collisionMatrixPrevious;
      	this.collisionMatrixPrevious = this.collisionMatrix;
      	this.collisionMatrix = temp;
      	this.collisionMatrix.reset();

          this.bodyOverlapKeeper.tick();
          this.shapeOverlapKeeper.tick();
      };

      /**
       * Add a rigid body to the simulation.
       * @method add
       * @param {Body} body
       * @todo If the simulation has not yet started, why recrete and copy arrays for each body? Accumulate in dynamic arrays in this case.
       * @todo Adding an array of bodies should be possible. This would save some loops too
       * @deprecated Use .addBody instead
       */
      World.prototype.add = World.prototype.addBody = function(body){
          if(this.bodies.indexOf(body) !== -1){
              return;
          }
          body.index = this.bodies.length;
          this.bodies.push(body);
          body.world = this;
          body.initPosition.copy(body.position);
          body.initVelocity.copy(body.velocity);
          body.timeLastSleepy = this.time;
          if(body instanceof Body){
              body.initAngularVelocity.copy(body.angularVelocity);
              body.initQuaternion.copy(body.quaternion);
          }
      	this.collisionMatrix.setNumObjects(this.bodies.length);
          this.addBodyEvent.body = body;
          this.cm.setNumObjects(this.bodies.length);
          World.idToBodyMap[body.id] = body;
          this.dispatchEvent(this.addBodyEvent);
      };

      /**
       * Add a constraint to the simulation.
       * @method addConstraint
       * @param {Constraint} c
       */
      World.prototype.addConstraint = function(c){
          this.constraints.push(c);
      };

      /**
       * Removes a constraint
       * @method removeConstraint
       * @param {Constraint} c
       */
      World.prototype.removeConstraint = function(c){
          var idx = this.constraints.indexOf(c);
          if(idx!==-1){
              this.constraints.splice(idx,1);
          }
      };

      /**
       * Raycast test
       * @method rayTest
       * @param {Vec3} from
       * @param {Vec3} to
       * @param {RaycastResult} result
       * @deprecated Use .raycastAll, .raycastClosest or .raycastAny instead.
       */
      World.prototype.rayTest = function(from, to, result){
          if(result instanceof RaycastResult){
              // Do raycastclosest
              this.raycastClosest(from, to, {
                  skipBackfaces: true
              }, result);
          } else {
              // Do raycastAll
              this.raycastAll(from, to, {
                  skipBackfaces: true
              }, result);
          }
      };

      /**
       * Ray cast against all bodies. The provided callback will be executed for each hit with a RaycastResult as single argument.
       * @method raycastAll
       * @param  {Vec3} from
       * @param  {Vec3} to
       * @param  {Object} options
       * @param  {number} [options.collisionFilterMask=-1]
       * @param  {number} [options.collisionFilterGroup=-1]
       * @param  {boolean} [options.skipBackfaces=false]
       * @param  {boolean} [options.checkCollisionResponse=true]
       * @param  {Function} callback
       * @return {boolean} True if any body was hit.
       */
      World.prototype.raycastAll = function(from, to, options, callback){
          options.mode = Ray.ALL;
          options.from = from;
          options.to = to;
          options.callback = callback;
          return tmpRay.intersectWorld(this, options);
      };

      /**
       * Ray cast, and stop at the first result. Note that the order is random - but the method is fast.
       * @method raycastAny
       * @param  {Vec3} from
       * @param  {Vec3} to
       * @param  {Object} options
       * @param  {number} [options.collisionFilterMask=-1]
       * @param  {number} [options.collisionFilterGroup=-1]
       * @param  {boolean} [options.skipBackfaces=false]
       * @param  {boolean} [options.checkCollisionResponse=true]
       * @param  {RaycastResult} result
       * @return {boolean} True if any body was hit.
       */
      World.prototype.raycastAny = function(from, to, options, result){
          options.mode = Ray.ANY;
          options.from = from;
          options.to = to;
          options.result = result;
          return tmpRay.intersectWorld(this, options);
      };

      /**
       * Ray cast, and return information of the closest hit.
       * @method raycastClosest
       * @param  {Vec3} from
       * @param  {Vec3} to
       * @param  {Object} options
       * @param  {number} [options.collisionFilterMask=-1]
       * @param  {number} [options.collisionFilterGroup=-1]
       * @param  {boolean} [options.skipBackfaces=false]
       * @param  {boolean} [options.checkCollisionResponse=true]
       * @param  {RaycastResult} result
       * @return {boolean} True if any body was hit.
       */
      World.prototype.raycastClosest = function(from, to, options, result){
          options.mode = Ray.CLOSEST;
          options.from = from;
          options.to = to;
          options.result = result;
          return tmpRay.intersectWorld(this, options);
      };

      /**
       * Remove a rigid body from the simulation.
       * @method remove
       * @param {Body} body
       * @deprecated Use .removeBody instead
       */
      World.prototype.remove = function(body){
          body.world = null;
          var n = this.bodies.length - 1,
              bodies = this.bodies,
              idx = bodies.indexOf(body);
          if(idx !== -1){
              bodies.splice(idx, 1); // Todo: should use a garbage free method

              // Recompute index
              for(var i=0; i!==bodies.length; i++){
                  bodies[i].index = i;
              }

              this.collisionMatrix.setNumObjects(n);
              this.removeBodyEvent.body = body;
              delete World.idToBodyMap[body.id];
              this.cm.setNumObjects(n);
              this.dispatchEvent(this.removeBodyEvent);
          }
      };

      /**
       * Remove a rigid body from the simulation.
       * @method removeBody
       * @param {Body} body
       */
      World.prototype.removeBody = World.prototype.remove;

      World.prototype.getBodyById = function (id) {
          return World.idToBodyMap[id];
      };

      World.prototype.getShapeById = function (id) {
          return World.idToShapeMap[id];
      };

      /**
       * Adds a material to the World.
       * @method addMaterial
       * @param {Material} m
       * @todo Necessary?
       */
      World.prototype.addMaterial = function(m){
          this.materials.push(m);
      };

      /**
       * Adds a contact material to the World
       * @method addContactMaterial
       * @param {ContactMaterial} cmat
       */
      World.prototype.addContactMaterial = function(cmat) {

          // Add contact material
          this.contactmaterials.push(cmat);

          // Add current contact material to the material table
          this.contactMaterialTable.set(cmat.materials[0].id,cmat.materials[1].id,cmat);
      };

      // performance.now()
      if(typeof performance === 'undefined'){
          performance = {};
      }
      if(!performance.now){
          var nowOffset = Date.now();
          if (performance.timing && performance.timing.navigationStart){
              nowOffset = performance.timing.navigationStart;
          }
          performance.now = function(){
              return Date.now() - nowOffset;
          };
      }

      World.prototype.saveKinematicAndApplyGravity = function(dt) {
          var bodies = this.bodies;
          var N = this.bodies.length;
          // apply damping / kinematic / gravity
          for(var i=0; i!==N; i++){
              var bi = bodies[i];
              if(bi.type === Body.DYNAMIC) {
                  bi.applyGravity(this.gravity);
              } else if(bi.type === Body.KINEMATIC) {
                  bi.updateKinematic(dt);
              }
          }
      };

      /**
       * Step the physics world forward in time.
       *
       * There are two modes. The simple mode is fixed timestepping without interpolation. In this case you only use the first argument. The second case uses interpolation. In that you also provide the time since the function was last used, as well as the maximum fixed timesteps to take.
       *
       * @method step
       * @param {Number} dt                       The fixed time step size to use.
       * @param {Number} [timeSinceLastCalled]    The time elapsed since the function was last called.
       * @param {Number} [maxSubSteps=10]         Maximum number of fixed steps to take per function call.
       *
       * @example
       *     // fixed timestepping without interpolation
       *     world.step(1/60);
       *
       * @see http://bulletphysics.org/mediawiki-1.5.8/index.php/Stepping_The_World
       */
      World.prototype.step = function(dt, timeSinceLastCalled, maxSubSteps){
          maxSubSteps = maxSubSteps || 10;
          timeSinceLastCalled = timeSinceLastCalled || 0;

          if(timeSinceLastCalled === 0){ // Fixed, simple stepping

              this.saveKinematicAndApplyGravity(dt);
              this.internalStep(dt);

              // Increment time
              this.time += dt;
              this.substeps = 1;

          } else {
              this.saveKinematicAndApplyGravity(timeSinceLastCalled);

              this.accumulator += timeSinceLastCalled;
              this.substeps = 0;
              while (this.accumulator >= dt && this.substeps < maxSubSteps) {
                  // Do fixed steps to catch up
                  this.internalStep(dt);
                  this.accumulator -= dt;
                  this.substeps++;
              }

              var t = (this.accumulator % dt) / dt;
              for(var j=0; j !== this.bodies.length; j++){
                  var b = this.bodies[j];
                  b.previousPosition.lerp(b.position, t, b.interpolatedPosition);
                  b.previousQuaternion.slerp(b.quaternion, t, b.interpolatedQuaternion);
                  b.previousQuaternion.normalize();
              }
              this.time += timeSinceLastCalled;
          }
          this.clearForces();
      };

      var /**
           * Dispatched after the world has stepped forward in time.
           * @event postStep
           */
          World_step_postStepEvent = {type:"postStep"}, // Reusable event objects to save memory
          /**
           * Dispatched before the world steps forward in time.
           * @event preStep
           */
          World_step_preStepEvent = {type:"preStep"},
          World_step_collideEvent = {type:"collide", body:null, contact:null },
          World_step_oldContacts = [], // Pools for unused objects
          World_step_frictionEquationPool = [],
          World_step_p1 = [], // Reusable arrays for collision pairs
          World_step_p2 = [];
          new Vec3(); // Temporary vectors and quats
          new Vec3();
          new Vec3();
          new Vec3();
          new Vec3();
          new Vec3();
          new Vec3();
          new Vec3();
          new Vec3();
          new Quaternion();
          new Quaternion();
          new Quaternion();
          new Vec3();
      World.prototype.internalStep = function(dt){
          this.dt = dt;

          var contacts = this.contacts,
              p1 = World_step_p1,
              p2 = World_step_p2,
              N = this.numObjects(),
              bodies = this.bodies,
              solver = this.solver,
              doProfiling = this.doProfiling,
              profile = this.profile,
              DYNAMIC = Body.DYNAMIC,
              profilingStart,
              constraints = this.constraints,
              frictionEquationPool = World_step_frictionEquationPool,
              i=0;

          if(doProfiling){
              profilingStart = performance.now();
          }

          // Update subsystems
          for(var i=0, Nsubsystems=this.subsystems.length; i!==Nsubsystems; i++){
              this.subsystems[i].update();
          }

          // Collision detection
          if(doProfiling){ profilingStart = performance.now(); }
          p1.length = 0; // Clean up pair arrays from last step
          p2.length = 0;
          this.broadphase.collisionPairs(this,p1,p2);
          if(doProfiling){ profile.broadphase = performance.now() - profilingStart; }

          // Remove constrained pairs with collideConnected == false
          var Nconstraints = constraints.length;
          for(i=0; i!==Nconstraints; i++){
              var c = constraints[i];
              if(!c.collideConnected){
                  for(var j = p1.length-1; j>=0; j-=1){
                      if( (c.bodyA === p1[j] && c.bodyB === p2[j]) ||
                          (c.bodyB === p1[j] && c.bodyA === p2[j])){
                          p1.splice(j, 1);
                          p2.splice(j, 1);
                      }
                  }
              }
          }

          this.collisionMatrixTick();

          // Generate contacts
          if(doProfiling){ profilingStart = performance.now(); }
          var oldcontacts = World_step_oldContacts;
          var NoldContacts = contacts.length;

          for(i=0; i!==NoldContacts; i++){
              oldcontacts.push(contacts[i]);
          }
          contacts.length = 0;

          // Transfer FrictionEquation from current list to the pool for reuse
          var NoldFrictionEquations = this.frictionEquations.length;
          for(i=0; i!==NoldFrictionEquations; i++){
              frictionEquationPool.push(this.frictionEquations[i]);
          }
          this.frictionEquations.length = 0;

          this.narrowphase.getContacts(
              p1,
              p2,
              this,
              contacts,
              oldcontacts, // To be reused
              this.frictionEquations,
              frictionEquationPool
          );

          if(doProfiling){
              profile.narrowphase = performance.now() - profilingStart;
          }

          // Loop over all collisions
          if(doProfiling){
              profilingStart = performance.now();
          }

          // Add all friction eqs
          for (var i = 0; i < this.frictionEquations.length; i++) {
              solver.addEquation(this.frictionEquations[i]);
          }

          var ncontacts = contacts.length;
          for(var k=0; k!==ncontacts; k++){

              // Current contact
              var c = contacts[k];

              // Get current collision indeces
              var bi = c.bi,
                  bj = c.bj,
                  si = c.si,
                  sj = c.sj;

              // // Get collision properties
              // var cm;
              // if(bi.material && bj.material){
              //     cm = this.getContactMaterial(bi.material,bj.material) || this.defaultContactMaterial;
              // } else {
              //     cm = this.defaultContactMaterial;
              // }

              // // c.enabled = bi.collisionResponse && bj.collisionResponse && si.collisionResponse && sj.collisionResponse;

              // var mu = cm.friction;
              // // c.restitution = cm.restitution;

              // // If friction or restitution were specified in the material, use them
              // if(bi.material && bj.material){
              //     if(bi.material.friction >= 0 && bj.material.friction >= 0){
              //         mu = bi.material.friction * bj.material.friction;
              //     }

              //     if(bi.material.restitution >= 0 && bj.material.restitution >= 0){
              //         c.restitution = bi.material.restitution * bj.material.restitution;
              //     }
              // }

              // EXTEND
              if (si.material && sj.material) {            
                  if(si.material.restitution >= 0 && sj.material.restitution >= 0){
                      c.restitution = si.material.restitution * sj.material.restitution;
                  }
              }else {
                  if(bi.material && bj.material){   
                      if(bi.material.restitution >= 0 && bj.material.restitution >= 0){
                          c.restitution = bi.material.restitution * bj.material.restitution;
                      }
                  }
              }

      		// c.setSpookParams(
        //           cm.contactEquationStiffness,
        //           cm.contactEquationRelaxation,
        //           dt
        //       );

      		solver.addEquation(c);

      		// // Add friction constraint equation
      		// if(mu > 0){

      		// 	// Create 2 tangent equations
      		// 	var mug = mu * gnorm;
      		// 	var reducedMass = (bi.invMass + bj.invMass);
      		// 	if(reducedMass > 0){
      		// 		reducedMass = 1/reducedMass;
      		// 	}
      		// 	var pool = frictionEquationPool;
      		// 	var c1 = pool.length ? pool.pop() : new FrictionEquation(bi,bj,mug*reducedMass);
      		// 	var c2 = pool.length ? pool.pop() : new FrictionEquation(bi,bj,mug*reducedMass);
      		// 	this.frictionEquations.push(c1, c2);

      		// 	c1.bi = c2.bi = bi;
      		// 	c1.bj = c2.bj = bj;
      		// 	c1.minForce = c2.minForce = -mug*reducedMass;
      		// 	c1.maxForce = c2.maxForce = mug*reducedMass;

      		// 	// Copy over the relative vectors
      		// 	c1.ri.copy(c.ri);
      		// 	c1.rj.copy(c.rj);
      		// 	c2.ri.copy(c.ri);
      		// 	c2.rj.copy(c.rj);

      		// 	// Construct tangents
      		// 	c.ni.tangents(c1.t, c2.t);

        //           // Set spook params
        //           c1.setSpookParams(cm.frictionEquationStiffness, cm.frictionEquationRelaxation, dt);
        //           c2.setSpookParams(cm.frictionEquationStiffness, cm.frictionEquationRelaxation, dt);

        //           c1.enabled = c2.enabled = c.enabled;

      		// 	// Add equations to solver
      		// 	solver.addEquation(c1);
      		// 	solver.addEquation(c2);
      		// }

              if( bi.allowSleep &&
                  bi.type === Body.DYNAMIC &&
                  bi.sleepState  === Body.SLEEPING &&
                  bj.sleepState  === Body.AWAKE &&
                  bj.type !== Body.STATIC
              ){
                  var speedSquaredB = bj.velocity.norm2() + bj.angularVelocity.norm2();
                  var speedLimitSquaredB = Math.pow(bj.sleepSpeedLimit,2);
                  if(speedSquaredB >= speedLimitSquaredB*2){
                      bi._wakeUpAfterNarrowphase = true;
                  }
              }

              if( bj.allowSleep &&
                  bj.type === Body.DYNAMIC &&
                  bj.sleepState  === Body.SLEEPING &&
                  bi.sleepState  === Body.AWAKE &&
                  bi.type !== Body.STATIC
              ){
                  var speedSquaredA = bi.velocity.norm2() + bi.angularVelocity.norm2();
                  var speedLimitSquaredA = Math.pow(bi.sleepSpeedLimit,2);
                  if(speedSquaredA >= speedLimitSquaredA*2){
                      bj._wakeUpAfterNarrowphase = true;
                  }
              }

              // Now we know that i and j are in contact. Set collision matrix state
      		this.collisionMatrix.set(bi, bj, true);

              if (!this.collisionMatrixPrevious.get(bi, bj)) {
                  // First contact!
                  // We reuse the collideEvent object, otherwise we will end up creating new objects for each new contact, even if there's no event listener attached.
                  World_step_collideEvent.body = bj;
                  World_step_collideEvent.contact = c;
                  bi.dispatchEvent(World_step_collideEvent);

                  World_step_collideEvent.body = bi;
                  bj.dispatchEvent(World_step_collideEvent);
              }

              this.bodyOverlapKeeper.set(bi.id, bj.id);
              this.shapeOverlapKeeper.set(si.id, sj.id);
          }

          this.emitContactEvents();

          if(doProfiling){
              profile.makeContactConstraints = performance.now() - profilingStart;
              profilingStart = performance.now();
          }

          // Wake up bodies
          for(i=0; i!==N; i++){
              var bi = bodies[i];
              if(bi._wakeUpAfterNarrowphase){
                  bi.wakeUp();
                  bi._wakeUpAfterNarrowphase = false;
              }
          }

          // Add user-added constraints
          var Nconstraints = constraints.length;
          for(i=0; i!==Nconstraints; i++){
              var c = constraints[i];
              c.update();
              for(var j=0, Neq=c.equations.length; j!==Neq; j++){
                  var eq = c.equations[j];
                  solver.addEquation(eq);
              }
          }

          // Solve the constrained system
          solver.solve(dt,this);

          if(doProfiling){
              profile.solve = performance.now() - profilingStart;
          }

          // Remove all contacts from solver
          solver.removeAllEquations();

          this.dispatchEvent(World_step_preStepEvent);

          // Invoke pre-step callbacks
          for(i=0; i!==N; i++){
              var bi = bodies[i];
              if(bi.preStep){
                  bi.preStep.call(bi);
              }
          }

          // Leap frog
          // vnew = v + h*f/m
          // xnew = x + h*vnew
          if(doProfiling){
              profilingStart = performance.now();
          }
          var stepnumber = this.stepnumber;
          var quatNormalize = stepnumber % (this.quatNormalizeSkip + 1) === 0;
          var quatNormalizeFast = this.quatNormalizeFast;

          for(i=0; i!==N; i++){
              bodies[i].integrate(dt, quatNormalize, quatNormalizeFast);
          }

          // Apply damping, see http://code.google.com/p/bullet/issues/detail?id=74 for details
          var pow = Math.pow;
          for(i=0; i!==N; i++){
              var bi = bodies[i];
              if(bi.type & DYNAMIC){ // Only for dynamic bodies
                  var ld = pow(1.0 - bi.linearDamping,dt);
                  var v = bi.velocity;
                  v.mult(ld,v);
                  var av = bi.angularVelocity;
                  if(av){
                      var ad = pow(1.0 - bi.angularDamping,dt);
                      av.mult(ad,av);
                  }
              }
          }

          this.broadphase.dirty = true;

          if(doProfiling){
              profile.integrate = performance.now() - profilingStart;
          }

          // Update world time
          this.time += dt;
          this.stepnumber += 1;

          this.dispatchEvent(World_step_postStepEvent);

          // Invoke post-step callbacks
          for(i=0; i!==N; i++){
              var bi = bodies[i];
              var postStep = bi.postStep;
              if(postStep){
                  postStep.call(bi);
              }
          }

          // Sleeping update
          if(this.allowSleep){
              for(i=0; i!==N; i++){
                  bodies[i].sleepTick(this.time);
              }
          }
      };

      World.prototype.emitContactEvents = (function(){
          var additions = [];
          var removals = [];
          var beginContactEvent = {
              type: 'beginContact',
              bodyA: null,
              bodyB: null
          };
          var endContactEvent = {
              type: 'endContact',
              bodyA: null,
              bodyB: null
          };
          var beginShapeContactEvent = {
              type: 'beginShapeContact',
              bodyA: null,
              bodyB: null,
              shapeA: null,
              shapeB: null
          };
          var endShapeContactEvent = {
              type: 'endShapeContact',
              bodyA: null,
              bodyB: null,
              shapeA: null,
              shapeB: null
          };
          return function(){
              var hasBeginContact = this.hasAnyEventListener('beginContact');
              var hasEndContact = this.hasAnyEventListener('endContact');

              if(hasBeginContact || hasEndContact){
                  this.bodyOverlapKeeper.getDiff(additions, removals);
              }

              if(hasBeginContact){
                  for (var i = 0, l = additions.length; i < l; i += 2) {
                      beginContactEvent.bodyA = this.getBodyById(additions[i]);
                      beginContactEvent.bodyB = this.getBodyById(additions[i+1]);
                      this.dispatchEvent(beginContactEvent);
                  }
                  beginContactEvent.bodyA = beginContactEvent.bodyB = null;
              }

              if(hasEndContact){
                  for (var i = 0, l = removals.length; i < l; i += 2) {
                      endContactEvent.bodyA = this.getBodyById(removals[i]);
                      endContactEvent.bodyB = this.getBodyById(removals[i+1]);
                      this.dispatchEvent(endContactEvent);
                  }
                  endContactEvent.bodyA = endContactEvent.bodyB = null;
              }

              additions.length = removals.length = 0;

              var hasBeginShapeContact = this.hasAnyEventListener('beginShapeContact');
              var hasEndShapeContact = this.hasAnyEventListener('endShapeContact');

              if(hasBeginShapeContact || hasEndShapeContact){
                  this.shapeOverlapKeeper.getDiff(additions, removals);
              }

              if(hasBeginShapeContact){
                  for (var i = 0, l = additions.length; i < l; i += 2) {
                      var shapeA = this.getShapeById(additions[i]);
                      var shapeB = this.getShapeById(additions[i+1]);
                      beginShapeContactEvent.shapeA = shapeA;
                      beginShapeContactEvent.shapeB = shapeB;
                      beginShapeContactEvent.bodyA = shapeA.body;
                      beginShapeContactEvent.bodyB = shapeB.body;
                      this.dispatchEvent(beginShapeContactEvent);
                  }
                  beginShapeContactEvent.bodyA = beginShapeContactEvent.bodyB = beginShapeContactEvent.shapeA = beginShapeContactEvent.shapeB = null;
              }

              if(hasEndShapeContact){
                  for (var i = 0, l = removals.length; i < l; i += 2) {
                      var shapeA = this.getShapeById(removals[i]);
                      var shapeB = this.getShapeById(removals[i+1]);
                      endShapeContactEvent.shapeA = shapeA;
                      endShapeContactEvent.shapeB = shapeB;
                      endShapeContactEvent.bodyA = shapeA.body;
                      endShapeContactEvent.bodyB = shapeB.body;
                      this.dispatchEvent(endShapeContactEvent);
                  }
                  endShapeContactEvent.bodyA = endShapeContactEvent.bodyB = endShapeContactEvent.shapeA = endShapeContactEvent.shapeB = null;
              }

          };
      })();

      /**
       * Sets all body forces in the world to zero.
       * @method clearForces
       */
      World.prototype.clearForces = function(){
          var bodies = this.bodies;
          var N = bodies.length;
          for(var i=0; i !== N; i++){
              var b = bodies[i];
                  b.force;
                  b.torque;

              b.force.set(0,0,0);
              b.torque.set(0,0,0);
          }
      };

      var cc_trigger = {type: 'cc-trigger',event: '',selfBody: null,otherBody: null,selfShape: null,otherShape: null};
      var cc_collide = {type: "cc-collide",event: '',body: null,selfShape: null,otherShape: null,contacts: null};
      var cc_oldContacts = [];
      World.prototype.emitTriggeredEvents = function () {
          if (this.substeps == 0) return;

          var key;
          var data;
          var i = this.triggerDic.getLength();
          while (i--) {
              key = this.triggerDic.getKeyByIndex(i);
              data = this.triggerDic.getDataByKey(key);
              
              if (data == null) continue;
              
              var shapeA = data.si;
              var shapeB = data.sj;
              if (this.tm.get(shapeA, shapeB)) {
                  cc_trigger.event = 'onTriggerStay';
              } else {
                  this.tm.set(shapeA, shapeB, true);
                  cc_trigger.event = 'onTriggerEnter';
              }
              cc_trigger.selfShape = shapeA;
              cc_trigger.otherShape = shapeB;
              cc_trigger.selfBody = shapeA.body;
              cc_trigger.otherBody = shapeB.body;
              shapeA.dispatchEvent(cc_trigger);

              cc_trigger.selfShape = shapeB;
              cc_trigger.otherShape = shapeA;
              cc_trigger.selfBody = shapeB.body;
              cc_trigger.otherBody = shapeA.body;
              shapeB.dispatchEvent(cc_trigger);
          }

          i = this.oldTriggerDic.getLength();
          while (i > 0) {
              i--;
              key = this.oldTriggerDic.getKeyByIndex(i);

              if (this.triggerDic.getDataByKey(key) != null) continue;

              data = this.oldTriggerDic.getDataByKey(key);        
              if (data == null) continue;

              var shapeA = data.si;
              var shapeB = data.sj;
                      
              this.tm.set(shapeA, shapeB, false);
              if (this.oldTriggerDic.del(shapeA.id, shapeB.id)) i--;

              cc_trigger.event = 'onTriggerExit';
              cc_trigger.selfShape = shapeA;
              cc_trigger.otherShape = shapeB;
              cc_trigger.selfBody = shapeA.body;
              cc_trigger.otherBody = shapeB.body;
              shapeA.dispatchEvent(cc_trigger);

              cc_trigger.selfShape = shapeB;
              cc_trigger.otherShape = shapeA;
              cc_trigger.selfBody = shapeB.body;
              cc_trigger.otherBody = shapeA.body;
              shapeB.dispatchEvent(cc_trigger);
          }

          this.triggerDic.reset();
      };

      World.prototype.emitCollisionEvents = function () {
          if (this.substeps == 0)
              return;

          var contacts = this.contacts;
          var i = this.contacts.length;
          while (i--) {
              // Current contact
              var c = contacts[i];
              // Get current collision indeces
              var si = c.si;
              var sj = c.sj;
              var item = this.contactsDic.get(si.id, sj.id);
              if (item == null) {
                  item = this.contactsDic.set(si.id, sj.id, []);
              }
              item.push(c);
          }

          var key;
          var data;
          // is collision enter or stay
          var i = this.contactsDic.getLength();
          while (i--) {
              key = this.contactsDic.getKeyByIndex(i);
              data = this.contactsDic.getDataByKey(key);

              if (data == null)
                  continue;

              var si = data[0].si;
              var sj = data[0].sj;
              var bi = si.body;
              var bj = sj.body;

              // Now we know that i and j are in contact. Set collision matrix state		
              if (this.cm.get(bi, bj)) {
                  // collision stay
                  cc_collide.event = 'onCollisionStay';

              } else {
                  this.cm.set(bi, bj, true);
                  // collision enter
                  cc_collide.event = 'onCollisionEnter';
              }

              cc_collide.bi = bi;
              cc_collide.contact = data[0];

              cc_collide.contacts = data;

              cc_collide.body = bj;
              cc_collide.selfShape = si;
              cc_collide.otherShape = sj;
              bi.dispatchEvent(cc_collide);

              cc_collide.body = bi;
              cc_collide.selfShape = sj;
              cc_collide.otherShape = si;
              bj.dispatchEvent(cc_collide);
          }
          var oldcontacts = cc_oldContacts;
          for (i = oldcontacts.length; i--;) {
              // Current contact
              var c = oldcontacts[i];

              // Get current collision indeces
              var si = c.si;
              var sj = c.sj;
              if (this.oldContactsDic.get(si.id, sj.id) == null) {
                  this.oldContactsDic.set(si.id, sj.id, c);
              }
          }

          // is collision exit
          i = this.oldContactsDic.getLength();
          while (i--) {
              key = this.oldContactsDic.getKeyByIndex(i);
              if (this.contactsDic.getDataByKey(key) == null) {
                  data = this.oldContactsDic.getDataByKey(key);
                  var si = data.si;
                  var sj = data.sj;
                  var bi = si.body;
                  var bj = sj.body;
                  if (this.cm.get(bi, bj)) {
                      if (!bi.isSleeping() || !bj.isSleeping()) {
                          this.cm.set(bi, bj, false);

                          cc_collide.bi = bi;    
                          cc_collide.contact = data;
                  
                          // collision exit
                          cc_collide.event = 'onCollisionExit';
                          cc_collide.body = bj;
                          cc_collide.selfShape = si;
                          cc_collide.otherShape = sj;
                          cc_collide.contacts.length = 0;
                          cc_collide.contacts.push(data);
                          bi.dispatchEvent(cc_collide);

                          cc_collide.body = bi;
                          cc_collide.selfShape = sj;
                          cc_collide.otherShape = si;
                          bj.dispatchEvent(cc_collide);
                      }
                  }
              }
          }

          this.contactsDic.reset();
          this.oldContactsDic.reset();
          World_step_oldContacts = cc_oldContacts;  
          cc_oldContacts = this.contacts.slice();
          this.contacts.length = 0;
      };

      },{"../collision/AABB":3,"../collision/ArrayCollisionMatrix":4,"../collision/NaiveBroadphase":7,"../collision/ObjectCollisionMatrix":8,"../collision/OverlapKeeper":9,"../collision/Ray":10,"../collision/RaycastResult":11,"../equations/ContactEquation":20,"../equations/FrictionEquation":22,"../material/ContactMaterial":25,"../material/Material":26,"../math/Quaternion":29,"../math/Vec3":31,"../objects/Body":32,"../shapes/Shape":44,"../solver/GSSolver":47,"../utils/EventTarget":50,"../utils/TupleDictionary":53,"./Narrowphase":56}]},{},[2])
      (2)
      });
      });

      var ERigidBodyType; exports('f5', ERigidBodyType);
      (function (ERigidBodyType) {
        ERigidBodyType[ERigidBodyType["DYNAMIC"] = 1] = "DYNAMIC";
        ERigidBodyType[ERigidBodyType["STATIC"] = 2] = "STATIC";
        ERigidBodyType[ERigidBodyType["KINEMATIC"] = 4] = "KINEMATIC";
      })(ERigidBodyType || (exports('f5', ERigidBodyType = {})));
      Enum(ERigidBodyType);
      var EAxisDirection; exports('f4', EAxisDirection);
      (function (EAxisDirection) {
        EAxisDirection[EAxisDirection["X_AXIS"] = 0] = "X_AXIS";
        EAxisDirection[EAxisDirection["Y_AXIS"] = 1] = "Y_AXIS";
        EAxisDirection[EAxisDirection["Z_AXIS"] = 2] = "Z_AXIS";
      })(EAxisDirection || (exports('f4', EAxisDirection = {})));
      Enum(EAxisDirection);
      var ED6Axis;
      (function (ED6Axis) {
        ED6Axis[ED6Axis["X"] = 0] = "X";
        ED6Axis[ED6Axis["Y"] = 1] = "Y";
        ED6Axis[ED6Axis["Z"] = 2] = "Z";
        ED6Axis[ED6Axis["SWING1"] = 3] = "SWING1";
        ED6Axis[ED6Axis["SWING2"] = 4] = "SWING2";
        ED6Axis[ED6Axis["TWIST"] = 5] = "TWIST";
      })(ED6Axis || (ED6Axis = {}));
      Enum(ED6Axis);
      var ESimplexType;
      (function (ESimplexType) {
        ESimplexType[ESimplexType["VERTEX"] = 1] = "VERTEX";
        ESimplexType[ESimplexType["LINE"] = 2] = "LINE";
        ESimplexType[ESimplexType["TRIANGLE"] = 3] = "TRIANGLE";
        ESimplexType[ESimplexType["TETRAHEDRON"] = 4] = "TETRAHEDRON";
      })(ESimplexType || (ESimplexType = {}));
      Enum(ESimplexType);
      var EColliderType; exports('f6', EColliderType);
      (function (EColliderType) {
        EColliderType[EColliderType["BOX"] = 0] = "BOX";
        EColliderType[EColliderType["SPHERE"] = 1] = "SPHERE";
        EColliderType[EColliderType["CAPSULE"] = 2] = "CAPSULE";
        EColliderType[EColliderType["CYLINDER"] = 3] = "CYLINDER";
        EColliderType[EColliderType["CONE"] = 4] = "CONE";
        EColliderType[EColliderType["MESH"] = 5] = "MESH";
        EColliderType[EColliderType["PLANE"] = 6] = "PLANE";
        EColliderType[EColliderType["SIMPLEX"] = 7] = "SIMPLEX";
        EColliderType[EColliderType["TERRAIN"] = 8] = "TERRAIN";
      })(EColliderType || (exports('f6', EColliderType = {})));
      Enum(EColliderType);
      var EConstraintType;
      (function (EConstraintType) {
        EConstraintType[EConstraintType["POINT_TO_POINT"] = 0] = "POINT_TO_POINT";
        EConstraintType[EConstraintType["HINGE"] = 1] = "HINGE";
        EConstraintType[EConstraintType["FIXED"] = 2] = "FIXED";
        EConstraintType[EConstraintType["CONFIGURABLE"] = 3] = "CONFIGURABLE";
      })(EConstraintType || (EConstraintType = {}));
      Enum(EConstraintType);
      var EConstraintMode;
      (function (EConstraintMode) {
        EConstraintMode[EConstraintMode["FREE"] = 0] = "FREE";
        EConstraintMode[EConstraintMode["LIMITED"] = 1] = "LIMITED";
        EConstraintMode[EConstraintMode["LOCKED"] = 2] = "LOCKED";
      })(EConstraintMode || (EConstraintMode = {}));
      Enum(EConstraintMode);
      var EDriverMode;
      (function (EDriverMode) {
        EDriverMode[EDriverMode["DISABLED"] = 0] = "DISABLED";
        EDriverMode[EDriverMode["SERVO"] = 1] = "SERVO";
        EDriverMode[EDriverMode["INDUCTION"] = 2] = "INDUCTION";
      })(EDriverMode || (EDriverMode = {}));
      Enum(EDriverMode);
      var ECharacterControllerType;
      (function (ECharacterControllerType) {
        ECharacterControllerType[ECharacterControllerType["BOX"] = 0] = "BOX";
        ECharacterControllerType[ECharacterControllerType["CAPSULE"] = 1] = "CAPSULE";
      })(ECharacterControllerType || (ECharacterControllerType = {}));
      Enum(ECharacterControllerType);
      var PhysicsGroup;
      (function (PhysicsGroup) {
        PhysicsGroup[PhysicsGroup["DEFAULT"] = 1] = "DEFAULT";
      })(PhysicsGroup || (PhysicsGroup = {}));
      Enum(PhysicsGroup);

      function updateLegacyMacro(id) {
        legacyCC._global.CC_PHYSICS_BUILTIN = id === 'builtin';
        legacyCC._global.CC_PHYSICS_CANNON = id === 'cannon.js';
        legacyCC._global.CC_PHYSICS_AMMO = id === 'bullet';
      }
      function register(id, wrapper) {
        console.info("[PHYSICS]: register " + id + ".");
        selector.backend[id] = wrapper;
        if (!selector.physicsWorld || selector.id === id) {
          updateLegacyMacro(id);
          var mutableSelector = selector;
          mutableSelector.id = id;
          mutableSelector.wrapper = wrapper;
        }
      }
      var worldInitData;
      function switchTo(id) {
        if (!selector.runInEditor) return;
        var mutableSelector = selector;
        if (selector.physicsWorld && id !== selector.id && selector.backend[id] != null) {
          selector.physicsWorld.destroy();
          console.info("[PHYSICS]: switch from " + selector.id + " to " + id + ".");
          updateLegacyMacro(id);
          mutableSelector.id = id;
          mutableSelector.wrapper = selector.backend[id];
          mutableSelector.physicsWorld = createPhysicsWorld();
        } else {
          console.info("[PHYSICS]: using " + id + ".");
          mutableSelector.physicsWorld = createPhysicsWorld();
        }
        if (worldInitData) {
          var world = mutableSelector.physicsWorld;
          world.setGravity(worldInitData.gravity);
          world.setAllowSleep(worldInitData.allowSleep);
        }
      }
      var selector = {
        id: '',
        switchTo: switchTo,
        register: register,
        wrapper: {},
        backend: {},
        physicsWorld: null,
        runInEditor: !EDITOR
      };
      function constructDefaultWorld(data) {
        if (!worldInitData) worldInitData = data;
        if (!selector.runInEditor) return;
        if (!selector.physicsWorld) {
          console.info("[PHYSICS]: using " + selector.id + ".");
          var mutableSelector = selector;
          var world = mutableSelector.physicsWorld = createPhysicsWorld();
          world.setGravity(worldInitData.gravity);
          world.setAllowSleep(worldInitData.allowSleep);
        }
      }
      var FUNC = function FUNC() {
        return 0;
      };
      var ENTIRE_WORLD = {
        impl: null,
        setGravity: FUNC,
        setAllowSleep: FUNC,
        setDefaultMaterial: FUNC,
        step: FUNC,
        syncAfterEvents: FUNC,
        syncSceneToPhysics: FUNC,
        raycast: FUNC,
        raycastClosest: FUNC,
        sweepBox: FUNC,
        sweepBoxClosest: FUNC,
        sweepSphere: FUNC,
        sweepSphereClosest: FUNC,
        sweepCapsule: FUNC,
        sweepCapsuleClosest: FUNC,
        emitEvents: FUNC,
        destroy: FUNC
      };
      var ECheckType;
      (function (ECheckType) {
        ECheckType[ECheckType["World"] = 0] = "World";
        ECheckType[ECheckType["RigidBody"] = 1] = "RigidBody";
        ECheckType[ECheckType["BoxCollider"] = 2] = "BoxCollider";
        ECheckType[ECheckType["SphereCollider"] = 3] = "SphereCollider";
        ECheckType[ECheckType["CapsuleCollider"] = 4] = "CapsuleCollider";
        ECheckType[ECheckType["MeshCollider"] = 5] = "MeshCollider";
        ECheckType[ECheckType["CylinderCollider"] = 6] = "CylinderCollider";
        ECheckType[ECheckType["ConeCollider"] = 7] = "ConeCollider";
        ECheckType[ECheckType["TerrainCollider"] = 8] = "TerrainCollider";
        ECheckType[ECheckType["SimplexCollider"] = 9] = "SimplexCollider";
        ECheckType[ECheckType["PlaneCollider"] = 10] = "PlaneCollider";
        ECheckType[ECheckType["PointToPointConstraint"] = 11] = "PointToPointConstraint";
        ECheckType[ECheckType["HingeConstraint"] = 12] = "HingeConstraint";
        ECheckType[ECheckType["FixedConstraint"] = 13] = "FixedConstraint";
        ECheckType[ECheckType["ConfigurableConstraint"] = 14] = "ConfigurableConstraint";
        ECheckType[ECheckType["BoxCharacterController"] = 15] = "BoxCharacterController";
        ECheckType[ECheckType["CapsuleCharacterController"] = 16] = "CapsuleCharacterController";
      })(ECheckType || (ECheckType = {}));
      function check(obj, type) {
        if (obj == null) {
          if (selector.id) {
            warn(selector.id + " physics does not support " + ECheckType[type]);
          } else {
            errorID(9600);
          }
          return true;
        }
        return false;
      }
      function createPhysicsWorld() {
        if (check(selector.wrapper.PhysicsWorld, ECheckType.World)) {
          return ENTIRE_WORLD;
        }
        return new selector.wrapper.PhysicsWorld();
      }
      var ENTIRE_RIGID_BODY = {
        impl: null,
        rigidBody: null,
        isAwake: false,
        isSleepy: false,
        isSleeping: false,
        initialize: FUNC,
        onEnable: FUNC,
        onDisable: FUNC,
        onDestroy: FUNC,
        setType: FUNC,
        setMass: FUNC,
        setLinearDamping: FUNC,
        setAngularDamping: FUNC,
        useGravity: FUNC,
        setLinearFactor: FUNC,
        setAngularFactor: FUNC,
        setAllowSleep: FUNC,
        wakeUp: FUNC,
        sleep: FUNC,
        clearState: FUNC,
        clearForces: FUNC,
        clearVelocity: FUNC,
        setSleepThreshold: FUNC,
        getSleepThreshold: FUNC,
        getLinearVelocity: FUNC,
        setLinearVelocity: FUNC,
        getAngularVelocity: FUNC,
        setAngularVelocity: FUNC,
        applyForce: FUNC,
        applyLocalForce: FUNC,
        applyImpulse: FUNC,
        applyLocalImpulse: FUNC,
        applyTorque: FUNC,
        applyLocalTorque: FUNC,
        setGroup: FUNC,
        getGroup: FUNC,
        addGroup: FUNC,
        removeGroup: FUNC,
        setMask: FUNC,
        getMask: FUNC,
        addMask: FUNC,
        removeMask: FUNC,
        isUsingCCD: FUNC,
        useCCD: FUNC
      };
      function createRigidBody() {
        if (check(selector.wrapper.RigidBody, ECheckType.RigidBody)) {
          return ENTIRE_RIGID_BODY;
        }
        return new selector.wrapper.RigidBody();
      }
      var CREATE_COLLIDER_PROXY = {
        INITED: false
      };
      var ENTIRE_SHAPE = {
        impl: null,
        collider: null,
        attachedRigidBody: null,
        initialize: FUNC,
        onLoad: FUNC,
        onEnable: FUNC,
        onDisable: FUNC,
        onDestroy: FUNC,
        setGroup: FUNC,
        getGroup: FUNC,
        addGroup: FUNC,
        removeGroup: FUNC,
        setMask: FUNC,
        getMask: FUNC,
        addMask: FUNC,
        removeMask: FUNC,
        setMaterial: FUNC,
        setAsTrigger: FUNC,
        setCenter: FUNC,
        getAABB: FUNC,
        getBoundingSphere: FUNC,
        updateSize: FUNC,
        updateRadius: FUNC,
        setRadius: FUNC,
        setCylinderHeight: FUNC,
        setDirection: FUNC,
        setHeight: FUNC,
        setShapeType: FUNC,
        setVertices: FUNC,
        setMesh: FUNC,
        setTerrain: FUNC,
        setNormal: FUNC,
        setConstant: FUNC,
        updateEventListener: FUNC
      };
      function createShape(type) {
        initColliderProxy();
        return CREATE_COLLIDER_PROXY[type]();
      }
      function initColliderProxy() {
        if (CREATE_COLLIDER_PROXY.INITED) return;
        CREATE_COLLIDER_PROXY.INITED = true;
        CREATE_COLLIDER_PROXY[EColliderType.BOX] = function createBoxShape() {
          if (check(selector.wrapper.BoxShape, ECheckType.BoxCollider)) {
            return ENTIRE_SHAPE;
          }
          return new selector.wrapper.BoxShape();
        };
        CREATE_COLLIDER_PROXY[EColliderType.SPHERE] = function createSphereShape() {
          if (check(selector.wrapper.SphereShape, ECheckType.SphereCollider)) {
            return ENTIRE_SHAPE;
          }
          return new selector.wrapper.SphereShape();
        };
        CREATE_COLLIDER_PROXY[EColliderType.CAPSULE] = function createCapsuleShape() {
          if (check(selector.wrapper.CapsuleShape, ECheckType.CapsuleCollider)) {
            return ENTIRE_SHAPE;
          }
          return new selector.wrapper.CapsuleShape();
        };
        CREATE_COLLIDER_PROXY[EColliderType.CYLINDER] = function createCylinderShape() {
          if (check(selector.wrapper.CylinderShape, ECheckType.CylinderCollider)) {
            return ENTIRE_SHAPE;
          }
          return new selector.wrapper.CylinderShape();
        };
        CREATE_COLLIDER_PROXY[EColliderType.CONE] = function createConeShape() {
          if (check(selector.wrapper.ConeShape, ECheckType.ConeCollider)) {
            return ENTIRE_SHAPE;
          }
          return new selector.wrapper.ConeShape();
        };
        CREATE_COLLIDER_PROXY[EColliderType.MESH] = function createTrimeshShape() {
          if (check(selector.wrapper.TrimeshShape, ECheckType.MeshCollider)) {
            return ENTIRE_SHAPE;
          }
          return new selector.wrapper.TrimeshShape();
        };
        CREATE_COLLIDER_PROXY[EColliderType.TERRAIN] = function createTerrainShape() {
          if (check(selector.wrapper.TerrainShape, ECheckType.TerrainCollider)) {
            return ENTIRE_SHAPE;
          }
          return new selector.wrapper.TerrainShape();
        };
        CREATE_COLLIDER_PROXY[EColliderType.SIMPLEX] = function createSimplexShape() {
          if (check(selector.wrapper.SimplexShape, ECheckType.SimplexCollider)) {
            return ENTIRE_SHAPE;
          }
          return new selector.wrapper.SimplexShape();
        };
        CREATE_COLLIDER_PROXY[EColliderType.PLANE] = function createPlaneShape() {
          if (check(selector.wrapper.PlaneShape, ECheckType.PlaneCollider)) {
            return ENTIRE_SHAPE;
          }
          return new selector.wrapper.PlaneShape();
        };
      }
      var CREATE_CONSTRAINT_PROXY = {
        INITED: false
      };
      var ENTIRE_CONSTRAINT = {
        impl: null,
        initialize: FUNC,
        onLoad: FUNC,
        onEnable: FUNC,
        onDisable: FUNC,
        onDestroy: FUNC,
        setEnableCollision: FUNC,
        setConnectedBody: FUNC,
        setPivotA: FUNC,
        setPivotB: FUNC,
        setAxis: FUNC,
        setSecondaryAxis: FUNC,
        setBreakForce: FUNC,
        setBreakTorque: FUNC,
        setConstraintMode: FUNC,
        setLinearLimit: FUNC,
        setAngularExtent: FUNC,
        setLinearSoftConstraint: FUNC,
        setLinearStiffness: FUNC,
        setLinearDamping: FUNC,
        setLinearRestitution: FUNC,
        setSwingSoftConstraint: FUNC,
        setTwistSoftConstraint: FUNC,
        setSwingStiffness: FUNC,
        setSwingDamping: FUNC,
        setSwingRestitution: FUNC,
        setTwistStiffness: FUNC,
        setTwistDamping: FUNC,
        setTwistRestitution: FUNC,
        setDriverMode: FUNC,
        setLinearMotorTarget: FUNC,
        setLinearMotorVelocity: FUNC,
        setLinearMotorForceLimit: FUNC,
        setAngularMotorTarget: FUNC,
        setAngularMotorVelocity: FUNC,
        setAngularMotorForceLimit: FUNC,
        setAutoPivotB: FUNC,
        setLimitEnabled: FUNC,
        setLowerLimit: FUNC,
        setUpperLimit: FUNC,
        setMotorEnabled: FUNC,
        setMotorVelocity: FUNC,
        setMotorForceLimit: FUNC
      };
      function createConstraint(type) {
        initConstraintProxy();
        return CREATE_CONSTRAINT_PROXY[type]();
      }
      function initConstraintProxy() {
        if (CREATE_CONSTRAINT_PROXY.INITED) return;
        CREATE_CONSTRAINT_PROXY.INITED = true;
        CREATE_CONSTRAINT_PROXY[EConstraintType.POINT_TO_POINT] = function createPointToPointConstraint() {
          if (check(selector.wrapper.PointToPointConstraint, ECheckType.PointToPointConstraint)) {
            return ENTIRE_CONSTRAINT;
          }
          return new selector.wrapper.PointToPointConstraint();
        };
        CREATE_CONSTRAINT_PROXY[EConstraintType.HINGE] = function createHingeConstraint() {
          if (check(selector.wrapper.HingeConstraint, ECheckType.HingeConstraint)) {
            return ENTIRE_CONSTRAINT;
          }
          return new selector.wrapper.HingeConstraint();
        };
        CREATE_CONSTRAINT_PROXY[EConstraintType.FIXED] = function createFixedConstraint() {
          if (check(selector.wrapper.FixedConstraint, ECheckType.FixedConstraint)) {
            return ENTIRE_CONSTRAINT;
          }
          return new selector.wrapper.FixedConstraint();
        };
        CREATE_CONSTRAINT_PROXY[EConstraintType.CONFIGURABLE] = function createConfigurableConstraint() {
          if (check(selector.wrapper.ConfigurableConstraint, ECheckType.ConfigurableConstraint)) {
            return ENTIRE_CONSTRAINT;
          }
          return new selector.wrapper.ConfigurableConstraint();
        };
      }
      var CREATE_CHARACTER_CONTROLLER_PROXY = {
        INITED: false
      };
      var ENTIRE_CHARACTER_CONTROLLER = {
        initialize: FUNC,
        onLoad: FUNC,
        onEnable: FUNC,
        onDisable: FUNC,
        onDestroy: FUNC,
        onGround: FUNC,
        getPosition: FUNC,
        setPosition: FUNC,
        setStepOffset: FUNC,
        setSlopeLimit: FUNC,
        setContactOffset: FUNC,
        setDetectCollisions: FUNC,
        setOverlapRecovery: FUNC,
        setGroup: FUNC,
        getGroup: FUNC,
        addGroup: FUNC,
        removeGroup: FUNC,
        setMask: FUNC,
        getMask: FUNC,
        addMask: FUNC,
        removeMask: FUNC,
        move: FUNC,
        syncPhysicsToScene: FUNC,
        updateEventListener: FUNC,
        setHalfHeight: FUNC,
        setHalfSideExtent: FUNC,
        setHalfForwardExtent: FUNC,
        setRadius: FUNC,
        setHeight: FUNC
      };
      function createCharacterController(type) {
        initCharacterControllerProxy();
        return CREATE_CHARACTER_CONTROLLER_PROXY[type]();
      }
      function initCharacterControllerProxy() {
        if (CREATE_CHARACTER_CONTROLLER_PROXY.INITED) return;
        CREATE_CHARACTER_CONTROLLER_PROXY.INITED = true;
        CREATE_CHARACTER_CONTROLLER_PROXY[ECharacterControllerType.BOX] = function createBoxCharacterController() {
          if (check(selector.wrapper.BoxCharacterController, ECheckType.BoxCharacterController)) {
            return ENTIRE_CHARACTER_CONTROLLER;
          }
          return new selector.wrapper.BoxCharacterController();
        };
        CREATE_CHARACTER_CONTROLLER_PROXY[ECharacterControllerType.CAPSULE] = function createCapsuleCharacterController() {
          if (check(selector.wrapper.CapsuleCharacterController, ECheckType.CapsuleCharacterController)) {
            return ENTIRE_CHARACTER_CONTROLLER;
          }
          return new selector.wrapper.CapsuleCharacterController();
        };
      }

      var _dec$F, _dec2$C, _dec3$r, _dec4$m, _dec5$k, _class$E, _class2$C, _initializer$B, _initializer2$y, _initializer3$o, _initializer4$i, _class3$h;
      var PhysicsMaterial = exports('eM', (_dec$F = ccclass$n('cc.PhysicsMaterial'), _dec2$C = type$7(CCFloat), _dec3$r = type$7(CCFloat), _dec4$m = type$7(CCFloat), _dec5$k = type$7(CCFloat), _dec$F(_class$E = (_class2$C = (_class3$h = function (_Asset) {
        _inheritsLoose(PhysicsMaterial, _Asset);
        function PhysicsMaterial() {
          var _this;
          _this = _Asset.call(this) || this;
          _this.id = void 0;
          _this._friction = _initializer$B && _initializer$B();
          _this._rollingFriction = _initializer2$y && _initializer2$y();
          _this._spinningFriction = _initializer3$o && _initializer3$o();
          _this._restitution = _initializer4$i && _initializer4$i();
          PhysicsMaterial.allMaterials.push(_assertThisInitialized(_this));
          _this.id = PhysicsMaterial._idCounter++;
          if (!_this._uuid) _this._uuid = "pm_" + _this.id;
          return _this;
        }
        var _proto = PhysicsMaterial.prototype;
        _proto.clone = function clone() {
          var c = new PhysicsMaterial();
          c._friction = this._friction;
          c._restitution = this._restitution;
          c._rollingFriction = this._rollingFriction;
          c._spinningFriction = this._spinningFriction;
          return c;
        };
        _proto.destroy = function destroy() {
          if (_Asset.prototype.destroy.call(this)) {
            var idx = PhysicsMaterial.allMaterials.indexOf(this);
            if (idx >= 0) {
              PhysicsMaterial.allMaterials.splice(idx, 1);
            }
            return true;
          }
          return false;
        };
        _proto.setValues = function setValues(friction, rollingFriction, spinningFriction, restitution) {
          var emitUpdate = this._friction !== friction || this._rollingFriction !== rollingFriction || this._spinningFriction !== spinningFriction || this._restitution !== restitution;
          this._friction = friction;
          this._rollingFriction = rollingFriction;
          this._spinningFriction = spinningFriction;
          this._restitution = restitution;
          if (emitUpdate) this.emit(PhysicsMaterial.EVENT_UPDATE);
        };
        _createClass(PhysicsMaterial, [{
          key: "friction",
          get: function get() {
            return this._friction;
          },
          set: function set(value) {
            if (!equals$1(this._friction, value)) {
              this._friction = value;
              this.emit(PhysicsMaterial.EVENT_UPDATE);
            }
          }
        }, {
          key: "rollingFriction",
          get: function get() {
            return this._rollingFriction;
          },
          set: function set(value) {
            if (!equals$1(this._rollingFriction, value)) {
              this._rollingFriction = value;
              this.emit(PhysicsMaterial.EVENT_UPDATE);
            }
          }
        }, {
          key: "spinningFriction",
          get: function get() {
            return this._spinningFriction;
          },
          set: function set(value) {
            if (!equals$1(this._spinningFriction, value)) {
              this._spinningFriction = value;
              this.emit(PhysicsMaterial.EVENT_UPDATE);
            }
          }
        }, {
          key: "restitution",
          get: function get() {
            return this._restitution;
          },
          set: function set(value) {
            if (!equals$1(this._restitution, value)) {
              this._restitution = value;
              this.emit(PhysicsMaterial.EVENT_UPDATE);
            }
          }
        }]);
        return PhysicsMaterial;
      }(Asset), _class3$h.allMaterials = [], _class3$h.EVENT_UPDATE = 'event_update', _class3$h._idCounter = 0, _class3$h), (_applyDecoratedDescriptor(_class2$C.prototype, "friction", [_dec2$C], Object.getOwnPropertyDescriptor(_class2$C.prototype, "friction"), _class2$C.prototype), _applyDecoratedDescriptor(_class2$C.prototype, "rollingFriction", [_dec3$r], Object.getOwnPropertyDescriptor(_class2$C.prototype, "rollingFriction"), _class2$C.prototype), _applyDecoratedDescriptor(_class2$C.prototype, "spinningFriction", [_dec4$m], Object.getOwnPropertyDescriptor(_class2$C.prototype, "spinningFriction"), _class2$C.prototype), _applyDecoratedDescriptor(_class2$C.prototype, "restitution", [_dec5$k], Object.getOwnPropertyDescriptor(_class2$C.prototype, "restitution"), _class2$C.prototype), _initializer$B = applyDecoratedInitializer(_class2$C.prototype, "_friction", [serializable$j], function () {
        return 0.6;
      }), _initializer2$y = applyDecoratedInitializer(_class2$C.prototype, "_rollingFriction", [serializable$j], function () {
        return 0.0;
      }), _initializer3$o = applyDecoratedInitializer(_class2$C.prototype, "_spinningFriction", [serializable$j], function () {
        return 0.0;
      }), _initializer4$i = applyDecoratedInitializer(_class2$C.prototype, "_restitution", [serializable$j], function () {
        return 0.0;
      })), _class2$C)) || _class$E));

      var PhysicsRayResult = exports('eN', function () {
        function PhysicsRayResult() {
          this._hitPoint = new Vec3();
          this._hitNormal = new Vec3();
          this._distance = 0;
          this._collider = null;
        }
        var _proto = PhysicsRayResult.prototype;
        _proto._assign = function _assign(hitPoint, distance, collider, hitNormal) {
          Vec3.copy(this._hitPoint, hitPoint);
          Vec3.copy(this._hitNormal, hitNormal);
          this._distance = distance;
          this._collider = collider;
        };
        _proto.clone = function clone() {
          var c = new PhysicsRayResult();
          Vec3.copy(c._hitPoint, this._hitPoint);
          Vec3.copy(c._hitNormal, this._hitNormal);
          c._distance = this._distance;
          c._collider = this._collider;
          return c;
        };
        _createClass(PhysicsRayResult, [{
          key: "hitPoint",
          get: function get() {
            return this._hitPoint;
          }
        }, {
          key: "distance",
          get: function get() {
            return this._distance;
          }
        }, {
          key: "collider",
          get: function get() {
            return this._collider;
          }
        }, {
          key: "hitNormal",
          get: function get() {
            return this._hitNormal;
          }
        }]);
        return PhysicsRayResult;
      }());
      var PhysicsLineStripCastResult = exports('eO', function (_PhysicsRayResult) {
        _inheritsLoose(PhysicsLineStripCastResult, _PhysicsRayResult);
        function PhysicsLineStripCastResult() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _PhysicsRayResult.call.apply(_PhysicsRayResult, [this].concat(args)) || this;
          _this._id = 0;
          return _this;
        }
        var _proto2 = PhysicsLineStripCastResult.prototype;
        _proto2._assign = function _assign(hitPoint, distance, collider, hitNormal, id) {
          if (id === void 0) {
            id = 0;
          }
          _PhysicsRayResult.prototype._assign.call(this, hitPoint, distance, collider, hitNormal);
          this._id = id;
        };
        _proto2.clone = function clone() {
          var c = new PhysicsLineStripCastResult();
          Vec3.copy(c._hitPoint, this._hitPoint);
          Vec3.copy(c._hitNormal, this._hitNormal);
          c._distance = this._distance;
          c._collider = this._collider;
          c._id = this._id;
          return c;
        };
        _createClass(PhysicsLineStripCastResult, [{
          key: "id",
          get: function get() {
            return this._id;
          }
        }]);
        return PhysicsLineStripCastResult;
      }(PhysicsRayResult));

      var CollisionMatrix = function CollisionMatrix(strategy) {
        if (strategy === 1) {
          var self = this;
          var _loop = function _loop(i) {
            var key = "_" + (1 << i);
            self[key] = 0;
            self.updateArray = [];
            Object.defineProperty(self, 1 << i, {
              get: function get() {
                return this[key];
              },
              set: function set(v) {
                if (this[key] !== v) {
                  this[key] = v;
                  if (this.updateArray.indexOf(i) < 0) {
                    this.updateArray.push(i);
                  }
                }
              }
            });
          };
          for (var i = 0; i < 32; i++) {
            _loop(i);
          }
          this['_1'] = PhysicsGroup.DEFAULT;
        } else {
          for (var _i = 0; _i < 32; _i++) {
            var key = 1 << _i;
            this["" + key] = 0;
          }
          this['1'] = PhysicsGroup.DEFAULT;
        }
      };

      legacyCC.internal.PhysicsGroup = PhysicsGroup;
      var PhysicsSystem = exports('eI', function (_System) {
        _inheritsLoose(PhysicsSystem, _System);
        var _proto = PhysicsSystem.prototype;
        _proto.setDefaultPhysicsMaterial = function setDefaultPhysicsMaterial(material) {
          this._material = material;
          this.physicsWorld.setDefaultMaterial(this._material);
          this._material.on(PhysicsMaterial.EVENT_UPDATE, this._updateMaterial, this);
        };
        _proto.initDefaultMaterial = function initDefaultMaterial() {
          var _this2 = this;
          if (this._material != null) return Promise.resolve();
          var builtinMaterial = builtinResMgr.get('default-physics-material');
          if (!builtinMaterial) {
            console.error('PhysicsSystem initDefaultMaterial() Failed to load builtinMaterial');
            return Promise.resolve();
          }
          var userMaterial = settings.querySettings(Settings.Category.PHYSICS, 'defaultMaterial');
          if (!userMaterial) {
            this.setDefaultPhysicsMaterial(builtinMaterial);
            return Promise.resolve();
          } else {
            return new Promise(function (resolve, reject) {
              assetManager.loadAny(userMaterial, function (err, asset) {
                return err || !(asset instanceof PhysicsMaterial) ? reject(err) : resolve(asset);
              });
            }).then(function (asset) {
              _this2.setDefaultPhysicsMaterial(asset);
            })["catch"](function (reason) {
              warn(reason);
              warn("Failed to load user customized default physics material: " + userMaterial + ", will fallback to built-in default physics material");
              _this2.setDefaultPhysicsMaterial(builtinMaterial);
            });
          }
        };
        function PhysicsSystem() {
          var _this;
          _this = _System.call(this) || this;
          _this.raycastClosestResult = new PhysicsRayResult();
          _this.raycastResults = [];
          _this.lineStripCastClosestResult = new PhysicsLineStripCastResult();
          _this.lineStripCastResults = [];
          _this.sweepCastClosestResult = new PhysicsRayResult();
          _this.sweepCastResults = [];
          _this.collisionMatrix = new CollisionMatrix(1);
          _this.minVolumeSize = 1e-5;
          _this.useNodeChains = false;
          _this._enable = true;
          _this._allowSleep = true;
          _this._maxSubSteps = 1;
          _this._subStepCount = 0;
          _this._fixedTimeStep = 1.0 / 60.0;
          _this._autoSimulation = true;
          _this._accumulator = 0;
          _this._sleepThreshold = 0.1;
          _this._gravity = new Vec3(0, -10, 0);
          _this._material = void 0;
          _this.raycastOptions = {
            group: -1,
            mask: -1,
            queryTrigger: true,
            maxDistance: 10000000
          };
          _this.raycastResultPool = new RecyclePool(function () {
            return new PhysicsRayResult();
          }, 1);
          _this.sweepResultPool = new RecyclePool(function () {
            return new PhysicsRayResult();
          }, 1);
          return _this;
        }
        _proto.postUpdate = function postUpdate(deltaTime) {
          if (!this.physicsWorld) return;
          if (!this._enable) {
            this.physicsWorld.syncSceneToPhysics();
            return;
          }
          if (this._autoSimulation) {
            this._subStepCount = 0;
            this._accumulator += deltaTime;
            director.emit(Director.EVENT_BEFORE_PHYSICS);
            while (this._subStepCount < this._maxSubSteps) {
              if (this._accumulator >= this._fixedTimeStep) {
                this.physicsWorld.syncSceneToPhysics();
                this.physicsWorld.step(this._fixedTimeStep);
                this.physicsWorld.emitEvents();
                this.physicsWorld.syncAfterEvents();
                this._accumulator -= this._fixedTimeStep;
                this._subStepCount++;
              } else {
                this.physicsWorld.syncSceneToPhysics();
                break;
              }
            }
            director.emit(Director.EVENT_AFTER_PHYSICS);
          }
        };
        _proto.resetConfiguration = function resetConfiguration(config) {
          var allowSleep = config ? config.allowSleep : settings.querySettings(Settings.Category.PHYSICS, 'allowSleep');
          if (typeof allowSleep === 'boolean') this._allowSleep = allowSleep;
          var fixedTimeStep = config ? config.fixedTimeStep : settings.querySettings(Settings.Category.PHYSICS, 'fixedTimeStep');
          if (typeof fixedTimeStep === 'number') this._fixedTimeStep = fixedTimeStep;
          var maxSubSteps = config ? config.maxSubSteps : settings.querySettings(Settings.Category.PHYSICS, 'maxSubSteps');
          if (typeof maxSubSteps === 'number') this._maxSubSteps = maxSubSteps;
          var sleepThreshold = config ? config.sleepThreshold : settings.querySettings(Settings.Category.PHYSICS, 'sleepThreshold');
          if (typeof sleepThreshold === 'number') this._sleepThreshold = sleepThreshold;
          var autoSimulation = config ? config.autoSimulation : settings.querySettings(Settings.Category.PHYSICS, 'autoSimulation');
          if (typeof autoSimulation === 'boolean') this.autoSimulation = autoSimulation;
          var gravity = config ? config.gravity : settings.querySettings(Settings.Category.PHYSICS, 'gravity');
          if (gravity) Vec3.copy(this._gravity, gravity);
          var collisionMatrix = config ? config.collisionMatrix : settings.querySettings(Settings.Category.PHYSICS, 'collisionMatrix');
          if (collisionMatrix) {
            for (var i in collisionMatrix) {
              this.collisionMatrix["" + (1 << parseInt(i))] = collisionMatrix[i];
            }
          }
          var collisionGroups = config ? config.collisionGroups : settings.querySettings(Settings.Category.PHYSICS, 'collisionGroups');
          if (collisionGroups) {
            var cg = collisionGroups;
            if (cg instanceof Array) {
              cg.forEach(function (v) {
                PhysicsGroup[v.name] = 1 << v.index;
              });
              Enum.update(PhysicsGroup);
            }
          }
          if (this.physicsWorld) {
            this.physicsWorld.setGravity(this._gravity);
            this.physicsWorld.setAllowSleep(this._allowSleep);
          }
        };
        _proto.resetAccumulator = function resetAccumulator(time) {
          if (time === void 0) {
            time = 0;
          }
          this._accumulator = time;
        };
        _proto.step = function step(fixedTimeStep, deltaTime, maxSubSteps) {
          if (this.physicsWorld) this.physicsWorld.step(fixedTimeStep, deltaTime, maxSubSteps);
        };
        _proto.syncSceneToPhysics = function syncSceneToPhysics() {
          if (this.physicsWorld) this.physicsWorld.syncSceneToPhysics();
        };
        _proto.emitEvents = function emitEvents() {
          if (this.physicsWorld) this.physicsWorld.emitEvents();
        };
        _proto.raycast = function raycast(worldRay, mask, maxDistance, queryTrigger) {
          if (mask === void 0) {
            mask = 0xffffffff;
          }
          if (maxDistance === void 0) {
            maxDistance = 10000000;
          }
          if (queryTrigger === void 0) {
            queryTrigger = true;
          }
          if (!this.physicsWorld) return false;
          this.raycastResultPool.reset();
          this.raycastResults.length = 0;
          this.raycastOptions.mask = mask >>> 0;
          this.raycastOptions.maxDistance = maxDistance;
          this.raycastOptions.queryTrigger = queryTrigger;
          return this.physicsWorld.raycast(worldRay, this.raycastOptions, this.raycastResultPool, this.raycastResults);
        };
        _proto.raycastClosest = function raycastClosest(worldRay, mask, maxDistance, queryTrigger) {
          if (mask === void 0) {
            mask = 0xffffffff;
          }
          if (maxDistance === void 0) {
            maxDistance = 10000000;
          }
          if (queryTrigger === void 0) {
            queryTrigger = true;
          }
          if (!this.physicsWorld) return false;
          this.raycastOptions.mask = mask >>> 0;
          this.raycastOptions.maxDistance = maxDistance;
          this.raycastOptions.queryTrigger = queryTrigger;
          return this.physicsWorld.raycastClosest(worldRay, this.raycastOptions, this.raycastClosestResult);
        };
        _proto.lineStripCast = function lineStripCast(samplePointsWorldSpace, mask, maxDistance, queryTrigger) {
          if (mask === void 0) {
            mask = 0xffffffff;
          }
          if (maxDistance === void 0) {
            maxDistance = 10000000;
          }
          if (queryTrigger === void 0) {
            queryTrigger = true;
          }
          if (samplePointsWorldSpace.length < 2) return false;
          this.lineStripCastResults = [];
          var distance = 0;
          var worldRay = new Ray();
          for (var i = 1; i < samplePointsWorldSpace.length; ++i) {
            if (distance > maxDistance) break;
            var fromPoint = samplePointsWorldSpace[i - 1];
            var toPoint = samplePointsWorldSpace[i];
            var direction = new Vec3();
            Vec3.subtract(direction, toPoint, fromPoint);
            var stepLength = Vec3.len(direction);
            distance += stepLength;
            Vec3.multiplyScalar(direction, direction, 1.0 / stepLength);
            worldRay.d = direction;
            worldRay.o = fromPoint;
            var hit = this.raycast(worldRay, mask, stepLength, queryTrigger);
            if (hit) {
              for (var re = 0; re < this.raycastResults.length; re++) {
                var result = this.raycastResults[re];
                if (re === 0 && Vec3.equals(fromPoint, result.hitPoint)) {
                  continue;
                }
                var copiedResult = new PhysicsLineStripCastResult();
                copiedResult._assign(result.hitPoint, result.distance, result.collider, result.hitNormal, i - 1);
                this.lineStripCastResults.push(copiedResult);
              }
            }
          }
          return this.lineStripCastResults.length > 0;
        };
        _proto.lineStripCastClosest = function lineStripCastClosest(samplePointsWorldSpace, mask, maxDistance, queryTrigger) {
          if (mask === void 0) {
            mask = 0xffffffff;
          }
          if (maxDistance === void 0) {
            maxDistance = 10000000;
          }
          if (queryTrigger === void 0) {
            queryTrigger = true;
          }
          if (samplePointsWorldSpace.length < 2) {
            return false;
          }
          var distance = 0;
          var worldRay = new Ray();
          var hit = false;
          for (var i = 1; i < samplePointsWorldSpace.length; ++i) {
            if (distance > maxDistance) break;
            var fromPoint = samplePointsWorldSpace[i - 1];
            var toPoint = samplePointsWorldSpace[i];
            var direction = new Vec3();
            Vec3.subtract(direction, toPoint, fromPoint);
            var stepLength = Vec3.len(direction);
            distance += stepLength;
            Vec3.multiplyScalar(direction, direction, 1.0 / stepLength);
            worldRay.d = direction;
            worldRay.o = fromPoint;
            hit = this.raycastClosest(worldRay, mask, stepLength, queryTrigger);
            if (hit) {
              var result = this.raycastClosestResult;
              var copiedResult = new PhysicsLineStripCastResult();
              copiedResult._assign(result.hitPoint, result.distance, result.collider, result.hitNormal, i - 1);
              this.lineStripCastClosestResult = copiedResult;
              break;
            }
          }
          return hit;
        };
        _proto.sweepBox = function sweepBox(worldRay, halfExtent, orientation, mask, maxDistance, queryTrigger) {
          if (mask === void 0) {
            mask = 0xffffffff;
          }
          if (maxDistance === void 0) {
            maxDistance = 10000000;
          }
          if (queryTrigger === void 0) {
            queryTrigger = true;
          }
          if (!this.physicsWorld) return false;
          this.sweepResultPool.reset();
          this.sweepCastResults.length = 0;
          this.raycastOptions.mask = mask >>> 0;
          this.raycastOptions.maxDistance = maxDistance;
          this.raycastOptions.queryTrigger = queryTrigger;
          return this.physicsWorld.sweepBox(worldRay, halfExtent, orientation, this.raycastOptions, this.sweepResultPool, this.sweepCastResults);
        };
        _proto.sweepBoxClosest = function sweepBoxClosest(worldRay, halfExtent, orientation, mask, maxDistance, queryTrigger) {
          if (mask === void 0) {
            mask = 0xffffffff;
          }
          if (maxDistance === void 0) {
            maxDistance = 10000000;
          }
          if (queryTrigger === void 0) {
            queryTrigger = true;
          }
          if (!this.physicsWorld) return false;
          this.raycastOptions.mask = mask >>> 0;
          this.raycastOptions.maxDistance = maxDistance;
          this.raycastOptions.queryTrigger = queryTrigger;
          return this.physicsWorld.sweepBoxClosest(worldRay, halfExtent, orientation, this.raycastOptions, this.sweepCastClosestResult);
        };
        _proto.sweepSphere = function sweepSphere(worldRay, radius, mask, maxDistance, queryTrigger) {
          if (mask === void 0) {
            mask = 0xffffffff;
          }
          if (maxDistance === void 0) {
            maxDistance = 10000000;
          }
          if (queryTrigger === void 0) {
            queryTrigger = true;
          }
          if (!this.physicsWorld) return false;
          this.sweepResultPool.reset();
          this.sweepCastResults.length = 0;
          this.raycastOptions.mask = mask >>> 0;
          this.raycastOptions.maxDistance = maxDistance;
          this.raycastOptions.queryTrigger = queryTrigger;
          return this.physicsWorld.sweepSphere(worldRay, radius, this.raycastOptions, this.sweepResultPool, this.sweepCastResults);
        };
        _proto.sweepSphereClosest = function sweepSphereClosest(worldRay, radius, mask, maxDistance, queryTrigger) {
          if (mask === void 0) {
            mask = 0xffffffff;
          }
          if (maxDistance === void 0) {
            maxDistance = 10000000;
          }
          if (queryTrigger === void 0) {
            queryTrigger = true;
          }
          if (!this.physicsWorld) return false;
          this.raycastOptions.mask = mask >>> 0;
          this.raycastOptions.maxDistance = maxDistance;
          this.raycastOptions.queryTrigger = queryTrigger;
          return this.physicsWorld.sweepSphereClosest(worldRay, radius, this.raycastOptions, this.sweepCastClosestResult);
        };
        _proto.sweepCapsule = function sweepCapsule(worldRay, radius, height, orientation, mask, maxDistance, queryTrigger) {
          if (mask === void 0) {
            mask = 0xffffffff;
          }
          if (maxDistance === void 0) {
            maxDistance = 10000000;
          }
          if (queryTrigger === void 0) {
            queryTrigger = true;
          }
          if (!this.physicsWorld) return false;
          this.sweepResultPool.reset();
          this.sweepCastResults.length = 0;
          this.raycastOptions.mask = mask >>> 0;
          this.raycastOptions.maxDistance = maxDistance;
          this.raycastOptions.queryTrigger = queryTrigger;
          return this.physicsWorld.sweepCapsule(worldRay, radius, height, orientation, this.raycastOptions, this.sweepResultPool, this.sweepCastResults);
        };
        _proto.sweepCapsuleClosest = function sweepCapsuleClosest(worldRay, radius, height, orientation, mask, maxDistance, queryTrigger) {
          if (mask === void 0) {
            mask = 0xffffffff;
          }
          if (maxDistance === void 0) {
            maxDistance = 10000000;
          }
          if (queryTrigger === void 0) {
            queryTrigger = true;
          }
          if (!this.physicsWorld) return false;
          this.raycastOptions.mask = mask >>> 0;
          this.raycastOptions.maxDistance = maxDistance;
          this.raycastOptions.queryTrigger = queryTrigger;
          return this.physicsWorld.sweepCapsuleClosest(worldRay, radius, height, orientation, this.raycastOptions, this.sweepCastClosestResult);
        };
        _proto._updateMaterial = function _updateMaterial() {
          if (this.physicsWorld) this.physicsWorld.setDefaultMaterial(this._material);
        };
        PhysicsSystem.constructAndRegister = function constructAndRegister() {
          var _settings$querySettin;
          var enabled = (_settings$querySettin = settings.querySettings(Settings.Category.PHYSICS, 'enabled')) !== null && _settings$querySettin !== void 0 ? _settings$querySettin : true;
          if (!enabled) {
            return;
          }
          if (!PhysicsSystem._instance) {
            var sys = new PhysicsSystem();
            PhysicsSystem._instance = sys;
            sys.resetConfiguration();
            constructDefaultWorld(sys);
            director.registerSystem(PhysicsSystem.ID, sys, sys.priority);
            game.onPostProjectInitDelegate.add(sys.initDefaultMaterial.bind(sys));
          }
        };
        _createClass(PhysicsSystem, [{
          key: "enable",
          get: function get() {
            return this._enable;
          },
          set: function set(value) {
            this._enable = value;
          }
        }, {
          key: "allowSleep",
          get: function get() {
            return this._allowSleep;
          },
          set: function set(v) {
            this._allowSleep = v;
            if (this.physicsWorld) {
              this.physicsWorld.setAllowSleep(v);
            }
          }
        }, {
          key: "maxSubSteps",
          get: function get() {
            return this._maxSubSteps;
          },
          set: function set(value) {
            this._maxSubSteps = value;
          }
        }, {
          key: "fixedTimeStep",
          get: function get() {
            return this._fixedTimeStep;
          },
          set: function set(value) {
            this._fixedTimeStep = value;
          }
        }, {
          key: "gravity",
          get: function get() {
            return this._gravity;
          },
          set: function set(gravity) {
            this._gravity.set(gravity);
            if (this.physicsWorld) {
              this.physicsWorld.setGravity(gravity);
            }
          }
        }, {
          key: "sleepThreshold",
          get: function get() {
            return this._sleepThreshold;
          },
          set: function set(v) {
            this._sleepThreshold = v;
          }
        }, {
          key: "autoSimulation",
          get: function get() {
            return this._autoSimulation;
          },
          set: function set(value) {
            this._autoSimulation = value;
          }
        }, {
          key: "defaultMaterial",
          get: function get() {
            return this._material;
          }
        }, {
          key: "physicsWorld",
          get: function get() {
            return selector.physicsWorld;
          }
        }], [{
          key: "PHYSICS_NONE",
          get: function get() {
            return !selector.id;
          }
        }, {
          key: "PHYSICS_BUILTIN",
          get: function get() {
            return selector.id === 'builtin';
          }
        }, {
          key: "PHYSICS_CANNON",
          get: function get() {
            return selector.id === 'cannon.js';
          }
        }, {
          key: "PHYSICS_BULLET",
          get: function get() {
            return selector.id === 'bullet';
          }
        }, {
          key: "PHYSICS_PHYSX",
          get: function get() {
            return selector.id === 'physx';
          }
        }, {
          key: "PhysicsGroup",
          get: function get() {
            return PhysicsGroup;
          }
        }, {
          key: "instance",
          get: function get() {
            return PhysicsSystem._instance;
          }
        }]);
        return PhysicsSystem;
      }(System));
      PhysicsSystem.ID = 'PHYSICS';
      PhysicsSystem._instance = null;
      director.once(Director.EVENT_INIT, function () {
        PhysicsSystem.constructAndRegister();
      });

      var _dec$E, _dec2$B, _dec3$q, _dec4$l, _class$D, _class2$B, _initializer$A, _initializer2$x, _initializer3$n, _initializer4$h, _initializer5$d, _initializer6$a, _initializer7$9, _initializer8$8, _initializer9$8, _class3$g;
      var RigidBody = exports('eJ', (_dec$E = ccclass$n('cc.RigidBody'), _dec2$B = executionOrder$1(-1), _dec3$q = type$7(PhysicsSystem.PhysicsGroup), _dec4$l = type$7(ERigidBodyType), _dec$E(_class$D = disallowMultiple$1(_class$D = _dec2$B(_class$D = (_class2$B = (_class3$g = function (_Component) {
        _inheritsLoose(RigidBody, _Component);
        function RigidBody() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Component.call.apply(_Component, [this].concat(args)) || this;
          _this._body = null;
          _this._group = _initializer$A && _initializer$A();
          _this._type = _initializer2$x && _initializer2$x();
          _this._mass = _initializer3$n && _initializer3$n();
          _this._allowSleep = _initializer4$h && _initializer4$h();
          _this._linearDamping = _initializer5$d && _initializer5$d();
          _this._angularDamping = _initializer6$a && _initializer6$a();
          _this._useGravity = _initializer7$9 && _initializer7$9();
          _this._linearFactor = _initializer8$8 && _initializer8$8();
          _this._angularFactor = _initializer9$8 && _initializer9$8();
          return _this;
        }
        var _proto = RigidBody.prototype;
        _proto.onLoad = function onLoad() {
          if (!selector.runInEditor) return;
          this._body = createRigidBody();
          this._body.initialize(this);
        };
        _proto.onEnable = function onEnable() {
          if (this._body) this._body.onEnable();
        };
        _proto.onDisable = function onDisable() {
          if (this._body) this._body.onDisable();
        };
        _proto.onDestroy = function onDestroy() {
          if (this._body) this._body.onDestroy();
        };
        _proto.applyForce = function applyForce(force, relativePoint) {
          if (this._isInitialized) this._body.applyForce(force, relativePoint);
        };
        _proto.applyLocalForce = function applyLocalForce(force, localPoint) {
          if (this._isInitialized) this._body.applyLocalForce(force, localPoint);
        };
        _proto.applyImpulse = function applyImpulse(impulse, relativePoint) {
          if (this._isInitialized) this._body.applyImpulse(impulse, relativePoint);
        };
        _proto.applyLocalImpulse = function applyLocalImpulse(impulse, localPoint) {
          if (this._isInitialized) this._body.applyLocalImpulse(impulse, localPoint);
        };
        _proto.applyTorque = function applyTorque(torque) {
          if (this._isInitialized) this._body.applyTorque(torque);
        };
        _proto.applyLocalTorque = function applyLocalTorque(torque) {
          if (this._isInitialized) this._body.applyLocalTorque(torque);
        };
        _proto.wakeUp = function wakeUp() {
          if (this._isInitialized) this._body.wakeUp();
        };
        _proto.sleep = function sleep() {
          if (this._isInitialized) this._body.sleep();
        };
        _proto.clearState = function clearState() {
          if (this._isInitialized) this._body.clearState();
        };
        _proto.clearForces = function clearForces() {
          if (this._isInitialized) this._body.clearForces();
        };
        _proto.clearVelocity = function clearVelocity() {
          if (this._isInitialized) this._body.clearVelocity();
        };
        _proto.getLinearVelocity = function getLinearVelocity(out) {
          if (this._isInitialized) this._body.getLinearVelocity(out);
        };
        _proto.setLinearVelocity = function setLinearVelocity(value) {
          if (this._isInitialized) this._body.setLinearVelocity(value);
        };
        _proto.getAngularVelocity = function getAngularVelocity(out) {
          if (this._isInitialized) this._body.getAngularVelocity(out);
        };
        _proto.setAngularVelocity = function setAngularVelocity(value) {
          if (this._isInitialized) this._body.setAngularVelocity(value);
        };
        _proto.getGroup = function getGroup() {
          if (this._isInitialized) return this._body.getGroup();
          return 0;
        };
        _proto.setGroup = function setGroup(v) {
          if (this._isInitialized) this._body.setGroup(v);
        };
        _proto.addGroup = function addGroup(v) {
          if (this._isInitialized) this._body.addGroup(v);
        };
        _proto.removeGroup = function removeGroup(v) {
          if (this._isInitialized) this._body.removeGroup(v);
        };
        _proto.getMask = function getMask() {
          if (this._isInitialized) return this._body.getMask();
          return 0;
        };
        _proto.setMask = function setMask(v) {
          if (this._isInitialized) this._body.setMask(v);
        };
        _proto.addMask = function addMask(v) {
          if (this._isInitialized) this._body.addMask(v);
        };
        _proto.removeMask = function removeMask(v) {
          if (this._isInitialized) this._body.removeMask(v);
        };
        _createClass(RigidBody, [{
          key: "group",
          get: function get() {
            return this._group;
          },
          set: function set(v) {
            if (!Number.isInteger(Math.log2(v >>> 0))) warn('[Physics]: The group should only have one bit.');
            this._group = v;
            if (this._body) {
              if (this._body.getGroup() !== v) this._body.setGroup(v);
            }
          }
        }, {
          key: "type",
          get: function get() {
            return this._type;
          },
          set: function set(v) {
            if (this._type === v) return;
            this._type = v;
            if (this._body) this._body.setType(v);
          }
        }, {
          key: "mass",
          get: function get() {
            return this._mass;
          },
          set: function set(value) {
            if (value <= 0) warn('[Physics]: The mass should be greater than zero.');
            if (this._mass === value) return;
            value = value <= 0 ? 0.0001 : value;
            this._mass = value;
            if (this._body) this._body.setMass(value);
          }
        }, {
          key: "allowSleep",
          get: function get() {
            return this._allowSleep;
          },
          set: function set(v) {
            this._allowSleep = v;
            if (this._body) this._body.setAllowSleep(v);
          }
        }, {
          key: "linearDamping",
          get: function get() {
            return this._linearDamping;
          },
          set: function set(value) {
            if ((value < 0 || value > 1)) warn('[Physics]: The damping should be between zero to one.');
            this._linearDamping = value;
            if (this._body) this._body.setLinearDamping(value);
          }
        }, {
          key: "angularDamping",
          get: function get() {
            return this._angularDamping;
          },
          set: function set(value) {
            if ((value < 0 || value > 1)) warn('[Physics]: The damping should be between zero to one.');
            this._angularDamping = value;
            if (this._body) this._body.setAngularDamping(value);
          }
        }, {
          key: "useGravity",
          get: function get() {
            return this._useGravity;
          },
          set: function set(value) {
            this._useGravity = value;
            if (this._body) this._body.useGravity(value);
          }
        }, {
          key: "linearFactor",
          get: function get() {
            return this._linearFactor;
          },
          set: function set(value) {
            Vec3.copy(this._linearFactor, value);
            if (this._body) {
              this._body.setLinearFactor(this._linearFactor);
            }
          }
        }, {
          key: "angularFactor",
          get: function get() {
            return this._angularFactor;
          },
          set: function set(value) {
            Vec3.copy(this._angularFactor, value);
            if (this._body) {
              this._body.setAngularFactor(this._angularFactor);
            }
          }
        }, {
          key: "sleepThreshold",
          get: function get() {
            if (this._isInitialized) {
              return this._body.getSleepThreshold();
            }
            return 0.1;
          },
          set: function set(v) {
            if (this._isInitialized) {
              this._body.setSleepThreshold(v);
            }
          }
        }, {
          key: "useCCD",
          get: function get() {
            if (this._isInitialized) {
              return this._body.isUsingCCD();
            }
            return false;
          },
          set: function set(v) {
            if (this._isInitialized) {
              this._body.useCCD(v);
            }
          }
        }, {
          key: "isAwake",
          get: function get() {
            if (this._isInitialized) return this._body.isAwake;
            return false;
          }
        }, {
          key: "isSleepy",
          get: function get() {
            if (this._isInitialized) return this._body.isSleepy;
            return false;
          }
        }, {
          key: "isSleeping",
          get: function get() {
            if (this._isInitialized) return this._body.isSleeping;
            return false;
          }
        }, {
          key: "isStatic",
          get: function get() {
            return this._type === ERigidBodyType.STATIC;
          },
          set: function set(v) {
            if (v && this.isStatic || !v && !this.isStatic) return;
            this.type = v ? ERigidBodyType.STATIC : ERigidBodyType.DYNAMIC;
          }
        }, {
          key: "isDynamic",
          get: function get() {
            return this._type === ERigidBodyType.DYNAMIC;
          },
          set: function set(v) {
            if (v && this.isDynamic || !v && !this.isDynamic) return;
            this.type = v ? ERigidBodyType.DYNAMIC : ERigidBodyType.KINEMATIC;
          }
        }, {
          key: "isKinematic",
          get: function get() {
            return this._type === ERigidBodyType.KINEMATIC;
          },
          set: function set(v) {
            if (v && this.isKinematic || !v && !this.isKinematic) return;
            this.type = v ? ERigidBodyType.KINEMATIC : ERigidBodyType.DYNAMIC;
          }
        }, {
          key: "body",
          get: function get() {
            return this._body;
          }
        }, {
          key: "_isInitialized",
          get: function get() {
            var r = this._body === null;
            if (r) {
              error('[Physics]: This component has not been call onLoad yet, please make sure the node has been added to the scene.');
            }
            return !r;
          }
        }]);
        return RigidBody;
      }(Component), _class3$g.Type = ERigidBodyType, _class3$g), (_applyDecoratedDescriptor(_class2$B.prototype, "group", [_dec3$q], Object.getOwnPropertyDescriptor(_class2$B.prototype, "group"), _class2$B.prototype), _applyDecoratedDescriptor(_class2$B.prototype, "type", [_dec4$l], Object.getOwnPropertyDescriptor(_class2$B.prototype, "type"), _class2$B.prototype), _initializer$A = applyDecoratedInitializer(_class2$B.prototype, "_group", [serializable$j], function () {
        return PhysicsSystem.PhysicsGroup.DEFAULT;
      }), _initializer2$x = applyDecoratedInitializer(_class2$B.prototype, "_type", [serializable$j], function () {
        return ERigidBodyType.DYNAMIC;
      }), _initializer3$n = applyDecoratedInitializer(_class2$B.prototype, "_mass", [serializable$j], function () {
        return 1;
      }), _initializer4$h = applyDecoratedInitializer(_class2$B.prototype, "_allowSleep", [serializable$j], function () {
        return true;
      }), _initializer5$d = applyDecoratedInitializer(_class2$B.prototype, "_linearDamping", [serializable$j], function () {
        return 0.1;
      }), _initializer6$a = applyDecoratedInitializer(_class2$B.prototype, "_angularDamping", [serializable$j], function () {
        return 0.1;
      }), _initializer7$9 = applyDecoratedInitializer(_class2$B.prototype, "_useGravity", [serializable$j], function () {
        return true;
      }), _initializer8$8 = applyDecoratedInitializer(_class2$B.prototype, "_linearFactor", [serializable$j], function () {
        return new Vec3(1, 1, 1);
      }), _initializer9$8 = applyDecoratedInitializer(_class2$B.prototype, "_angularFactor", [serializable$j], function () {
        return new Vec3(1, 1, 1);
      })), _class2$B)) || _class$D) || _class$D) || _class$D));
      (function (_RigidBody) {})(RigidBody || (exports('eJ', RigidBody = {})));

      var _dec$D, _dec2$A, _dec3$p, _dec4$k, _dec5$j, _class$C, _class2$A, _initializer$z, _initializer2$w, _initializer3$m, _class3$f;
      var Collider = exports('eP', (_dec$D = ccclass$n('cc.Collider'), _dec2$A = type$7(RigidBody), _dec3$p = type$7(PhysicsMaterial), _dec4$k = type$7(Vec3), _dec5$j = type$7(PhysicsMaterial), _dec$D(_class$C = (_class2$A = (_class3$f = function (_Eventify) {
        _inheritsLoose(Collider, _Eventify);
        function Collider(type) {
          var _this;
          _this = _Eventify.call(this) || this;
          _this.type = void 0;
          _this._shape = null;
          _this._aabb = null;
          _this._boundingSphere = null;
          _this._isSharedMaterial = true;
          _this._needTriggerEvent = false;
          _this._needCollisionEvent = false;
          _this._material = _initializer$z && _initializer$z();
          _this._isTrigger = _initializer2$w && _initializer2$w();
          _this._center = _initializer3$m && _initializer3$m();
          _this.type = type;
          return _this;
        }
        var _proto = Collider.prototype;
        _proto.on = function on(type, callback, target, once) {
          var ret = _Eventify.prototype.on.call(this, type, callback, target, once);
          this._updateNeedEvent(type);
          return ret;
        };
        _proto.off = function off(type, callback, target) {
          _Eventify.prototype.off.call(this, type, callback, target);
          this._updateNeedEvent();
        };
        _proto.once = function once(type, callback, target) {
          var ret = _Eventify.prototype.once.call(this, type, callback, target);
          this._updateNeedEvent(type);
          return ret;
        };
        _proto.removeAll = function removeAll(typeOrTarget) {
          _Eventify.prototype.removeAll.call(this, typeOrTarget);
          this._updateNeedEvent();
        };
        _proto.getGroup = function getGroup() {
          if (this._isInitialized) {
            return this._shape.getGroup();
          }
          return 0;
        };
        _proto.setGroup = function setGroup(v) {
          if (this._isInitialized) {
            this._shape.setGroup(v);
          }
        };
        _proto.addGroup = function addGroup(v) {
          if (this._isInitialized) {
            this._shape.addGroup(v);
          }
        };
        _proto.removeGroup = function removeGroup(v) {
          if (this._isInitialized) {
            this._shape.removeGroup(v);
          }
        };
        _proto.getMask = function getMask() {
          if (this._isInitialized) {
            return this._shape.getMask();
          }
          return 0;
        };
        _proto.setMask = function setMask(v) {
          if (this._isInitialized) {
            this._shape.setMask(v);
          }
        };
        _proto.addMask = function addMask(v) {
          if (this._isInitialized) {
            this._shape.addMask(v);
          }
        };
        _proto.removeMask = function removeMask(v) {
          if (this._isInitialized) {
            this._shape.removeMask(v);
          }
        };
        _proto.onLoad = function onLoad() {
          if (!selector.runInEditor) return;
          this.sharedMaterial = this._material;
          this._shape = createShape(this.type);
          this._shape.initialize(this);
          this._shape.onLoad();
        };
        _proto.onEnable = function onEnable() {
          if (this._shape) {
            this._shape.onEnable();
          }
        };
        _proto.onDisable = function onDisable() {
          if (this._shape) {
            this._shape.onDisable();
          }
        };
        _proto.onDestroy = function onDestroy() {
          if (this._shape) {
            this._needTriggerEvent = false;
            this._needCollisionEvent = false;
            this._shape.updateEventListener();
            if (this._material) this._material.off(PhysicsMaterial.EVENT_UPDATE, this._updateMaterial, this);
            this._shape.onDestroy();
          }
          if (this._boundingSphere) this._boundingSphere.destroy();
        };
        _proto._updateMaterial = function _updateMaterial() {
          if (this._shape) this._shape.setMaterial(this._material);
        };
        _proto._updateNeedEvent = function _updateNeedEvent(type) {
          if (this.isValid) {
            if (type !== undefined) {
              if (type === 'onCollisionEnter' || type === 'onCollisionStay' || type === 'onCollisionExit') {
                this._needCollisionEvent = true;
              }
              if (type === 'onTriggerEnter' || type === 'onTriggerStay' || type === 'onTriggerExit' || type === 'onControllerTriggerEnter' || type === 'onControllerTriggerStay' || type === 'onControllerTriggerExit') {
                this._needTriggerEvent = true;
              }
            } else {
              if (!(this.hasEventListener('onTriggerEnter') || this.hasEventListener('onTriggerStay') || this.hasEventListener('onTriggerExit') || this.hasEventListener('onControllerTriggerEnter') || this.hasEventListener('onControllerTriggerStay') || this.hasEventListener('onControllerTriggerExit'))) {
                this._needTriggerEvent = false;
              }
              if (!(this.hasEventListener('onCollisionEnter') || this.hasEventListener('onCollisionStay') || this.hasEventListener('onCollisionExit'))) {
                this._needCollisionEvent = false;
              }
            }
            if (this._shape) this._shape.updateEventListener();
          }
        };
        _createClass(Collider, [{
          key: "attachedRigidBody",
          get: function get() {
            return findAttachedBody(this.node);
          }
        }, {
          key: "sharedMaterial",
          get: function get() {
            return this._material;
          },
          set: function set(value) {
            {
              this.material = value;
            }
          }
        }, {
          key: "material",
          get: function get() {
            if (this._isSharedMaterial && this._material) {
              this._material.off(PhysicsMaterial.EVENT_UPDATE, this._updateMaterial, this);
              this._material = this._material.clone();
              this._material.on(PhysicsMaterial.EVENT_UPDATE, this._updateMaterial, this);
              this._isSharedMaterial = false;
            }
            return this._material;
          },
          set: function set(value) {
            if (this._shape) {
              if (value && this._material) {
                if (this._material.id !== value.id) {
                  this._material.off(PhysicsMaterial.EVENT_UPDATE, this._updateMaterial, this);
                  value.on(PhysicsMaterial.EVENT_UPDATE, this._updateMaterial, this);
                  this._isSharedMaterial = false;
                  this._material = value;
                }
              } else if (value && !this._material) {
                value.on(PhysicsMaterial.EVENT_UPDATE, this._updateMaterial, this);
                this._material = value;
              } else if (!value && this._material) {
                this._material.off(PhysicsMaterial.EVENT_UPDATE, this._updateMaterial, this);
                this._material = value;
              }
              this._updateMaterial();
            } else {
              this._material = value;
            }
          }
        }, {
          key: "isTrigger",
          get: function get() {
            return this._isTrigger;
          },
          set: function set(value) {
            this._isTrigger = value;
            if (this._shape) {
              this._shape.setAsTrigger(this._isTrigger);
            }
          }
        }, {
          key: "center",
          get: function get() {
            return this._center;
          },
          set: function set(value) {
            Vec3.copy(this._center, value);
            if (this._shape) {
              this._shape.setCenter(this._center);
            }
          }
        }, {
          key: "shape",
          get: function get() {
            return this._shape;
          }
        }, {
          key: "worldBounds",
          get: function get() {
            if (this._aabb == null) this._aabb = new AABB();
            if (this._shape) this._shape.getAABB(this._aabb);
            return this._aabb;
          }
        }, {
          key: "boundingSphere",
          get: function get() {
            if (this._boundingSphere == null) this._boundingSphere = new Sphere();
            if (this._shape) this._shape.getBoundingSphere(this._boundingSphere);
            return this._boundingSphere;
          }
        }, {
          key: "needTriggerEvent",
          get: function get() {
            return this._needTriggerEvent;
          }
        }, {
          key: "needCollisionEvent",
          get: function get() {
            return this._needCollisionEvent;
          }
        }, {
          key: "_isInitialized",
          get: function get() {
            var r = this._shape === null;
            if (r) {
              error('[Physics]: This component has not been call onLoad yet, please make sure the node has been added to the scene.');
            }
            return !r;
          }
        }]);
        return Collider;
      }(Eventify(Component)), _class3$f.Type = EColliderType, _class3$f.Axis = EAxisDirection, _class3$f), (_applyDecoratedDescriptor(_class2$A.prototype, "attachedRigidBody", [_dec2$A], Object.getOwnPropertyDescriptor(_class2$A.prototype, "attachedRigidBody"), _class2$A.prototype), _applyDecoratedDescriptor(_class2$A.prototype, "sharedMaterial", [_dec3$p], Object.getOwnPropertyDescriptor(_class2$A.prototype, "sharedMaterial"), _class2$A.prototype), _applyDecoratedDescriptor(_class2$A.prototype, "center", [_dec4$k], Object.getOwnPropertyDescriptor(_class2$A.prototype, "center"), _class2$A.prototype), _initializer$z = applyDecoratedInitializer(_class2$A.prototype, "_material", [_dec5$j], function () {
        return null;
      }), _initializer2$w = applyDecoratedInitializer(_class2$A.prototype, "_isTrigger", [serializable$j], function () {
        return false;
      }), _initializer3$m = applyDecoratedInitializer(_class2$A.prototype, "_center", [serializable$j], function () {
        return new Vec3();
      })), _class2$A)) || _class$C));
      (function (_Collider) {})(Collider || (exports('eP', Collider = {})));
      function findAttachedBody(node) {
        var rb = node.getComponent(RigidBody);
        if (rb && rb.isValid) {
          return rb;
        }
        return null;
      }

      var _dec$C, _dec2$z, _class$B, _class2$z, _initializer$y;
      var BoxCollider = exports('eQ', (_dec$C = ccclass$n('cc.BoxCollider'), _dec2$z = type$7(Vec3), _dec$C(_class$B = (_class2$z = function (_Collider) {
        _inheritsLoose(BoxCollider, _Collider);
        function BoxCollider() {
          var _this;
          _this = _Collider.call(this, EColliderType.BOX) || this;
          _this._size = _initializer$y && _initializer$y();
          return _this;
        }
        _createClass(BoxCollider, [{
          key: "size",
          get: function get() {
            return this._size;
          },
          set: function set(value) {
            if (Vec3.strictEquals(this._size, value)) return;
            Vec3.copy(this._size, value);
            absolute(this._size);
            if (this._shape) {
              this.shape.updateSize();
            }
          }
        }, {
          key: "shape",
          get: function get() {
            return this._shape;
          }
        }]);
        return BoxCollider;
      }(Collider), (_applyDecoratedDescriptor(_class2$z.prototype, "size", [_dec2$z], Object.getOwnPropertyDescriptor(_class2$z.prototype, "size"), _class2$z.prototype), _initializer$y = applyDecoratedInitializer(_class2$z.prototype, "_size", [serializable$j], function () {
        return new Vec3(1, 1, 1);
      })), _class2$z)) || _class$B));

      var _dec$B, _class$A, _class2$y, _initializer$x;
      var SphereCollider = exports('eR', (_dec$B = ccclass$n('cc.SphereCollider'), _dec$B(_class$A = (_class2$y = function (_Collider) {
        _inheritsLoose(SphereCollider, _Collider);
        function SphereCollider() {
          var _this;
          _this = _Collider.call(this, EColliderType.SPHERE) || this;
          _this._radius = _initializer$x && _initializer$x();
          return _this;
        }
        _createClass(SphereCollider, [{
          key: "radius",
          get: function get() {
            return this._radius;
          },
          set: function set(value) {
            if (this._radius === value) return;
            this._radius = Math.abs(value);
            if (this._shape) {
              this.shape.updateRadius();
            }
          }
        }, {
          key: "shape",
          get: function get() {
            return this._shape;
          }
        }]);
        return SphereCollider;
      }(Collider), (_initializer$x = applyDecoratedInitializer(_class2$y.prototype, "_radius", [serializable$j], function () {
        return 0.5;
      })), _class2$y)) || _class$A));

      var _dec$A, _dec2$y, _class$z, _class2$x, _initializer$w, _initializer2$v, _initializer3$l;
      var CapsuleCollider = exports('eS', (_dec$A = ccclass$n('cc.CapsuleCollider'), _dec2$y = type$7(EAxisDirection), _dec$A(_class$z = (_class2$x = function (_Collider) {
        _inheritsLoose(CapsuleCollider, _Collider);
        function CapsuleCollider() {
          var _this;
          _this = _Collider.call(this, EColliderType.CAPSULE) || this;
          _this._radius = _initializer$w && _initializer$w();
          _this._cylinderHeight = _initializer2$v && _initializer2$v();
          _this._direction = _initializer3$l && _initializer3$l();
          return _this;
        }
        var _proto = CapsuleCollider.prototype;
        _proto._getRadiusScale = function _getRadiusScale() {
          if (this.node == null) return 1;
          var ws = this.node.worldScale;
          if (this._direction === EAxisDirection.Y_AXIS) return Math.abs(absMax(ws.x, ws.z));
          if (this._direction === EAxisDirection.X_AXIS) return Math.abs(absMax(ws.y, ws.z));
          return Math.abs(absMax(ws.x, ws.y));
        };
        _proto._getHeightScale = function _getHeightScale() {
          if (this.node == null) return 1;
          var ws = this.node.worldScale;
          if (this._direction === EAxisDirection.Y_AXIS) return Math.abs(ws.y);
          if (this._direction === EAxisDirection.X_AXIS) return Math.abs(ws.x);
          return Math.abs(ws.z);
        };
        _createClass(CapsuleCollider, [{
          key: "radius",
          get: function get() {
            return this._radius;
          },
          set: function set(value) {
            if (this._radius === value) return;
            this._radius = Math.abs(value);
            if (this._shape) {
              this.shape.setRadius(value);
            }
          }
        }, {
          key: "cylinderHeight",
          get: function get() {
            return this._cylinderHeight;
          },
          set: function set(value) {
            if (this._cylinderHeight === value) return;
            this._cylinderHeight = Math.abs(value);
            if (this._shape) {
              this.shape.setCylinderHeight(value);
            }
          }
        }, {
          key: "direction",
          get: function get() {
            return this._direction;
          },
          set: function set(value) {
            value = Math.floor(value);
            if (value < EAxisDirection.X_AXIS || value > EAxisDirection.Z_AXIS) return;
            if (this._direction === value) return;
            this._direction = value;
            if (this._shape) {
              this.shape.setDirection(value);
            }
          }
        }, {
          key: "height",
          get: function get() {
            return this._radius * 2 + this._cylinderHeight;
          },
          set: function set(value) {
            var ch = value - this._radius * 2;
            if (ch < 0) ch = 0;
            this.cylinderHeight = ch;
          }
        }, {
          key: "worldHeight",
          get: function get() {
            return this._radius * 2 * this._getRadiusScale() + this._cylinderHeight * this._getHeightScale();
          }
        }, {
          key: "shape",
          get: function get() {
            return this._shape;
          }
        }]);
        return CapsuleCollider;
      }(Collider), (_applyDecoratedDescriptor(_class2$x.prototype, "direction", [_dec2$y], Object.getOwnPropertyDescriptor(_class2$x.prototype, "direction"), _class2$x.prototype), _initializer$w = applyDecoratedInitializer(_class2$x.prototype, "_radius", [serializable$j], function () {
        return 0.5;
      }), _initializer2$v = applyDecoratedInitializer(_class2$x.prototype, "_cylinderHeight", [serializable$j], function () {
        return 1;
      }), _initializer3$l = applyDecoratedInitializer(_class2$x.prototype, "_direction", [serializable$j], function () {
        return EAxisDirection.Y_AXIS;
      })), _class2$x)) || _class$z));

      var _dec$z, _dec2$x, _class$y, _class2$w, _initializer$v, _initializer2$u, _initializer3$k;
      var CylinderCollider = exports('eU', (_dec$z = ccclass$n('cc.CylinderCollider'), _dec2$x = type$7(EAxisDirection), _dec$z(_class$y = (_class2$w = function (_Collider) {
        _inheritsLoose(CylinderCollider, _Collider);
        function CylinderCollider() {
          var _this;
          _this = _Collider.call(this, EColliderType.CYLINDER) || this;
          _this._radius = _initializer$v && _initializer$v();
          _this._height = _initializer2$u && _initializer2$u();
          _this._direction = _initializer3$k && _initializer3$k();
          return _this;
        }
        _createClass(CylinderCollider, [{
          key: "radius",
          get: function get() {
            return this._radius;
          },
          set: function set(value) {
            if (this._radius === value) return;
            this._radius = Math.abs(value);
            if (this._shape) {
              this.shape.setRadius(value);
            }
          }
        }, {
          key: "height",
          get: function get() {
            return this._height;
          },
          set: function set(value) {
            if (this._height === value) return;
            this._height = Math.abs(value);
            if (this._shape) {
              this.shape.setHeight(value);
            }
          }
        }, {
          key: "direction",
          get: function get() {
            return this._direction;
          },
          set: function set(value) {
            if (this._direction === value) return;
            if (value < EAxisDirection.X_AXIS || value > EAxisDirection.Z_AXIS) return;
            this._direction = value;
            if (this._shape) {
              this.shape.setDirection(value);
            }
          }
        }, {
          key: "shape",
          get: function get() {
            return this._shape;
          }
        }]);
        return CylinderCollider;
      }(Collider), (_applyDecoratedDescriptor(_class2$w.prototype, "direction", [_dec2$x], Object.getOwnPropertyDescriptor(_class2$w.prototype, "direction"), _class2$w.prototype), _initializer$v = applyDecoratedInitializer(_class2$w.prototype, "_radius", [serializable$j], function () {
        return 0.5;
      }), _initializer2$u = applyDecoratedInitializer(_class2$w.prototype, "_height", [serializable$j], function () {
        return 2;
      }), _initializer3$k = applyDecoratedInitializer(_class2$w.prototype, "_direction", [serializable$j], function () {
        return EAxisDirection.Y_AXIS;
      })), _class2$w)) || _class$y));

      var _dec$y, _dec2$w, _class$x, _class2$v, _initializer$u, _initializer2$t, _initializer3$j;
      var ConeCollider = exports('eV', (_dec$y = ccclass$n('cc.ConeCollider'), _dec2$w = type$7(EAxisDirection), _dec$y(_class$x = (_class2$v = function (_Collider) {
        _inheritsLoose(ConeCollider, _Collider);
        function ConeCollider() {
          var _this;
          _this = _Collider.call(this, EColliderType.CONE) || this;
          _this._radius = _initializer$u && _initializer$u();
          _this._height = _initializer2$t && _initializer2$t();
          _this._direction = _initializer3$j && _initializer3$j();
          return _this;
        }
        _createClass(ConeCollider, [{
          key: "radius",
          get: function get() {
            return this._radius;
          },
          set: function set(value) {
            if (this._radius === value) return;
            this._radius = Math.abs(value);
            if (this._shape) {
              this.shape.setRadius(value);
            }
          }
        }, {
          key: "height",
          get: function get() {
            return this._height;
          },
          set: function set(value) {
            if (this._height === value) return;
            if (value < 0) value = 0;
            this._height = value;
            if (this._shape) {
              this.shape.setHeight(value);
            }
          }
        }, {
          key: "direction",
          get: function get() {
            return this._direction;
          },
          set: function set(value) {
            if (this._direction === value) return;
            if (value < EAxisDirection.X_AXIS || value > EAxisDirection.Z_AXIS) return;
            this._direction = value;
            if (this._shape) {
              this.shape.setDirection(value);
            }
          }
        }, {
          key: "shape",
          get: function get() {
            return this._shape;
          }
        }]);
        return ConeCollider;
      }(Collider), (_applyDecoratedDescriptor(_class2$v.prototype, "direction", [_dec2$w], Object.getOwnPropertyDescriptor(_class2$v.prototype, "direction"), _class2$v.prototype), _initializer$u = applyDecoratedInitializer(_class2$v.prototype, "_radius", [serializable$j], function () {
        return 0.5;
      }), _initializer2$t = applyDecoratedInitializer(_class2$v.prototype, "_height", [serializable$j], function () {
        return 1;
      }), _initializer3$j = applyDecoratedInitializer(_class2$v.prototype, "_direction", [serializable$j], function () {
        return EAxisDirection.Y_AXIS;
      })), _class2$v)) || _class$x));

      var _dec$x, _dec2$v, _class$w, _class2$u, _initializer$t, _initializer2$s;
      var MeshCollider = exports('eT', (_dec$x = ccclass$n('cc.MeshCollider'), _dec2$v = type$7(Mesh), _dec$x(_class$w = (_class2$u = function (_Collider) {
        _inheritsLoose(MeshCollider, _Collider);
        var _proto = MeshCollider.prototype;
        _proto.onEnable = function onEnable() {
          _Collider.prototype.onEnable.call(this);
          if (this.node) {
            var body = this.node.getComponent(RigidBody);
            if (body && body.isValid && body.type === ERigidBodyType.DYNAMIC && !this.convex) {
              warnID(9630, this.node.name);
            }
          }
        };
        function MeshCollider() {
          var _this;
          _this = _Collider.call(this, EColliderType.MESH) || this;
          _this._mesh = _initializer$t && _initializer$t();
          _this._convex = _initializer2$s && _initializer2$s();
          return _this;
        }
        _createClass(MeshCollider, [{
          key: "mesh",
          get: function get() {
            return this._mesh;
          },
          set: function set(value) {
            if (this._mesh === value) return;
            this._mesh = value;
            if (this._shape) this.shape.setMesh(this._mesh);
          }
        }, {
          key: "convex",
          get: function get() {
            return this._convex;
          },
          set: function set(value) {
            if (this._convex === value) return;
            this._convex = value;
            if (this._shape && this._mesh) this.shape.setMesh(this._mesh);
          }
        }, {
          key: "shape",
          get: function get() {
            return this._shape;
          }
        }]);
        return MeshCollider;
      }(Collider), (_applyDecoratedDescriptor(_class2$u.prototype, "mesh", [_dec2$v], Object.getOwnPropertyDescriptor(_class2$u.prototype, "mesh"), _class2$u.prototype), _initializer$t = applyDecoratedInitializer(_class2$u.prototype, "_mesh", [serializable$j], function () {
        return null;
      }), _initializer2$s = applyDecoratedInitializer(_class2$u.prototype, "_convex", [serializable$j], function () {
        return false;
      })), _class2$u)) || _class$w));

      var _dec$w, _dec2$u, _class$v, _class2$t, _initializer$s, _initializer2$r, _initializer3$i, _initializer4$g;
      var ConstantForce = exports('eL', (_dec$w = ccclass$n('cc.ConstantForce'), _dec2$u = requireComponent(RigidBody), _dec$w(_class$v = _dec2$u(_class$v = disallowMultiple$1(_class$v = (_class2$t = function (_Component) {
        _inheritsLoose(ConstantForce, _Component);
        function ConstantForce() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Component.call.apply(_Component, [this].concat(args)) || this;
          _this._rigidBody = null;
          _this._force = _initializer$s && _initializer$s();
          _this._localForce = _initializer2$r && _initializer2$r();
          _this._torque = _initializer3$i && _initializer3$i();
          _this._localTorque = _initializer4$g && _initializer4$g();
          _this._mask = 0;
          return _this;
        }
        var _proto = ConstantForce.prototype;
        _proto.onLoad = function onLoad() {
          this._rigidBody = this.node.getComponent(RigidBody);
          this._maskUpdate(this._force, 1);
          this._maskUpdate(this._localForce, 2);
          this._maskUpdate(this._torque, 4);
          this._maskUpdate(this._localTorque, 8);
        };
        _proto.lateUpdate = function lateUpdate(dt) {
          {
            if (this._rigidBody != null && this._mask !== 0) {
              if (this._mask & 1) this._rigidBody.applyForce(this._force);
              if (this._mask & 2) this._rigidBody.applyLocalForce(this.localForce);
              if (this._mask & 4) this._rigidBody.applyTorque(this._torque);
              if (this._mask & 8) this._rigidBody.applyLocalTorque(this._localTorque);
            }
          }
        };
        _proto._maskUpdate = function _maskUpdate(t, m) {
          if (t.strictEquals(Vec3.ZERO)) {
            this._mask &= ~m;
          } else {
            this._mask |= m;
          }
        };
        _createClass(ConstantForce, [{
          key: "force",
          get: function get() {
            return this._force;
          },
          set: function set(value) {
            Vec3.copy(this._force, value);
            this._maskUpdate(this._force, 1);
          }
        }, {
          key: "localForce",
          get: function get() {
            return this._localForce;
          },
          set: function set(value) {
            Vec3.copy(this._localForce, value);
            this._maskUpdate(this.localForce, 2);
          }
        }, {
          key: "torque",
          get: function get() {
            return this._torque;
          },
          set: function set(value) {
            Vec3.copy(this._torque, value);
            this._maskUpdate(this._torque, 4);
          }
        }, {
          key: "localTorque",
          get: function get() {
            return this._localTorque;
          },
          set: function set(value) {
            Vec3.copy(this._localTorque, value);
            this._maskUpdate(this._localTorque, 8);
          }
        }]);
        return ConstantForce;
      }(Component), (_initializer$s = applyDecoratedInitializer(_class2$t.prototype, "_force", [serializable$j], function () {
        return new Vec3();
      }), _initializer2$r = applyDecoratedInitializer(_class2$t.prototype, "_localForce", [serializable$j], function () {
        return new Vec3();
      }), _initializer3$i = applyDecoratedInitializer(_class2$t.prototype, "_torque", [serializable$j], function () {
        return new Vec3();
      }), _initializer4$g = applyDecoratedInitializer(_class2$t.prototype, "_localTorque", [serializable$j], function () {
        return new Vec3();
      })), _class2$t)) || _class$v) || _class$v) || _class$v));

      var _dec$v, _class2$s, _class3$e, _initializer$r, _initializer2$q, _initializer3$h, _initializer4$f, _initializer5$c, _initializer6$9, _dec2$t, _class5$4, _dec3$o, _class7$2, _class8$2, _initializer7$8;
      var TERRAIN_BLOCK_TILE_COMPLEXITY = 32;
      var TERRAIN_HEIGHT_BASE = 32768;
      var TERRAIN_HEIGHT_FACTORY = 1.0 / 128.0;
      var TERRAIN_HEIGHT_FACTORY_V7 = 1.0 / 512.0;
      var TERRAIN_DATA_VERSION = 0x01010001;
      var TERRAIN_DATA_VERSION2 = 0x01010002;
      var TERRAIN_DATA_VERSION3 = 0x01010003;
      var TERRAIN_DATA_VERSION4 = 0x01010004;
      var TERRAIN_DATA_VERSION5 = 0x01010005;
      var TERRAIN_DATA_VERSION6 = 0x01010006;
      var TERRAIN_DATA_VERSION7 = 0x01010007;
      var TERRAIN_DATA_VERSION8 = 0x01010008;
      var TERRAIN_DATA_VERSION_DEFAULT = 0x01010111;
      var TerrainBuffer = function () {
        function TerrainBuffer() {
          this.length = 0;
          this.buffer = new Uint8Array(2048);
          this._buffView = new DataView(this.buffer.buffer);
          this._seekPos = 0;
        }
        var _proto = TerrainBuffer.prototype;
        _proto.reserve = function reserve(size) {
          if (this.buffer.byteLength > size) {
            return;
          }
          var capacity = this.buffer.byteLength;
          while (capacity < size) {
            capacity += capacity;
          }
          var temp = new Uint8Array(capacity);
          for (var i = 0; i < this.length; ++i) {
            temp[i] = this.buffer[i];
          }
          this.buffer = temp;
          this._buffView = new DataView(this.buffer.buffer);
        };
        _proto.assign = function assign(buff) {
          this.buffer = buff;
          this.length = buff.length;
          this._seekPos = buff.byteOffset;
          this._buffView = new DataView(buff.buffer);
        };
        _proto.writeInt8 = function writeInt8(value) {
          this.reserve(this.length + 1);
          this._buffView.setInt8(this.length, value);
          this.length += 1;
        };
        _proto.writeInt16 = function writeInt16(value) {
          this.reserve(this.length + 2);
          this._buffView.setInt16(this.length, value, true);
          this.length += 2;
        };
        _proto.writeInt32 = function writeInt32(value) {
          this.reserve(this.length + 4);
          this._buffView.setInt32(this.length, value, true);
          this.length += 4;
        };
        _proto.writeIntArray = function writeIntArray(value) {
          this.reserve(this.length + 4 * value.length);
          for (var i = 0; i < value.length; ++i) {
            this._buffView.setInt32(this.length + i * 4, value[i], true);
          }
          this.length += 4 * value.length;
        };
        _proto.writeFloat = function writeFloat(value) {
          this.reserve(this.length + 4);
          this._buffView.setFloat32(this.length, value, true);
          this.length += 4;
        };
        _proto.writeFloatArray = function writeFloatArray(value) {
          this.reserve(this.length + 4 * value.length);
          for (var i = 0; i < value.length; ++i) {
            this._buffView.setFloat32(this.length + i * 4, value[i], true);
          }
          this.length += 4 * value.length;
        };
        _proto.writeDouble = function writeDouble(value) {
          this.reserve(this.length + 8);
          this._buffView.setFloat64(this.length, value, true);
          this.length += 8;
        };
        _proto.writeDoubleArray = function writeDoubleArray(value) {
          this.reserve(this.length + 8 * value.length);
          for (var i = 0; i < value.length; ++i) {
            this._buffView.setFloat64(this.length + i * 8, value[i], true);
          }
          this.length += 8 * value.length;
        };
        _proto.writeString = function writeString(value) {
          this.reserve(this.length + value.length + 4);
          this._buffView.setInt32(this.length, value.length, true);
          for (var i = 0; i < value.length; ++i) {
            this._buffView.setInt8(this.length + 4 + i, value.charCodeAt(i));
          }
          this.length += value.length + 4;
        };
        _proto.readInt8 = function readInt8() {
          var value = this._buffView.getInt8(this._seekPos);
          this._seekPos += 1;
          return value;
        };
        _proto.readInt16 = function readInt16() {
          var value = this._buffView.getInt16(this._seekPos, true);
          this._seekPos += 2;
          return value;
        };
        _proto.readInt = function readInt() {
          var value = this._buffView.getInt32(this._seekPos, true);
          this._seekPos += 4;
          return value;
        };
        _proto.readIntArray = function readIntArray(value) {
          for (var i = 0; i < value.length; ++i) {
            value[i] = this._buffView.getInt32(this._seekPos + i * 4, true);
          }
          this._seekPos += 4 * value.length;
          return value;
        };
        _proto.readFloat = function readFloat() {
          var value = this._buffView.getFloat32(this._seekPos, true);
          this._seekPos += 4;
          return value;
        };
        _proto.readFloatArray = function readFloatArray(value) {
          for (var i = 0; i < value.length; ++i) {
            value[i] = this._buffView.getFloat32(this._seekPos + i * 4, true);
          }
          this._seekPos += 4 * value.length;
          return value;
        };
        _proto.readDouble = function readDouble() {
          var value = this._buffView.getFloat64(this._seekPos, true);
          this._seekPos += 8;
          return value;
        };
        _proto.readDoubleArray = function readDoubleArray(value) {
          for (var i = 0; i < value.length; ++i) {
            value[i] = this._buffView.getFloat64(this._seekPos + i * 4, true);
          }
          this._seekPos += 8 * value.length;
          return value;
        };
        _proto.readString = function readString() {
          var length = this.readInt();
          var value = '';
          for (var i = 0; i < length; ++i) {
            value += String.fromCharCode(this.readInt8());
          }
          return value;
        };
        return TerrainBuffer;
      }();
      (_dec$v = ccclass$n('cc.TerrainLayerInfo'), _dec$v(_class2$s = (_class3$e = function TerrainLayerInfo() {
        this.slot = _initializer$r && _initializer$r();
        this.tileSize = _initializer2$q && _initializer2$q();
        this.detailMap = _initializer3$h && _initializer3$h();
        this.normalMap = _initializer4$f && _initializer4$f();
        this.roughness = _initializer5$c && _initializer5$c();
        this.metallic = _initializer6$9 && _initializer6$9();
      }, (_initializer$r = applyDecoratedInitializer(_class3$e.prototype, "slot", [serializable$j], function () {
        return 0;
      }), _initializer2$q = applyDecoratedInitializer(_class3$e.prototype, "tileSize", [serializable$j], function () {
        return 1;
      }), _initializer3$h = applyDecoratedInitializer(_class3$e.prototype, "detailMap", [serializable$j], function () {
        return null;
      }), _initializer4$f = applyDecoratedInitializer(_class3$e.prototype, "normalMap", [serializable$j], function () {
        return null;
      }), _initializer5$c = applyDecoratedInitializer(_class3$e.prototype, "roughness", [serializable$j], function () {
        return 1;
      }), _initializer6$9 = applyDecoratedInitializer(_class3$e.prototype, "metallic", [serializable$j], function () {
        return 0;
      })), _class3$e)) || _class2$s);
      var TerrainLayerBinaryInfo = (_dec2$t = ccclass$n('cc.TerrainLayerBinaryInfo'), _dec2$t(_class5$4 = function TerrainLayerBinaryInfo() {
        this.slot = 0;
        this.tileSize = 1;
        this.roughness = 1;
        this.metallic = 0;
        this.detailMapId = '';
        this.normalMapId = '';
      }) || _class5$4);
      var TerrainAsset = (_dec3$o = ccclass$n('cc.TerrainAsset'), _dec3$o(_class7$2 = (_class8$2 = function (_Asset) {
        _inheritsLoose(TerrainAsset, _Asset);
        function TerrainAsset() {
          var _this;
          _this = _Asset.call(this) || this;
          _this._version = 0;
          _this._data = null;
          _this._tileSize = 1;
          _this._blockCount = [1, 1];
          _this._weightMapSize = 128;
          _this._lightMapSize = 128;
          _this._heights = new Uint16Array();
          _this._normals = new Float32Array();
          _this._weights = new Uint8Array();
          _this._layerBuffer = [-1, -1, -1, -1];
          _this._layerBinaryInfos = [];
          _this._layerInfos = _initializer7$8 && _initializer7$8();
          return _this;
        }
        var _proto2 = TerrainAsset.prototype;
        _proto2.getLayer = function getLayer(xBlock, yBlock, layerId) {
          var blockId = yBlock * this.blockCount[0] + xBlock;
          var index = blockId * 4 + layerId;
          if (xBlock < this.blockCount[0] && yBlock < this.blockCount[1] && index < this._layerBuffer.length) {
            return this._layerBuffer[index];
          }
          return -1;
        };
        _proto2.getHeight = function getHeight(i, j) {
          var vertexCountX = this._blockCount[0] * TERRAIN_BLOCK_TILE_COMPLEXITY + 1;
          return (this._heights[j * vertexCountX + i] - TERRAIN_HEIGHT_BASE) * TERRAIN_HEIGHT_FACTORY;
        };
        _proto2.getVertexCountI = function getVertexCountI() {
          if (this._blockCount.length < 1) return 0;
          return this._blockCount[0] * TERRAIN_BLOCK_TILE_COMPLEXITY + 1;
        };
        _proto2.getVertexCountJ = function getVertexCountJ() {
          if (this._blockCount.length < 2) return 0;
          return this._blockCount[1] * TERRAIN_BLOCK_TILE_COMPLEXITY + 1;
        };
        _proto2._setNativeData = function _setNativeData(_nativeData) {
          this._data = _nativeData;
        };
        _proto2._loadNativeData = function _loadNativeData(_nativeData) {
          if (!_nativeData || _nativeData.length === 0) {
            return false;
          }
          var stream = new TerrainBuffer();
          stream.assign(_nativeData);
          this._version = stream.readInt();
          if (this._version === TERRAIN_DATA_VERSION_DEFAULT) {
            return true;
          }
          if (this._version !== TERRAIN_DATA_VERSION && this._version !== TERRAIN_DATA_VERSION2 && this._version !== TERRAIN_DATA_VERSION3 && this._version !== TERRAIN_DATA_VERSION4 && this._version !== TERRAIN_DATA_VERSION5 && this._version !== TERRAIN_DATA_VERSION6 && this._version !== TERRAIN_DATA_VERSION7 && this._version !== TERRAIN_DATA_VERSION8) {
            return false;
          }
          if (this._version >= TERRAIN_DATA_VERSION7) {
            this.tileSize = stream.readDouble();
          } else {
            this.tileSize = stream.readFloat();
          }
          this.tileSize = Math.floor(this.tileSize * 100) / 100.0;
          stream.readIntArray(this._blockCount);
          this.weightMapSize = stream.readInt16();
          this.lightMapSize = stream.readInt16();
          var heightBufferSize = stream.readInt();
          this.heights = new Uint16Array(heightBufferSize);
          for (var i = 0; i < this.heights.length; ++i) {
            this.heights[i] = stream.readInt16();
          }
          if (this._version < TERRAIN_DATA_VERSION8) {
            for (var _i = 0; _i < this.heights.length; ++_i) {
              var h = (this._heights[_i] - TERRAIN_HEIGHT_BASE) * TERRAIN_HEIGHT_FACTORY_V7;
              var ch = TERRAIN_HEIGHT_BASE + h / TERRAIN_HEIGHT_FACTORY;
              this.heights[_i] = ch;
            }
          }
          if (this._version >= TERRAIN_DATA_VERSION6) {
            var normalBufferSize = stream.readInt();
            this.normals = new Float32Array(normalBufferSize);
            for (var _i2 = 0; _i2 < this.normals.length; ++_i2) {
              this.normals[_i2] = stream.readFloat();
            }
          }
          var WeightBufferSize = stream.readInt();
          this.weights = new Uint8Array(WeightBufferSize);
          for (var _i3 = 0; _i3 < this.weights.length; ++_i3) {
            this.weights[_i3] = stream.readInt8();
          }
          if (this._version >= TERRAIN_DATA_VERSION2) {
            var layerBufferSize = stream.readInt();
            this.layerBuffer = new Array(layerBufferSize);
            for (var _i4 = 0; _i4 < this.layerBuffer.length; ++_i4) {
              this.layerBuffer[_i4] = stream.readInt16();
            }
          }
          if (this._version >= TERRAIN_DATA_VERSION3) {
            var layerInfoSize = stream.readInt();
            this._layerBinaryInfos = new Array(layerInfoSize);
            for (var _i5 = 0; _i5 < this._layerBinaryInfos.length; ++_i5) {
              this._layerBinaryInfos[_i5] = new TerrainLayerBinaryInfo();
              this._layerBinaryInfos[_i5].slot = stream.readInt();
              if (this._version >= TERRAIN_DATA_VERSION7) {
                this._layerBinaryInfos[_i5].tileSize = stream.readDouble();
              } else {
                this._layerBinaryInfos[_i5].tileSize = stream.readFloat();
              }
              this._layerBinaryInfos[_i5].detailMapId = stream.readString();
              if (this._version >= TERRAIN_DATA_VERSION4) {
                this._layerBinaryInfos[_i5].normalMapId = stream.readString();
                if (this._version >= TERRAIN_DATA_VERSION7) {
                  this._layerBinaryInfos[_i5].roughness = stream.readDouble();
                  this._layerBinaryInfos[_i5].metallic = stream.readDouble();
                } else {
                  this._layerBinaryInfos[_i5].roughness = stream.readFloat();
                  this._layerBinaryInfos[_i5].metallic = stream.readFloat();
                }
              }
            }
          }
          return true;
        };
        _proto2._exportNativeData = function _exportNativeData() {
          var stream = new TerrainBuffer();
          stream.writeInt32(TERRAIN_DATA_VERSION8);
          stream.writeDouble(this.tileSize);
          stream.writeIntArray(this._blockCount);
          stream.writeInt16(this.weightMapSize);
          stream.writeInt16(this.lightMapSize);
          stream.writeInt32(this.heights.length);
          for (var i = 0; i < this.heights.length; ++i) {
            stream.writeInt16(this.heights[i]);
          }
          stream.writeInt32(this.normals.length);
          for (var _i6 = 0; _i6 < this.normals.length; ++_i6) {
            stream.writeFloat(this.normals[_i6]);
          }
          stream.writeInt32(this.weights.length);
          for (var _i7 = 0; _i7 < this.weights.length; ++_i7) {
            stream.writeInt8(this.weights[_i7]);
          }
          stream.writeInt32(this.layerBuffer.length);
          for (var _i8 = 0; _i8 < this.layerBuffer.length; ++_i8) {
            stream.writeInt16(this.layerBuffer[_i8]);
          }
          var layerBinaryInfos = [];
          layerBinaryInfos.length = this.layerInfos.length;
          for (var _i9 = 0; _i9 < layerBinaryInfos.length; ++_i9) {
            var layer = this.layerInfos[_i9];
            var binaryLayer = new TerrainLayerBinaryInfo();
            binaryLayer.slot = _i9;
            binaryLayer.tileSize = layer.tileSize;
            binaryLayer.detailMapId = layer.detailMap ? layer.detailMap._uuid : '';
            binaryLayer.normalMapId = layer.normalMap ? layer.normalMap._uuid : '';
            binaryLayer.metallic = layer.metallic;
            binaryLayer.roughness = layer.roughness;
            layerBinaryInfos[_i9] = binaryLayer;
          }
          stream.writeInt32(layerBinaryInfos.length);
          for (var _i10 = 0; _i10 < layerBinaryInfos.length; ++_i10) {
            stream.writeInt32(layerBinaryInfos[_i10].slot);
            stream.writeDouble(layerBinaryInfos[_i10].tileSize);
            stream.writeString(layerBinaryInfos[_i10].detailMapId);
            stream.writeString(layerBinaryInfos[_i10].normalMapId);
            stream.writeDouble(layerBinaryInfos[_i10].roughness);
            stream.writeDouble(layerBinaryInfos[_i10].metallic);
          }
          return stream.buffer;
        };
        _proto2._exportDefaultNativeData = function _exportDefaultNativeData() {
          var stream = new TerrainBuffer();
          stream.writeInt32(TERRAIN_DATA_VERSION_DEFAULT);
          return stream.buffer;
        };
        _createClass(TerrainAsset, [{
          key: "_nativeAsset",
          get: function get() {
            return this._data.buffer;
          },
          set: function set(value) {
            if (this._data && this._data.byteLength === value.byteLength) {
              this._data.set(new Uint8Array(value));
            } else {
              this._data = new Uint8Array(value);
            }
            this._loadNativeData(this._data);
          }
        }, {
          key: "version",
          get: function get() {
            return this._version;
          }
        }, {
          key: "tileSize",
          get: function get() {
            return this._tileSize;
          },
          set: function set(value) {
            this._tileSize = value;
          }
        }, {
          key: "blockCount",
          get: function get() {
            return this._blockCount;
          },
          set: function set(value) {
            this._blockCount = value;
          }
        }, {
          key: "lightMapSize",
          get: function get() {
            return this._lightMapSize;
          },
          set: function set(value) {
            this._lightMapSize = value;
          }
        }, {
          key: "weightMapSize",
          get: function get() {
            return this._weightMapSize;
          },
          set: function set(value) {
            this._weightMapSize = value;
          }
        }, {
          key: "heights",
          get: function get() {
            return this._heights;
          },
          set: function set(value) {
            this._heights = value;
          }
        }, {
          key: "normals",
          get: function get() {
            return this._normals;
          },
          set: function set(value) {
            this._normals = value;
          }
        }, {
          key: "weights",
          get: function get() {
            return this._weights;
          },
          set: function set(value) {
            this._weights = value;
          }
        }, {
          key: "layerBuffer",
          get: function get() {
            return this._layerBuffer;
          },
          set: function set(value) {
            this._layerBuffer = value;
          }
        }, {
          key: "layerInfos",
          get: function get() {
            return this._layerInfos;
          },
          set: function set(value) {
            this._layerInfos = value;
          }
        }, {
          key: "layerBinaryInfos",
          get: function get() {
            return this._layerBinaryInfos;
          }
        }]);
        return TerrainAsset;
      }(Asset), (_initializer7$8 = applyDecoratedInitializer(_class8$2.prototype, "_layerInfos", [serializable$j], function () {
        return [];
      })), _class8$2)) || _class7$2);

      var _dec$u, _dec2$s, _class$u, _class2$r, _initializer$q;
      var TerrainCollider = exports('eW', (_dec$u = ccclass$n('cc.TerrainCollider'), _dec2$s = type$7(TerrainAsset), _dec$u(_class$u = (_class2$r = function (_Collider) {
        _inheritsLoose(TerrainCollider, _Collider);
        var _proto = TerrainCollider.prototype;
        _proto.onEnable = function onEnable() {
          _Collider.prototype.onEnable.call(this);
          if (this.node) {
            var body = this.node.getComponent(RigidBody);
            if (body && body.isValid && body.type === ERigidBodyType.DYNAMIC) {
              warnID(9630, this.node.name);
            }
          }
        };
        function TerrainCollider() {
          var _this;
          _this = _Collider.call(this, EColliderType.TERRAIN) || this;
          _this._terrain = _initializer$q && _initializer$q();
          return _this;
        }
        _createClass(TerrainCollider, [{
          key: "terrain",
          get: function get() {
            return this._terrain;
          },
          set: function set(value) {
            this._terrain = value;
            if (this._shape) this.shape.setTerrain(this._terrain);
          }
        }, {
          key: "shape",
          get: function get() {
            return this._shape;
          }
        }]);
        return TerrainCollider;
      }(Collider), (_applyDecoratedDescriptor(_class2$r.prototype, "terrain", [_dec2$s], Object.getOwnPropertyDescriptor(_class2$r.prototype, "terrain"), _class2$r.prototype), _initializer$q = applyDecoratedInitializer(_class2$r.prototype, "_terrain", [serializable$j], function () {
        return null;
      })), _class2$r)) || _class$u));

      var _dec$t, _dec2$r, _class$t, _class2$q, _initializer$p, _initializer2$p, _class3$d;
      var SimplexCollider = exports('eX', (_dec$t = ccclass$n('cc.SimplexCollider'), _dec2$r = type$7(ESimplexType), _dec$t(_class$t = (_class2$q = (_class3$d = function (_Collider) {
        _inheritsLoose(SimplexCollider, _Collider);
        function SimplexCollider() {
          var _this;
          _this = _Collider.call(this, EColliderType.SIMPLEX) || this;
          _this._shapeType = _initializer$p && _initializer$p();
          _this._vertices = _initializer2$p && _initializer2$p();
          return _this;
        }
        var _proto = SimplexCollider.prototype;
        _proto.updateVertices = function updateVertices() {
          if (this._shape) {
            this.shape.setVertices(this._vertices);
          }
        };
        _createClass(SimplexCollider, [{
          key: "shapeType",
          get: function get() {
            return this._shapeType;
          },
          set: function set(v) {
            this._shapeType = v;
            if (this._shape) {
              this.shape.setShapeType(v);
            }
          }
        }, {
          key: "vertex0",
          get: function get() {
            return this._vertices[0];
          },
          set: function set(v) {
            Vec3.copy(this._vertices[0], v);
            this.updateVertices();
          }
        }, {
          key: "vertex1",
          get: function get() {
            return this._vertices[1];
          },
          set: function set(v) {
            Vec3.copy(this._vertices[1], v);
            this.updateVertices();
          }
        }, {
          key: "vertex2",
          get: function get() {
            return this._vertices[2];
          },
          set: function set(v) {
            Vec3.copy(this._vertices[2], v);
            this.updateVertices();
          }
        }, {
          key: "vertex3",
          get: function get() {
            return this._vertices[3];
          },
          set: function set(v) {
            Vec3.copy(this._vertices[3], v);
            this.updateVertices();
          }
        }, {
          key: "shape",
          get: function get() {
            return this._shape;
          }
        }, {
          key: "vertices",
          get: function get() {
            return this._vertices;
          }
        }]);
        return SimplexCollider;
      }(Collider), _class3$d.ESimplexType = ESimplexType, _class3$d), (_applyDecoratedDescriptor(_class2$q.prototype, "shapeType", [_dec2$r], Object.getOwnPropertyDescriptor(_class2$q.prototype, "shapeType"), _class2$q.prototype), _initializer$p = applyDecoratedInitializer(_class2$q.prototype, "_shapeType", [serializable$j], function () {
        return ESimplexType.TETRAHEDRON;
      }), _initializer2$p = applyDecoratedInitializer(_class2$q.prototype, "_vertices", [serializable$j], function () {
        return [new Vec3(0, 0, 0), new Vec3(0, 0, 1), new Vec3(1, 0, 0), new Vec3(0, 1, 0)];
      })), _class2$q)) || _class$t));
      (function (_SimplexCollider) {})(SimplexCollider || (exports('eX', SimplexCollider = {})));

      var _dec$s, _dec2$q, _class$s, _class2$p, _initializer$o, _initializer2$o;
      var PlaneCollider = exports('eY', (_dec$s = ccclass$n('cc.PlaneCollider'), _dec2$q = type$7(Vec3), _dec$s(_class$s = (_class2$p = function (_Collider) {
        _inheritsLoose(PlaneCollider, _Collider);
        var _proto = PlaneCollider.prototype;
        _proto.onEnable = function onEnable() {
          _Collider.prototype.onEnable.call(this);
          if (this.node) {
            var body = this.node.getComponent(RigidBody);
            if (body && body.isValid && body.type === ERigidBodyType.DYNAMIC) {
              warnID(9630, this.node.name);
            }
          }
        };
        function PlaneCollider() {
          var _this;
          _this = _Collider.call(this, EColliderType.PLANE) || this;
          _this._normal = _initializer$o && _initializer$o();
          _this._constant = _initializer2$o && _initializer2$o();
          return _this;
        }
        _createClass(PlaneCollider, [{
          key: "normal",
          get: function get() {
            return this._normal;
          },
          set: function set(value) {
            if (Vec3.strictEquals(this._normal, value)) return;
            Vec3.copy(this._normal, value);
            if (this._shape) {
              this.shape.setNormal(this._normal);
            }
          }
        }, {
          key: "constant",
          get: function get() {
            return this._constant;
          },
          set: function set(v) {
            if (this._constant === v) return;
            this._constant = v;
            if (this._shape) {
              this.shape.setConstant(this._constant);
            }
          }
        }, {
          key: "shape",
          get: function get() {
            return this._shape;
          }
        }]);
        return PlaneCollider;
      }(Collider), (_applyDecoratedDescriptor(_class2$p.prototype, "normal", [_dec2$q], Object.getOwnPropertyDescriptor(_class2$p.prototype, "normal"), _class2$p.prototype), _initializer$o = applyDecoratedInitializer(_class2$p.prototype, "_normal", [serializable$j], function () {
        return new Vec3(0, 1, 0);
      }), _initializer2$o = applyDecoratedInitializer(_class2$p.prototype, "_constant", [serializable$j], function () {
        return 0;
      })), _class2$p)) || _class$s));

      var _dec$r, _dec2$p, _dec3$n, _dec4$j, _dec5$i, _class$r, _class2$o, _initializer$n, _initializer2$n, _class3$c;
      var Constraint$1 = exports('eZ', (_dec$r = ccclass$n('cc.Constraint'), _dec2$p = requireComponent(RigidBody), _dec3$n = type$7(RigidBody), _dec4$j = type$7(RigidBody), _dec5$i = type$7(RigidBody), _dec$r(_class$r = _dec2$p(_class$r = (_class2$o = (_class3$c = function (_Eventify) {
        _inheritsLoose(Constraint, _Eventify);
        function Constraint(type) {
          var _this;
          _this = _Eventify.call(this) || this;
          _this.TYPE = void 0;
          _this._enableCollision = _initializer$n && _initializer$n();
          _this._connectedBody = _initializer2$n && _initializer2$n();
          _this._constraint = null;
          _this.TYPE = type;
          return _this;
        }
        var _proto = Constraint.prototype;
        _proto.onLoad = function onLoad() {
          if (!selector.runInEditor) return;
          this._constraint = createConstraint(this.TYPE);
          this._constraint.initialize(this);
        };
        _proto.onEnable = function onEnable() {
          if (this._constraint) {
            this._constraint.onEnable();
          }
        };
        _proto.onDisable = function onDisable() {
          if (this._constraint) {
            this._constraint.onDisable();
          }
        };
        _proto.onDestroy = function onDestroy() {
          if (this._constraint) {
            this._constraint.onDestroy();
          }
        };
        _createClass(Constraint, [{
          key: "attachedBody",
          get: function get() {
            return this.getComponent(RigidBody);
          }
        }, {
          key: "connectedBody",
          get: function get() {
            return this._connectedBody;
          },
          set: function set(v) {
            this._connectedBody = v;
            {
              if (this._constraint) this._constraint.setConnectedBody(v);
            }
          }
        }, {
          key: "enableCollision",
          get: function get() {
            return this._enableCollision;
          },
          set: function set(v) {
            this._enableCollision = v;
            {
              if (this._constraint) this._constraint.setEnableCollision(v);
            }
          }
        }]);
        return Constraint;
      }(Eventify(Component)), _class3$c.Type = EConstraintType, _class3$c), (_applyDecoratedDescriptor(_class2$o.prototype, "attachedBody", [_dec3$n], Object.getOwnPropertyDescriptor(_class2$o.prototype, "attachedBody"), _class2$o.prototype), _applyDecoratedDescriptor(_class2$o.prototype, "connectedBody", [_dec4$j], Object.getOwnPropertyDescriptor(_class2$o.prototype, "connectedBody"), _class2$o.prototype), _initializer$n = applyDecoratedInitializer(_class2$o.prototype, "_enableCollision", [serializable$j], function () {
        return true;
      }), _initializer2$n = applyDecoratedInitializer(_class2$o.prototype, "_connectedBody", [_dec5$i], function () {
        return null;
      })), _class2$o)) || _class$r) || _class$r));
      (function (_Constraint) {})(Constraint$1 || (exports('eZ', Constraint$1 = {})));

      var _dec$q, _dec2$o, _dec3$m, _dec4$i, _dec5$h, _dec6$9, _dec7$7, _class$q, _class2$n, _initializer$m, _initializer2$m, _initializer3$g, _dec8$5, _dec9$5, _dec10$3, _dec11$2, _dec12$2, _dec13$2, _dec14$1, _class4$2, _class5$3, _initializer4$e, _initializer5$b, _initializer6$8, _dec15$1, _dec16$1, _dec17$1, _dec18$1, _dec19$1, _dec20$1, _dec21$1, _dec22$1, _dec23$1, _dec24$1, _dec25$1, _dec26$1, _dec27$1, _dec28$1, _dec29$1, _class7$1, _class8$1, _initializer7$7, _initializer8$7, _initializer9$7, _initializer10$7, _initializer11$7;
      var HingeLimitData = (_dec$q = ccclass$n('cc.HingeLimitData'), _dec2$o = formerlySerializedAs$4('enabled'), _dec3$m = formerlySerializedAs$4('upperLimit'), _dec4$i = formerlySerializedAs$4('lowerLimit'), _dec5$h = type$7(CCBoolean), _dec6$9 = type$7(CCFloat), _dec7$7 = type$7(CCFloat), _dec$q(_class$q = (_class2$n = function () {
        function HingeLimitData() {
          this._enabled = _initializer$m && _initializer$m();
          this._upperLimit = _initializer2$m && _initializer2$m();
          this._lowerLimit = _initializer3$g && _initializer3$g();
        }
        _createClass(HingeLimitData, [{
          key: "enabled",
          get: function get() {
            return this._enabled;
          },
          set: function set(v) {
            this._enabled = v;
          }
        }, {
          key: "upperLimit",
          get: function get() {
            return this._upperLimit;
          },
          set: function set(v) {
            this._upperLimit = v;
          }
        }, {
          key: "lowerLimit",
          get: function get() {
            return this._lowerLimit;
          },
          set: function set(v) {
            this._lowerLimit = v;
          }
        }]);
        return HingeLimitData;
      }(), (_initializer$m = applyDecoratedInitializer(_class2$n.prototype, "_enabled", [serializable$j, _dec2$o], function () {
        return false;
      }), _initializer2$m = applyDecoratedInitializer(_class2$n.prototype, "_upperLimit", [serializable$j, _dec3$m], function () {
        return Number.MAX_VALUE;
      }), _initializer3$g = applyDecoratedInitializer(_class2$n.prototype, "_lowerLimit", [serializable$j, _dec4$i], function () {
        return -Number.MAX_VALUE;
      }), _applyDecoratedDescriptor(_class2$n.prototype, "enabled", [_dec5$h], Object.getOwnPropertyDescriptor(_class2$n.prototype, "enabled"), _class2$n.prototype), _applyDecoratedDescriptor(_class2$n.prototype, "upperLimit", [_dec6$9], Object.getOwnPropertyDescriptor(_class2$n.prototype, "upperLimit"), _class2$n.prototype), _applyDecoratedDescriptor(_class2$n.prototype, "lowerLimit", [_dec7$7], Object.getOwnPropertyDescriptor(_class2$n.prototype, "lowerLimit"), _class2$n.prototype)), _class2$n)) || _class$q);
      var HingeMotorData = (_dec8$5 = ccclass$n('cc.HingeMotorData'), _dec9$5 = formerlySerializedAs$4('enabled'), _dec10$3 = formerlySerializedAs$4('motorVelocity'), _dec11$2 = formerlySerializedAs$4('motorForceLimit'), _dec12$2 = type$7(CCBoolean), _dec13$2 = type$7(CCFloat), _dec14$1 = type$7(CCFloat), _dec8$5(_class4$2 = (_class5$3 = function () {
        function HingeMotorData() {
          this._enabled = _initializer4$e && _initializer4$e();
          this._motorVelocity = _initializer5$b && _initializer5$b();
          this._motorForceLimit = _initializer6$8 && _initializer6$8();
        }
        _createClass(HingeMotorData, [{
          key: "enabled",
          get: function get() {
            return this._enabled;
          },
          set: function set(v) {
            this._enabled = v;
          }
        }, {
          key: "motorVelocity",
          get: function get() {
            return this._motorVelocity;
          },
          set: function set(v) {
            this._motorVelocity = v;
          }
        }, {
          key: "motorForceLimit",
          get: function get() {
            return this._motorForceLimit;
          },
          set: function set(v) {
            this._motorForceLimit = v;
          }
        }]);
        return HingeMotorData;
      }(), (_initializer4$e = applyDecoratedInitializer(_class5$3.prototype, "_enabled", [serializable$j, _dec9$5], function () {
        return false;
      }), _initializer5$b = applyDecoratedInitializer(_class5$3.prototype, "_motorVelocity", [serializable$j, _dec10$3], function () {
        return 0;
      }), _initializer6$8 = applyDecoratedInitializer(_class5$3.prototype, "_motorForceLimit", [serializable$j, _dec11$2], function () {
        return 0;
      }), _applyDecoratedDescriptor(_class5$3.prototype, "enabled", [_dec12$2], Object.getOwnPropertyDescriptor(_class5$3.prototype, "enabled"), _class5$3.prototype), _applyDecoratedDescriptor(_class5$3.prototype, "motorVelocity", [_dec13$2], Object.getOwnPropertyDescriptor(_class5$3.prototype, "motorVelocity"), _class5$3.prototype), _applyDecoratedDescriptor(_class5$3.prototype, "motorForceLimit", [_dec14$1], Object.getOwnPropertyDescriptor(_class5$3.prototype, "motorForceLimit"), _class5$3.prototype)), _class5$3)) || _class4$2);
      var HingeConstraint = exports('e_', (_dec15$1 = ccclass$n('cc.HingeConstraint'), _dec16$1 = type$7(Vec3), _dec17$1 = type$7(Vec3), _dec18$1 = type$7(Vec3), _dec19$1 = type$7(CCBoolean), _dec20$1 = type$7(CCFloat), _dec21$1 = type$7(CCFloat), _dec22$1 = type$7(CCBoolean), _dec23$1 = type$7(CCFloat), _dec24$1 = type$7(CCFloat), _dec25$1 = formerlySerializedAs$4('axisA'), _dec26$1 = formerlySerializedAs$4('pivotA'), _dec27$1 = formerlySerializedAs$4('pivotB'), _dec28$1 = formerlySerializedAs$4('limitData'), _dec29$1 = formerlySerializedAs$4('motorData'), _dec15$1(_class7$1 = (_class8$1 = function (_Constraint) {
        _inheritsLoose(HingeConstraint, _Constraint);
        function HingeConstraint() {
          var _this;
          _this = _Constraint.call(this, EConstraintType.HINGE) || this;
          _this._axis = _initializer7$7 && _initializer7$7();
          _this._pivotA = _initializer8$7 && _initializer8$7();
          _this._pivotB = _initializer9$7 && _initializer9$7();
          _this._limitData = _initializer10$7 && _initializer10$7();
          _this._motorData = _initializer11$7 && _initializer11$7();
          return _this;
        }
        _createClass(HingeConstraint, [{
          key: "pivotA",
          get: function get() {
            return this._pivotA;
          },
          set: function set(v) {
            Vec3.copy(this._pivotA, v);
            {
              this.constraint.setPivotA(this._pivotA);
            }
          }
        }, {
          key: "pivotB",
          get: function get() {
            return this._pivotB;
          },
          set: function set(v) {
            Vec3.copy(this._pivotB, v);
            {
              this.constraint.setPivotB(this._pivotB);
            }
          }
        }, {
          key: "axis",
          get: function get() {
            return this._axis;
          },
          set: function set(v) {
            Vec3.copy(this._axis, v);
            {
              this.constraint.setAxis(this._axis);
            }
          }
        }, {
          key: "limitEnabled",
          get: function get() {
            return this._limitData.enabled;
          },
          set: function set(v) {
            this._limitData.enabled = v;
            {
              this.constraint.setLimitEnabled(v);
            }
          }
        }, {
          key: "upperLimit",
          get: function get() {
            return this._limitData.upperLimit;
          },
          set: function set(v) {
            this._limitData.upperLimit = v;
            {
              this.constraint.setUpperLimit(v);
            }
          }
        }, {
          key: "lowerLimit",
          get: function get() {
            return this._limitData.lowerLimit;
          },
          set: function set(v) {
            this._limitData.lowerLimit = v;
            {
              this.constraint.setLowerLimit(v);
            }
          }
        }, {
          key: "motorEnabled",
          get: function get() {
            return this._motorData.enabled;
          },
          set: function set(v) {
            this._motorData.enabled = v;
            {
              this.constraint.setMotorEnabled(v);
            }
          }
        }, {
          key: "motorVelocity",
          get: function get() {
            return this._motorData.motorVelocity;
          },
          set: function set(v) {
            this._motorData.motorVelocity = v;
            {
              this.constraint.setMotorVelocity(v);
            }
          }
        }, {
          key: "motorForceLimit",
          get: function get() {
            return this._motorData.motorForceLimit;
          },
          set: function set(v) {
            this._motorData.motorForceLimit = v;
            {
              this.constraint.setMotorForceLimit(v);
            }
          }
        }, {
          key: "constraint",
          get: function get() {
            return this._constraint;
          }
        }]);
        return HingeConstraint;
      }(Constraint$1), (_applyDecoratedDescriptor(_class8$1.prototype, "pivotA", [_dec16$1], Object.getOwnPropertyDescriptor(_class8$1.prototype, "pivotA"), _class8$1.prototype), _applyDecoratedDescriptor(_class8$1.prototype, "pivotB", [_dec17$1], Object.getOwnPropertyDescriptor(_class8$1.prototype, "pivotB"), _class8$1.prototype), _applyDecoratedDescriptor(_class8$1.prototype, "axis", [_dec18$1], Object.getOwnPropertyDescriptor(_class8$1.prototype, "axis"), _class8$1.prototype), _applyDecoratedDescriptor(_class8$1.prototype, "limitEnabled", [_dec19$1], Object.getOwnPropertyDescriptor(_class8$1.prototype, "limitEnabled"), _class8$1.prototype), _applyDecoratedDescriptor(_class8$1.prototype, "upperLimit", [_dec20$1], Object.getOwnPropertyDescriptor(_class8$1.prototype, "upperLimit"), _class8$1.prototype), _applyDecoratedDescriptor(_class8$1.prototype, "lowerLimit", [_dec21$1], Object.getOwnPropertyDescriptor(_class8$1.prototype, "lowerLimit"), _class8$1.prototype), _applyDecoratedDescriptor(_class8$1.prototype, "motorEnabled", [_dec22$1], Object.getOwnPropertyDescriptor(_class8$1.prototype, "motorEnabled"), _class8$1.prototype), _applyDecoratedDescriptor(_class8$1.prototype, "motorVelocity", [_dec23$1], Object.getOwnPropertyDescriptor(_class8$1.prototype, "motorVelocity"), _class8$1.prototype), _applyDecoratedDescriptor(_class8$1.prototype, "motorForceLimit", [_dec24$1], Object.getOwnPropertyDescriptor(_class8$1.prototype, "motorForceLimit"), _class8$1.prototype), _initializer7$7 = applyDecoratedInitializer(_class8$1.prototype, "_axis", [serializable$j, _dec25$1], function () {
        return new Vec3();
      }), _initializer8$7 = applyDecoratedInitializer(_class8$1.prototype, "_pivotA", [serializable$j, _dec26$1], function () {
        return new Vec3();
      }), _initializer9$7 = applyDecoratedInitializer(_class8$1.prototype, "_pivotB", [serializable$j, _dec27$1], function () {
        return new Vec3();
      }), _initializer10$7 = applyDecoratedInitializer(_class8$1.prototype, "_limitData", [serializable$j, _dec28$1], function () {
        return new HingeLimitData();
      }), _initializer11$7 = applyDecoratedInitializer(_class8$1.prototype, "_motorData", [serializable$j, _dec29$1], function () {
        return new HingeMotorData();
      })), _class8$1)) || _class7$1));

      var _dec$p, _dec2$n, _dec3$l, _dec4$h, _dec5$g, _class$p, _class2$m, _initializer$l, _initializer2$l;
      var FixedConstraint = exports('f0', (_dec$p = ccclass$n('cc.FixedConstraint'), _dec2$n = type$7(CCFloat), _dec3$l = type$7(CCFloat), _dec4$h = formerlySerializedAs$4('breakForce'), _dec5$g = formerlySerializedAs$4('breakTorque'), _dec$p(_class$p = (_class2$m = function (_Constraint) {
        _inheritsLoose(FixedConstraint, _Constraint);
        function FixedConstraint() {
          var _this;
          _this = _Constraint.call(this, EConstraintType.FIXED) || this;
          _this._breakForce = _initializer$l && _initializer$l();
          _this._breakTorque = _initializer2$l && _initializer2$l();
          return _this;
        }
        _createClass(FixedConstraint, [{
          key: "breakForce",
          get: function get() {
            return this._breakForce;
          },
          set: function set(v) {
            this._breakForce = v;
            {
              this.constraint.setBreakForce(v);
            }
          }
        }, {
          key: "breakTorque",
          get: function get() {
            return this._breakTorque;
          },
          set: function set(v) {
            this._breakTorque = v;
            {
              this.constraint.setBreakTorque(v);
            }
          }
        }, {
          key: "constraint",
          get: function get() {
            return this._constraint;
          }
        }]);
        return FixedConstraint;
      }(Constraint$1), (_applyDecoratedDescriptor(_class2$m.prototype, "breakForce", [_dec2$n], Object.getOwnPropertyDescriptor(_class2$m.prototype, "breakForce"), _class2$m.prototype), _applyDecoratedDescriptor(_class2$m.prototype, "breakTorque", [_dec3$l], Object.getOwnPropertyDescriptor(_class2$m.prototype, "breakTorque"), _class2$m.prototype), _initializer$l = applyDecoratedInitializer(_class2$m.prototype, "_breakForce", [serializable$j, _dec4$h], function () {
        return 1e8;
      }), _initializer2$l = applyDecoratedInitializer(_class2$m.prototype, "_breakTorque", [serializable$j, _dec5$g], function () {
        return 1e8;
      })), _class2$m)) || _class$p));

      var _dec$o, _dec2$m, _dec3$k, _dec4$g, _dec5$f, _dec6$8, _dec7$6, _dec8$4, _dec9$4, _dec10$2, _class$o, _class2$l, _initializer$k, _initializer2$k, _initializer3$f, _initializer4$d, _initializer5$a, _initializer6$7, _initializer7$6, _initializer8$6, _initializer9$6, _dec11$1, _dec12$1, _dec13$1, _dec14, _dec15, _dec16, _dec17, _dec18, _dec19, _dec20, _dec21, _dec22, _dec23, _dec24, _dec25, _class4$1, _class5$2, _initializer10$6, _initializer11$6, _initializer12$5, _initializer13$4, _initializer14$3, _initializer15$2, _initializer16$2, _initializer17$1, _initializer18$1, _initializer19, _initializer20, _initializer21, _initializer22, _initializer23, _dec26, _dec27, _dec28, _dec29, _dec30, _dec31, _dec32, _class7, _class8, _initializer24, _initializer25, _initializer26, _initializer27, _initializer28, _initializer29, _dec33, _dec34, _dec35, _dec36, _dec37, _dec38, _dec39, _class10, _class11, _initializer30, _initializer31, _initializer32, _initializer33, _initializer34, _initializer35, _dec40, _dec41, _dec42, _dec43, _dec44, _dec45, _dec46, _dec47, _dec48, _dec49, _dec50, _dec51, _dec52, _dec53, _dec54, _dec55, _class13, _class14, _initializer36, _initializer37, _initializer38, _initializer39, _initializer40, _initializer41, _initializer42, _initializer43, _initializer44, _initializer45, _initializer46;
      var LinearLimitSettings = (_dec$o = ccclass$n('cc.LinearLimitSettings'), _dec2$m = type$7(EConstraintMode), _dec3$k = type$7(EConstraintMode), _dec4$g = type$7(EConstraintMode), _dec5$f = type$7(Vec3), _dec6$8 = type$7(Vec3), _dec7$6 = type$7(CCFloat), _dec8$4 = type$7(CCBoolean), _dec9$4 = type$7(CCFloat), _dec10$2 = type$7(CCFloat), _dec$o(_class$o = (_class2$l = function () {
        function LinearLimitSettings(configurableConstraint) {
          this._xMotion = _initializer$k && _initializer$k();
          this._yMotion = _initializer2$k && _initializer2$k();
          this._zMotion = _initializer3$f && _initializer3$f();
          this._upper = _initializer4$d && _initializer4$d();
          this._lower = _initializer5$a && _initializer5$a();
          this._enableSoftConstraint = _initializer6$7 && _initializer6$7();
          this._bounciness = _initializer7$6 && _initializer7$6();
          this._stiffness = _initializer8$6 && _initializer8$6();
          this._damping = _initializer9$6 && _initializer9$6();
          this._impl = void 0;
          this._impl = configurableConstraint;
        }
        _createClass(LinearLimitSettings, [{
          key: "xMotion",
          get: function get() {
            return this._xMotion;
          },
          set: function set(v) {
            this._xMotion = v;
            {
              this._impl.setConstraintMode(0, v);
            }
          }
        }, {
          key: "yMotion",
          get: function get() {
            return this._yMotion;
          },
          set: function set(v) {
            this._yMotion = v;
            {
              this._impl.setConstraintMode(1, v);
            }
          }
        }, {
          key: "zMotion",
          get: function get() {
            return this._zMotion;
          },
          set: function set(v) {
            this._zMotion = v;
            {
              this._impl.setConstraintMode(2, v);
            }
          }
        }, {
          key: "upper",
          get: function get() {
            return this._upper;
          },
          set: function set(v) {
            Vec3.copy(this._upper, v);
            {
              var lower = this.lower;
              this._impl.setLinearLimit(0, lower.x, v.x);
              this._impl.setLinearLimit(1, lower.y, v.y);
              this._impl.setLinearLimit(2, lower.z, v.z);
            }
          }
        }, {
          key: "lower",
          get: function get() {
            return this._lower;
          },
          set: function set(v) {
            Vec3.copy(this._lower, v);
            {
              var upper = this.upper;
              this._impl.setLinearLimit(0, v.x, upper.x);
              this._impl.setLinearLimit(1, v.y, upper.y);
              this._impl.setLinearLimit(2, v.z, upper.z);
            }
          }
        }, {
          key: "restitution",
          get: function get() {
            return this._bounciness;
          },
          set: function set(v) {
            this._bounciness = v;
            {
              this._impl.setLinearRestitution(v);
            }
          }
        }, {
          key: "enableSoftConstraint",
          get: function get() {
            return this._enableSoftConstraint;
          },
          set: function set(v) {
            this._enableSoftConstraint = v;
            {
              this._impl.setLinearSoftConstraint(v);
            }
          }
        }, {
          key: "stiffness",
          get: function get() {
            return this._stiffness;
          },
          set: function set(v) {
            this._stiffness = v;
            {
              this._impl.setLinearStiffness(v);
            }
          }
        }, {
          key: "damping",
          get: function get() {
            return this._damping;
          },
          set: function set(v) {
            this._damping = v;
            {
              this._impl.setLinearDamping(v);
            }
          }
        }, {
          key: "impl",
          set: function set(v) {
            this._impl = v;
          }
        }]);
        return LinearLimitSettings;
      }(), (_applyDecoratedDescriptor(_class2$l.prototype, "xMotion", [_dec2$m], Object.getOwnPropertyDescriptor(_class2$l.prototype, "xMotion"), _class2$l.prototype), _applyDecoratedDescriptor(_class2$l.prototype, "yMotion", [_dec3$k], Object.getOwnPropertyDescriptor(_class2$l.prototype, "yMotion"), _class2$l.prototype), _applyDecoratedDescriptor(_class2$l.prototype, "zMotion", [_dec4$g], Object.getOwnPropertyDescriptor(_class2$l.prototype, "zMotion"), _class2$l.prototype), _applyDecoratedDescriptor(_class2$l.prototype, "upper", [_dec5$f], Object.getOwnPropertyDescriptor(_class2$l.prototype, "upper"), _class2$l.prototype), _applyDecoratedDescriptor(_class2$l.prototype, "lower", [_dec6$8], Object.getOwnPropertyDescriptor(_class2$l.prototype, "lower"), _class2$l.prototype), _applyDecoratedDescriptor(_class2$l.prototype, "restitution", [_dec7$6], Object.getOwnPropertyDescriptor(_class2$l.prototype, "restitution"), _class2$l.prototype), _applyDecoratedDescriptor(_class2$l.prototype, "enableSoftConstraint", [_dec8$4], Object.getOwnPropertyDescriptor(_class2$l.prototype, "enableSoftConstraint"), _class2$l.prototype), _applyDecoratedDescriptor(_class2$l.prototype, "stiffness", [_dec9$4], Object.getOwnPropertyDescriptor(_class2$l.prototype, "stiffness"), _class2$l.prototype), _applyDecoratedDescriptor(_class2$l.prototype, "damping", [_dec10$2], Object.getOwnPropertyDescriptor(_class2$l.prototype, "damping"), _class2$l.prototype), _initializer$k = applyDecoratedInitializer(_class2$l.prototype, "_xMotion", [serializable$j], function () {
        return EConstraintMode.FREE;
      }), _initializer2$k = applyDecoratedInitializer(_class2$l.prototype, "_yMotion", [serializable$j], function () {
        return EConstraintMode.FREE;
      }), _initializer3$f = applyDecoratedInitializer(_class2$l.prototype, "_zMotion", [serializable$j], function () {
        return EConstraintMode.FREE;
      }), _initializer4$d = applyDecoratedInitializer(_class2$l.prototype, "_upper", [serializable$j], function () {
        return new Vec3();
      }), _initializer5$a = applyDecoratedInitializer(_class2$l.prototype, "_lower", [serializable$j], function () {
        return new Vec3();
      }), _initializer6$7 = applyDecoratedInitializer(_class2$l.prototype, "_enableSoftConstraint", [serializable$j], function () {
        return false;
      }), _initializer7$6 = applyDecoratedInitializer(_class2$l.prototype, "_bounciness", [serializable$j], function () {
        return 0;
      }), _initializer8$6 = applyDecoratedInitializer(_class2$l.prototype, "_stiffness", [serializable$j], function () {
        return 0;
      }), _initializer9$6 = applyDecoratedInitializer(_class2$l.prototype, "_damping", [serializable$j], function () {
        return 0;
      })), _class2$l)) || _class$o);
      var AngularLimitSettings = (_dec11$1 = ccclass$n('cc.AngularLimitSettings'), _dec12$1 = type$7(EConstraintMode), _dec13$1 = type$7(EConstraintMode), _dec14 = type$7(EConstraintMode), _dec15 = type$7(CCFloat), _dec16 = type$7(CCFloat), _dec17 = type$7(CCFloat), _dec18 = type$7(CCFloat), _dec19 = type$7(CCFloat), _dec20 = type$7(CCBoolean), _dec21 = type$7(CCFloat), _dec22 = type$7(CCFloat), _dec23 = type$7(CCBoolean), _dec24 = type$7(CCFloat), _dec25 = type$7(CCFloat), _dec11$1(_class4$1 = (_class5$2 = function () {
        function AngularLimitSettings(configurableConstraint) {
          this._swing1Motion = _initializer10$6 && _initializer10$6();
          this._swing2Motion = _initializer11$6 && _initializer11$6();
          this._twistMotion = _initializer12$5 && _initializer12$5();
          this._twistExtent = _initializer13$4 && _initializer13$4();
          this._swingExtent1 = _initializer14$3 && _initializer14$3();
          this._swingExtent2 = _initializer15$2 && _initializer15$2();
          this._enableSoftConstraintSwing = _initializer16$2 && _initializer16$2();
          this._swingBounciness = _initializer17$1 && _initializer17$1();
          this._swingStiffness = _initializer18$1 && _initializer18$1();
          this._swingDamping = _initializer19 && _initializer19();
          this._enableSoftConstraintTwist = _initializer20 && _initializer20();
          this._twistBounciness = _initializer21 && _initializer21();
          this._twistStiffness = _initializer22 && _initializer22();
          this._twistDamping = _initializer23 && _initializer23();
          this._impl = void 0;
          this._impl = configurableConstraint;
        }
        _createClass(AngularLimitSettings, [{
          key: "twistMotion",
          get: function get() {
            return this._twistMotion;
          },
          set: function set(v) {
            this._twistMotion = v;
            {
              this._impl.setConstraintMode(3, v);
            }
          }
        }, {
          key: "swingMotion1",
          get: function get() {
            return this._swing1Motion;
          },
          set: function set(v) {
            this._swing1Motion = v;
            {
              this._impl.setConstraintMode(4, v);
            }
          }
        }, {
          key: "swingMotion2",
          get: function get() {
            return this._swing2Motion;
          },
          set: function set(v) {
            this._swing2Motion = v;
            {
              this._impl.setConstraintMode(5, v);
            }
          }
        }, {
          key: "twistExtent",
          get: function get() {
            return this._twistExtent;
          },
          set: function set(v) {
            this._twistExtent = v;
            {
              this._impl.setAngularExtent(v, this.swingExtent1, this.swingExtent2);
            }
          }
        }, {
          key: "swingExtent1",
          get: function get() {
            return this._swingExtent1;
          },
          set: function set(v) {
            this._swingExtent1 = v;
            {
              this._impl.setAngularExtent(this.twistExtent, v, this.swingExtent2);
            }
          }
        }, {
          key: "swingExtent2",
          get: function get() {
            return this._swingExtent2;
          },
          set: function set(v) {
            this._swingExtent2 = v;
            {
              this._impl.setAngularExtent(this.twistExtent, this.swingExtent1, v);
            }
          }
        }, {
          key: "twistRestitution",
          get: function get() {
            return this._twistBounciness;
          },
          set: function set(v) {
            this._twistBounciness = v;
            {
              this._impl.setTwistRestitution(v);
            }
          }
        }, {
          key: "swingRestitution",
          get: function get() {
            return this._swingBounciness;
          },
          set: function set(v) {
            this._swingBounciness = v;
            {
              this._impl.setSwingRestitution(v);
            }
          }
        }, {
          key: "enableSoftConstraintTwist",
          get: function get() {
            return this._enableSoftConstraintTwist;
          },
          set: function set(v) {
            this._enableSoftConstraintTwist = v;
            {
              this._impl.setTwistSoftConstraint(v);
            }
          }
        }, {
          key: "twistStiffness",
          get: function get() {
            return this._twistStiffness;
          },
          set: function set(v) {
            this._twistStiffness = v;
            {
              this._impl.setTwistStiffness(v);
            }
          }
        }, {
          key: "twistDamping",
          get: function get() {
            return this._twistDamping;
          },
          set: function set(v) {
            this._twistDamping = v;
            {
              this._impl.setTwistDamping(v);
            }
          }
        }, {
          key: "enableSoftConstraintSwing",
          get: function get() {
            return this._enableSoftConstraintSwing;
          },
          set: function set(v) {
            this._enableSoftConstraintSwing = v;
            {
              this._impl.setSwingSoftConstraint(v);
            }
          }
        }, {
          key: "swingStiffness",
          get: function get() {
            return this._swingStiffness;
          },
          set: function set(v) {
            this._swingStiffness = v;
            {
              this._impl.setSwingStiffness(v);
            }
          }
        }, {
          key: "swingDamping",
          get: function get() {
            return this._swingDamping;
          },
          set: function set(v) {
            this._swingDamping = v;
            {
              this._impl.setSwingDamping(v);
            }
          }
        }, {
          key: "impl",
          set: function set(v) {
            this._impl = v;
          }
        }]);
        return AngularLimitSettings;
      }(), (_applyDecoratedDescriptor(_class5$2.prototype, "twistMotion", [_dec12$1], Object.getOwnPropertyDescriptor(_class5$2.prototype, "twistMotion"), _class5$2.prototype), _applyDecoratedDescriptor(_class5$2.prototype, "swingMotion1", [_dec13$1], Object.getOwnPropertyDescriptor(_class5$2.prototype, "swingMotion1"), _class5$2.prototype), _applyDecoratedDescriptor(_class5$2.prototype, "swingMotion2", [_dec14], Object.getOwnPropertyDescriptor(_class5$2.prototype, "swingMotion2"), _class5$2.prototype), _applyDecoratedDescriptor(_class5$2.prototype, "twistExtent", [_dec15], Object.getOwnPropertyDescriptor(_class5$2.prototype, "twistExtent"), _class5$2.prototype), _applyDecoratedDescriptor(_class5$2.prototype, "swingExtent1", [_dec16], Object.getOwnPropertyDescriptor(_class5$2.prototype, "swingExtent1"), _class5$2.prototype), _applyDecoratedDescriptor(_class5$2.prototype, "swingExtent2", [_dec17], Object.getOwnPropertyDescriptor(_class5$2.prototype, "swingExtent2"), _class5$2.prototype), _applyDecoratedDescriptor(_class5$2.prototype, "twistRestitution", [_dec18], Object.getOwnPropertyDescriptor(_class5$2.prototype, "twistRestitution"), _class5$2.prototype), _applyDecoratedDescriptor(_class5$2.prototype, "swingRestitution", [_dec19], Object.getOwnPropertyDescriptor(_class5$2.prototype, "swingRestitution"), _class5$2.prototype), _applyDecoratedDescriptor(_class5$2.prototype, "enableSoftConstraintTwist", [_dec20], Object.getOwnPropertyDescriptor(_class5$2.prototype, "enableSoftConstraintTwist"), _class5$2.prototype), _applyDecoratedDescriptor(_class5$2.prototype, "twistStiffness", [_dec21], Object.getOwnPropertyDescriptor(_class5$2.prototype, "twistStiffness"), _class5$2.prototype), _applyDecoratedDescriptor(_class5$2.prototype, "twistDamping", [_dec22], Object.getOwnPropertyDescriptor(_class5$2.prototype, "twistDamping"), _class5$2.prototype), _applyDecoratedDescriptor(_class5$2.prototype, "enableSoftConstraintSwing", [_dec23], Object.getOwnPropertyDescriptor(_class5$2.prototype, "enableSoftConstraintSwing"), _class5$2.prototype), _applyDecoratedDescriptor(_class5$2.prototype, "swingStiffness", [_dec24], Object.getOwnPropertyDescriptor(_class5$2.prototype, "swingStiffness"), _class5$2.prototype), _applyDecoratedDescriptor(_class5$2.prototype, "swingDamping", [_dec25], Object.getOwnPropertyDescriptor(_class5$2.prototype, "swingDamping"), _class5$2.prototype), _initializer10$6 = applyDecoratedInitializer(_class5$2.prototype, "_swing1Motion", [serializable$j], function () {
        return EConstraintMode.FREE;
      }), _initializer11$6 = applyDecoratedInitializer(_class5$2.prototype, "_swing2Motion", [serializable$j], function () {
        return EConstraintMode.FREE;
      }), _initializer12$5 = applyDecoratedInitializer(_class5$2.prototype, "_twistMotion", [serializable$j], function () {
        return EConstraintMode.FREE;
      }), _initializer13$4 = applyDecoratedInitializer(_class5$2.prototype, "_twistExtent", [serializable$j], function () {
        return 0;
      }), _initializer14$3 = applyDecoratedInitializer(_class5$2.prototype, "_swingExtent1", [serializable$j], function () {
        return 0;
      }), _initializer15$2 = applyDecoratedInitializer(_class5$2.prototype, "_swingExtent2", [serializable$j], function () {
        return 0;
      }), _initializer16$2 = applyDecoratedInitializer(_class5$2.prototype, "_enableSoftConstraintSwing", [serializable$j], function () {
        return false;
      }), _initializer17$1 = applyDecoratedInitializer(_class5$2.prototype, "_swingBounciness", [serializable$j], function () {
        return 0;
      }), _initializer18$1 = applyDecoratedInitializer(_class5$2.prototype, "_swingStiffness", [serializable$j], function () {
        return 0;
      }), _initializer19 = applyDecoratedInitializer(_class5$2.prototype, "_swingDamping", [serializable$j], function () {
        return 0;
      }), _initializer20 = applyDecoratedInitializer(_class5$2.prototype, "_enableSoftConstraintTwist", [serializable$j], function () {
        return false;
      }), _initializer21 = applyDecoratedInitializer(_class5$2.prototype, "_twistBounciness", [serializable$j], function () {
        return 0;
      }), _initializer22 = applyDecoratedInitializer(_class5$2.prototype, "_twistStiffness", [serializable$j], function () {
        return 0;
      }), _initializer23 = applyDecoratedInitializer(_class5$2.prototype, "_twistDamping", [serializable$j], function () {
        return 0;
      })), _class5$2)) || _class4$1);
      var LinearDriverSettings = (_dec26 = ccclass$n('cc.LinearDriverSettings'), _dec27 = type$7(EDriverMode), _dec28 = type$7(EDriverMode), _dec29 = type$7(EDriverMode), _dec30 = type$7(Vec3), _dec31 = type$7(Vec3), _dec32 = type$7(CCFloat), _dec26(_class7 = (_class8 = function () {
        function LinearDriverSettings(configurableConstraint) {
          this._target = _initializer24 && _initializer24();
          this._velocity = _initializer25 && _initializer25();
          this._xDrive = _initializer26 && _initializer26();
          this._yDrive = _initializer27 && _initializer27();
          this._zDrive = _initializer28 && _initializer28();
          this._strength = _initializer29 && _initializer29();
          this._impl = void 0;
          this._impl = configurableConstraint;
        }
        _createClass(LinearDriverSettings, [{
          key: "xDrive",
          get: function get() {
            return this._xDrive;
          },
          set: function set(v) {
            this._xDrive = v;
            {
              this._impl.setDriverMode(0, v);
            }
          }
        }, {
          key: "yDrive",
          get: function get() {
            return this._yDrive;
          },
          set: function set(v) {
            this._yDrive = v;
            {
              this._impl.setDriverMode(1, v);
            }
          }
        }, {
          key: "zDrive",
          get: function get() {
            return this._zDrive;
          },
          set: function set(v) {
            this._zDrive = v;
            {
              this._impl.setDriverMode(2, v);
            }
          }
        }, {
          key: "targetPosition",
          get: function get() {
            return this._target;
          },
          set: function set(v) {
            Vec3.copy(this._target, v);
            {
              this._impl.setLinearMotorTarget(v);
            }
          }
        }, {
          key: "targetVelocity",
          get: function get() {
            return this._velocity;
          },
          set: function set(v) {
            Vec3.copy(this._velocity, v);
            {
              this._impl.setLinearMotorVelocity(v);
            }
          }
        }, {
          key: "strength",
          get: function get() {
            return this._strength;
          },
          set: function set(v) {
            this._strength = v;
            {
              this._impl.setLinearMotorForceLimit(v);
            }
          }
        }, {
          key: "impl",
          set: function set(v) {
            this._impl = v;
          }
        }]);
        return LinearDriverSettings;
      }(), (_applyDecoratedDescriptor(_class8.prototype, "xDrive", [_dec27], Object.getOwnPropertyDescriptor(_class8.prototype, "xDrive"), _class8.prototype), _applyDecoratedDescriptor(_class8.prototype, "yDrive", [_dec28], Object.getOwnPropertyDescriptor(_class8.prototype, "yDrive"), _class8.prototype), _applyDecoratedDescriptor(_class8.prototype, "zDrive", [_dec29], Object.getOwnPropertyDescriptor(_class8.prototype, "zDrive"), _class8.prototype), _applyDecoratedDescriptor(_class8.prototype, "targetPosition", [_dec30], Object.getOwnPropertyDescriptor(_class8.prototype, "targetPosition"), _class8.prototype), _applyDecoratedDescriptor(_class8.prototype, "targetVelocity", [_dec31], Object.getOwnPropertyDescriptor(_class8.prototype, "targetVelocity"), _class8.prototype), _applyDecoratedDescriptor(_class8.prototype, "strength", [_dec32], Object.getOwnPropertyDescriptor(_class8.prototype, "strength"), _class8.prototype), _initializer24 = applyDecoratedInitializer(_class8.prototype, "_target", [serializable$j], function () {
        return new Vec3();
      }), _initializer25 = applyDecoratedInitializer(_class8.prototype, "_velocity", [serializable$j], function () {
        return new Vec3();
      }), _initializer26 = applyDecoratedInitializer(_class8.prototype, "_xDrive", [serializable$j], function () {
        return EDriverMode.DISABLED;
      }), _initializer27 = applyDecoratedInitializer(_class8.prototype, "_yDrive", [serializable$j], function () {
        return EDriverMode.DISABLED;
      }), _initializer28 = applyDecoratedInitializer(_class8.prototype, "_zDrive", [serializable$j], function () {
        return EDriverMode.DISABLED;
      }), _initializer29 = applyDecoratedInitializer(_class8.prototype, "_strength", [serializable$j], function () {
        return 0;
      })), _class8)) || _class7);
      var AngularDriverSettings = (_dec33 = ccclass$n('cc.AngularDriverSettings'), _dec34 = type$7(EDriverMode), _dec35 = type$7(EDriverMode), _dec36 = type$7(EDriverMode), _dec37 = type$7(Vec3), _dec38 = type$7(Vec3), _dec39 = type$7(CCFloat), _dec33(_class10 = (_class11 = function () {
        function AngularDriverSettings(configurableConstraint) {
          this._swingDrive1 = _initializer30 && _initializer30();
          this._swingDrive2 = _initializer31 && _initializer31();
          this._twistDrive = _initializer32 && _initializer32();
          this._targetOrientation = _initializer33 && _initializer33();
          this._targetVelocity = _initializer34 && _initializer34();
          this._strength = _initializer35 && _initializer35();
          this._impl = void 0;
          this._impl = configurableConstraint;
        }
        _createClass(AngularDriverSettings, [{
          key: "twistDrive",
          get: function get() {
            return this._twistDrive;
          },
          set: function set(v) {
            this._twistDrive = v;
            {
              this._impl.setDriverMode(3, v);
            }
          }
        }, {
          key: "swingDrive1",
          get: function get() {
            return this._swingDrive1;
          },
          set: function set(v) {
            this._swingDrive1 = v;
            {
              this._impl.setDriverMode(4, v);
            }
          }
        }, {
          key: "swingDrive2",
          get: function get() {
            return this._swingDrive2;
          },
          set: function set(v) {
            this._swingDrive2 = v;
            {
              this._impl.setDriverMode(5, v);
            }
          }
        }, {
          key: "targetOrientation",
          get: function get() {
            return this._targetOrientation;
          },
          set: function set(v) {
            Vec3.copy(this._targetOrientation, v);
            {
              this._impl.setAngularMotorTarget(v);
            }
          }
        }, {
          key: "targetVelocity",
          get: function get() {
            return this._targetVelocity;
          },
          set: function set(v) {
            Vec3.copy(this._targetVelocity, v);
            {
              this._impl.setAngularMotorVelocity(v);
            }
          }
        }, {
          key: "strength",
          get: function get() {
            return this._strength;
          },
          set: function set(v) {
            this._strength = v;
            {
              this._impl.setAngularMotorForceLimit(v);
            }
          }
        }, {
          key: "impl",
          set: function set(v) {
            this._impl = v;
          }
        }]);
        return AngularDriverSettings;
      }(), (_applyDecoratedDescriptor(_class11.prototype, "twistDrive", [_dec34], Object.getOwnPropertyDescriptor(_class11.prototype, "twistDrive"), _class11.prototype), _applyDecoratedDescriptor(_class11.prototype, "swingDrive1", [_dec35], Object.getOwnPropertyDescriptor(_class11.prototype, "swingDrive1"), _class11.prototype), _applyDecoratedDescriptor(_class11.prototype, "swingDrive2", [_dec36], Object.getOwnPropertyDescriptor(_class11.prototype, "swingDrive2"), _class11.prototype), _applyDecoratedDescriptor(_class11.prototype, "targetOrientation", [_dec37], Object.getOwnPropertyDescriptor(_class11.prototype, "targetOrientation"), _class11.prototype), _applyDecoratedDescriptor(_class11.prototype, "targetVelocity", [_dec38], Object.getOwnPropertyDescriptor(_class11.prototype, "targetVelocity"), _class11.prototype), _applyDecoratedDescriptor(_class11.prototype, "strength", [_dec39], Object.getOwnPropertyDescriptor(_class11.prototype, "strength"), _class11.prototype), _initializer30 = applyDecoratedInitializer(_class11.prototype, "_swingDrive1", [serializable$j], function () {
        return EDriverMode.DISABLED;
      }), _initializer31 = applyDecoratedInitializer(_class11.prototype, "_swingDrive2", [serializable$j], function () {
        return EDriverMode.DISABLED;
      }), _initializer32 = applyDecoratedInitializer(_class11.prototype, "_twistDrive", [serializable$j], function () {
        return EDriverMode.DISABLED;
      }), _initializer33 = applyDecoratedInitializer(_class11.prototype, "_targetOrientation", [serializable$j], function () {
        return new Vec3();
      }), _initializer34 = applyDecoratedInitializer(_class11.prototype, "_targetVelocity", [serializable$j], function () {
        return new Vec3();
      }), _initializer35 = applyDecoratedInitializer(_class11.prototype, "_strength", [serializable$j], function () {
        return 0;
      })), _class11)) || _class10);
      var ConfigurableConstraint = exports('e$', (_dec40 = ccclass$n('cc.ConfigurableConstraint'), _dec41 = type$7(Vec3), _dec42 = type$7(Vec3), _dec43 = type$7(Vec3), _dec44 = type$7(Vec3), _dec45 = type$7(CCBoolean), _dec46 = type$7(CCFloat), _dec47 = type$7(CCFloat), _dec48 = type$7(LinearLimitSettings), _dec49 = type$7(AngularLimitSettings), _dec50 = type$7(LinearDriverSettings), _dec51 = type$7(AngularDriverSettings), _dec52 = formerlySerializedAs$4('linearLimitSettings'), _dec53 = formerlySerializedAs$4('angularLimitSettings'), _dec54 = formerlySerializedAs$4('linearDriverSettings'), _dec55 = formerlySerializedAs$4('angularDriverSettings'), _dec40(_class13 = (_class14 = function (_Constraint) {
        _inheritsLoose(ConfigurableConstraint, _Constraint);
        function ConfigurableConstraint() {
          var _this;
          _this = _Constraint.call(this, EConstraintType.CONFIGURABLE) || this;
          _this._breakForce = _initializer36 && _initializer36();
          _this._breakTorque = _initializer37 && _initializer37();
          _this._linearLimitSettings = _initializer38 && _initializer38();
          _this._angularLimitSettings = _initializer39 && _initializer39();
          _this._linearDriverSettings = _initializer40 && _initializer40();
          _this._angularDriverSettings = _initializer41 && _initializer41();
          _this._pivotA = _initializer42 && _initializer42();
          _this._pivotB = _initializer43 && _initializer43();
          _this._autoPivotB = _initializer44 && _initializer44();
          _this._axis = _initializer45 && _initializer45();
          _this._secondaryAxis = _initializer46 && _initializer46();
          _this._linearLimitSettings = new LinearLimitSettings(_this.constraint);
          _this._angularLimitSettings = new AngularLimitSettings(_this.constraint);
          _this._linearDriverSettings = new LinearDriverSettings(_this.constraint);
          _this._angularDriverSettings = new AngularDriverSettings(_this.constraint);
          return _this;
        }
        var _proto = ConfigurableConstraint.prototype;
        _proto.onLoad = function onLoad() {
          _Constraint.prototype.onLoad.call(this);
          {
            this.linearLimitSettings.impl = this.constraint;
            this.angularLimitSettings.impl = this.constraint;
            this.linearDriverSettings.impl = this.constraint;
            this.angularDriverSettings.impl = this.constraint;
          }
        };
        _createClass(ConfigurableConstraint, [{
          key: "axis",
          get: function get() {
            return this._axis;
          },
          set: function set(v) {
            Vec3.copy(this._axis, v);
            {
              this.constraint.setAxis(this._axis);
            }
          }
        }, {
          key: "secondaryAxis",
          get: function get() {
            return this._secondaryAxis;
          },
          set: function set(v) {
            Vec3.copy(this._secondaryAxis, v);
            {
              this.constraint.setSecondaryAxis(this._secondaryAxis);
            }
          }
        }, {
          key: "pivotA",
          get: function get() {
            return this._pivotA;
          },
          set: function set(v) {
            Vec3.copy(this._pivotA, v);
            {
              this.constraint.setPivotA(this._pivotA);
            }
          }
        }, {
          key: "pivotB",
          get: function get() {
            return this._pivotB;
          },
          set: function set(v) {
            Vec3.copy(this._pivotB, v);
            {
              this.constraint.setPivotB(this._pivotB);
            }
          }
        }, {
          key: "autoPivotB",
          get: function get() {
            return this._autoPivotB;
          },
          set: function set(v) {
            this._autoPivotB = v;
            {
              this.constraint.setAutoPivotB(this._autoPivotB);
            }
          }
        }, {
          key: "breakForce",
          get: function get() {
            return this._breakForce;
          },
          set: function set(v) {
            this._breakForce = v;
            {
              this.constraint.setBreakForce(v);
            }
          }
        }, {
          key: "breakTorque",
          get: function get() {
            return this._breakTorque;
          },
          set: function set(v) {
            this._breakTorque = v;
            {
              this.constraint.setBreakTorque(v);
            }
          }
        }, {
          key: "linearLimitSettings",
          get: function get() {
            return this._linearLimitSettings;
          },
          set: function set(v) {
            this._linearLimitSettings = v;
            {
              var constraint = this.constraint;
              constraint.setConstraintMode(0, v.xMotion);
              constraint.setConstraintMode(1, v.yMotion);
              constraint.setConstraintMode(2, v.zMotion);
              var upper = v.upper;
              var lower = v.lower;
              constraint.setLinearLimit(0, lower.x, upper.x);
              constraint.setLinearLimit(1, lower.y, upper.y);
              constraint.setLinearLimit(2, lower.z, upper.z);
              constraint.setLinearSoftConstraint(v.enableSoftConstraint);
              constraint.setLinearDamping(v.damping);
              constraint.setLinearStiffness(v.stiffness);
              constraint.setLinearRestitution(v.restitution);
            }
          }
        }, {
          key: "angularLimitSettings",
          get: function get() {
            return this._angularLimitSettings;
          },
          set: function set(v) {
            this._angularLimitSettings = v;
            {
              var constraint = this.constraint;
              constraint.setConstraintMode(3, v.twistMotion);
              constraint.setConstraintMode(4, v.swingMotion1);
              constraint.setConstraintMode(5, v.swingMotion2);
              constraint.setAngularExtent(v.twistExtent, v.swingExtent1, v.swingExtent2);
              constraint.setTwistRestitution(v.twistRestitution);
              constraint.setSwingRestitution(v.swingRestitution);
              constraint.setTwistSoftConstraint(v.enableSoftConstraintTwist);
              constraint.setSwingSoftConstraint(v.enableSoftConstraintSwing);
              constraint.setTwistDamping(v.twistDamping);
              constraint.setSwingDamping(v.swingDamping);
              constraint.setTwistStiffness(v.twistStiffness);
              constraint.setSwingStiffness(v.swingStiffness);
            }
          }
        }, {
          key: "linearDriverSettings",
          get: function get() {
            return this._linearDriverSettings;
          },
          set: function set(v) {
            this._linearDriverSettings = v;
            {
              var constraint = this.constraint;
              constraint.setDriverMode(0, v.xDrive);
              constraint.setDriverMode(1, v.yDrive);
              constraint.setDriverMode(2, v.zDrive);
              constraint.setLinearMotorTarget(v.targetPosition);
              constraint.setLinearMotorVelocity(v.targetVelocity);
              constraint.setLinearMotorForceLimit(v.strength);
            }
          }
        }, {
          key: "angularDriverSettings",
          get: function get() {
            return this._angularDriverSettings;
          },
          set: function set(v) {
            this._angularDriverSettings = v;
            {
              var constraint = this.constraint;
              constraint.setDriverMode(3, v.twistDrive);
              constraint.setDriverMode(4, v.swingDrive1);
              constraint.setDriverMode(5, v.swingDrive2);
              constraint.setAngularMotorTarget(v.targetOrientation);
              constraint.setAngularMotorVelocity(v.targetVelocity);
              constraint.setAngularMotorForceLimit(v.strength);
            }
          }
        }, {
          key: "constraint",
          get: function get() {
            return this._constraint;
          }
        }]);
        return ConfigurableConstraint;
      }(Constraint$1), (_applyDecoratedDescriptor(_class14.prototype, "axis", [_dec41], Object.getOwnPropertyDescriptor(_class14.prototype, "axis"), _class14.prototype), _applyDecoratedDescriptor(_class14.prototype, "secondaryAxis", [_dec42], Object.getOwnPropertyDescriptor(_class14.prototype, "secondaryAxis"), _class14.prototype), _applyDecoratedDescriptor(_class14.prototype, "pivotA", [_dec43], Object.getOwnPropertyDescriptor(_class14.prototype, "pivotA"), _class14.prototype), _applyDecoratedDescriptor(_class14.prototype, "pivotB", [_dec44], Object.getOwnPropertyDescriptor(_class14.prototype, "pivotB"), _class14.prototype), _applyDecoratedDescriptor(_class14.prototype, "autoPivotB", [_dec45], Object.getOwnPropertyDescriptor(_class14.prototype, "autoPivotB"), _class14.prototype), _applyDecoratedDescriptor(_class14.prototype, "breakForce", [_dec46], Object.getOwnPropertyDescriptor(_class14.prototype, "breakForce"), _class14.prototype), _applyDecoratedDescriptor(_class14.prototype, "breakTorque", [_dec47], Object.getOwnPropertyDescriptor(_class14.prototype, "breakTorque"), _class14.prototype), _applyDecoratedDescriptor(_class14.prototype, "linearLimitSettings", [_dec48], Object.getOwnPropertyDescriptor(_class14.prototype, "linearLimitSettings"), _class14.prototype), _applyDecoratedDescriptor(_class14.prototype, "angularLimitSettings", [_dec49], Object.getOwnPropertyDescriptor(_class14.prototype, "angularLimitSettings"), _class14.prototype), _applyDecoratedDescriptor(_class14.prototype, "linearDriverSettings", [_dec50], Object.getOwnPropertyDescriptor(_class14.prototype, "linearDriverSettings"), _class14.prototype), _applyDecoratedDescriptor(_class14.prototype, "angularDriverSettings", [_dec51], Object.getOwnPropertyDescriptor(_class14.prototype, "angularDriverSettings"), _class14.prototype), _initializer36 = applyDecoratedInitializer(_class14.prototype, "_breakForce", [serializable$j], function () {
        return 1e8;
      }), _initializer37 = applyDecoratedInitializer(_class14.prototype, "_breakTorque", [serializable$j], function () {
        return 1e8;
      }), _initializer38 = applyDecoratedInitializer(_class14.prototype, "_linearLimitSettings", [serializable$j, _dec52], null), _initializer39 = applyDecoratedInitializer(_class14.prototype, "_angularLimitSettings", [serializable$j, _dec53], null), _initializer40 = applyDecoratedInitializer(_class14.prototype, "_linearDriverSettings", [serializable$j, _dec54], null), _initializer41 = applyDecoratedInitializer(_class14.prototype, "_angularDriverSettings", [serializable$j, _dec55], null), _initializer42 = applyDecoratedInitializer(_class14.prototype, "_pivotA", [serializable$j], function () {
        return new Vec3();
      }), _initializer43 = applyDecoratedInitializer(_class14.prototype, "_pivotB", [serializable$j], function () {
        return new Vec3();
      }), _initializer44 = applyDecoratedInitializer(_class14.prototype, "_autoPivotB", [serializable$j], function () {
        return false;
      }), _initializer45 = applyDecoratedInitializer(_class14.prototype, "_axis", [serializable$j], function () {
        return new Vec3(0, 1, 0);
      }), _initializer46 = applyDecoratedInitializer(_class14.prototype, "_secondaryAxis", [serializable$j], function () {
        return new Vec3(1, 0, 0);
      })), _class14)) || _class13));

      var _dec$n, _dec2$l, _dec3$j, _class$n, _class2$k, _initializer$j, _initializer2$j;
      var PointToPointConstraint = exports('f1', (_dec$n = ccclass$n('cc.PointToPointConstraint'), _dec2$l = type$7(Vec3), _dec3$j = type$7(Vec3), _dec$n(_class$n = (_class2$k = function (_Constraint) {
        _inheritsLoose(PointToPointConstraint, _Constraint);
        function PointToPointConstraint() {
          var _this;
          _this = _Constraint.call(this, EConstraintType.POINT_TO_POINT) || this;
          _this._pivotA = _initializer$j && _initializer$j();
          _this._pivotB = _initializer2$j && _initializer2$j();
          return _this;
        }
        _createClass(PointToPointConstraint, [{
          key: "pivotA",
          get: function get() {
            return this._pivotA;
          },
          set: function set(v) {
            Vec3.copy(this._pivotA, v);
            {
              this.constraint.setPivotA(this._pivotA);
            }
          }
        }, {
          key: "pivotB",
          get: function get() {
            return this._pivotB;
          },
          set: function set(v) {
            Vec3.copy(this._pivotB, v);
            {
              this.constraint.setPivotB(this._pivotB);
            }
          }
        }, {
          key: "constraint",
          get: function get() {
            return this._constraint;
          }
        }]);
        return PointToPointConstraint;
      }(Constraint$1), (_applyDecoratedDescriptor(_class2$k.prototype, "pivotA", [_dec2$l], Object.getOwnPropertyDescriptor(_class2$k.prototype, "pivotA"), _class2$k.prototype), _applyDecoratedDescriptor(_class2$k.prototype, "pivotB", [_dec3$j], Object.getOwnPropertyDescriptor(_class2$k.prototype, "pivotB"), _class2$k.prototype), _initializer$j = applyDecoratedInitializer(_class2$k.prototype, "_pivotA", [serializable$j], function () {
        return new Vec3();
      }), _initializer2$j = applyDecoratedInitializer(_class2$k.prototype, "_pivotB", [serializable$j], function () {
        return new Vec3();
      })), _class2$k)) || _class$n));

      var _dec$m, _dec2$k, _dec3$i, _dec4$f, _dec5$e, _dec6$7, _dec7$5, _class$m, _class2$j, _initializer$i, _initializer2$i, _initializer3$e, _initializer4$c, _initializer5$9, _initializer6$6;
      new Vec3(0, 0, 0);
      new Vec3(0, 0, 0);
      var CharacterController = exports('eK', (_dec$m = ccclass$n('cc.CharacterController'), _dec2$k = type$7(PhysicsSystem.PhysicsGroup), _dec3$i = type$7(CCFloat), _dec4$f = type$7(CCFloat), _dec5$e = type$7(CCFloat), _dec6$7 = type$7(CCFloat), _dec7$5 = type$7(Vec3), _dec$m(_class$m = disallowMultiple$1(_class$m = (_class2$j = function (_Eventify) {
        _inheritsLoose(CharacterController, _Eventify);
        function CharacterController(type) {
          var _this;
          _this = _Eventify.call(this) || this;
          _this.type = void 0;
          _this._cct = null;
          _this._group = _initializer$i && _initializer$i();
          _this._minMoveDistance = _initializer2$i && _initializer2$i();
          _this._stepOffset = _initializer3$e && _initializer3$e();
          _this._slopeLimit = _initializer4$c && _initializer4$c();
          _this._skinWidth = _initializer5$9 && _initializer5$9();
          _this._center = _initializer6$6 && _initializer6$6();
          _this._initialized = false;
          _this._prevPos = new Vec3();
          _this._currentPos = new Vec3();
          _this._velocity = new Vec3();
          _this._centerWorldPosition = new Vec3();
          _this._needCollisionEvent = false;
          _this._needTriggerEvent = false;
          _this.type = type;
          return _this;
        }
        var _proto = CharacterController.prototype;
        _proto.onLoad = function onLoad() {
          if (!selector.runInEditor) return;
          this._cct = createCharacterController(this.type);
          this._initialized = this._cct.initialize(this);
          this._cct.onLoad();
        };
        _proto.onEnable = function onEnable() {
          if (this._cct) {
            this._cct.onEnable();
          }
        };
        _proto.onDisable = function onDisable() {
          if (this._cct) {
            this._cct.onDisable();
          }
        };
        _proto.onDestroy = function onDestroy() {
          if (this._cct) {
            this._needCollisionEvent = false;
            this._needTriggerEvent = false;
            this._cct.updateEventListener();
            this._cct.onDestroy();
            this._cct = null;
          }
        };
        _proto.move = function move(movement) {
          if (!this._isInitialized) {
            return;
          }
          this._prevPos.set(this.centerWorldPosition);
          var elapsedTime = PhysicsSystem.instance.fixedTimeStep;
          this._cct.move(movement, this._minMoveDistance, elapsedTime);
          this._currentPos.set(this.centerWorldPosition);
          this._velocity = this._currentPos.subtract(this._prevPos).multiplyScalar(1.0 / elapsedTime);
          this._cct.syncPhysicsToScene();
        };
        _proto.on = function on(type, callback, target, once) {
          var ret = _Eventify.prototype.on.call(this, type, callback, target, once);
          this._updateNeedEvent(type);
          return ret;
        };
        _proto.off = function off(type, callback, target) {
          _Eventify.prototype.off.call(this, type, callback, target);
          this._updateNeedEvent();
        };
        _proto.once = function once(type, callback, target) {
          var ret = _Eventify.prototype.once.call(this, type, callback, target);
          this._updateNeedEvent(type);
          return ret;
        };
        _proto.getGroup = function getGroup() {
          if (this._isInitialized) return this._cct.getGroup();
          return 0;
        };
        _proto.setGroup = function setGroup(v) {
          if (this._isInitialized) this._cct.setGroup(v);
        };
        _proto.addGroup = function addGroup(v) {
          if (this._isInitialized) this._cct.addGroup(v);
        };
        _proto.removeGroup = function removeGroup(v) {
          if (this._isInitialized) this._cct.removeGroup(v);
        };
        _proto.getMask = function getMask() {
          if (this._isInitialized) return this._cct.getMask();
          return 0;
        };
        _proto.setMask = function setMask(v) {
          if (this._isInitialized) this._cct.setMask(v);
        };
        _proto.addMask = function addMask(v) {
          if (this._isInitialized) this._cct.addMask(v);
        };
        _proto.removeMask = function removeMask(v) {
          if (this._isInitialized) this._cct.removeMask(v);
        };
        _proto._updateNeedEvent = function _updateNeedEvent(type) {
          if (this.isValid) {
            if (type !== undefined) {
              if (type === 'onControllerColliderHit') {
                this._needCollisionEvent = true;
              }
              if (type === 'onControllerTriggerEnter' || type === 'onControllerTriggerStay' || type === 'onControllerTriggerExit') {
                this._needTriggerEvent = true;
              }
            } else {
              if (!this.hasEventListener('onControllerColliderHit')) {
                this._needCollisionEvent = false;
              }
              if (!(this.hasEventListener('onControllerTriggerEnter') || this.hasEventListener('onControllerTriggerStay') || this.hasEventListener('onControllerTriggerExit'))) {
                this._needTriggerEvent = false;
              }
            }
            if (this._cct) this._cct.updateEventListener();
          }
        };
        _createClass(CharacterController, [{
          key: "group",
          get: function get() {
            return this._group;
          },
          set: function set(v) {
            if (!Number.isInteger(Math.log2(v >>> 0))) {
              warn('[Physics]: The group should only have one bit.');
            }
            this._group = v;
            if (this._cct) {
              if (this._cct.getGroup() !== v) this._cct.setGroup(v);
            }
          }
        }, {
          key: "minMoveDistance",
          get: function get() {
            return this._minMoveDistance;
          },
          set: function set(value) {
            if (this._minMoveDistance === value) return;
            this._minMoveDistance = Math.abs(value);
          }
        }, {
          key: "stepOffset",
          get: function get() {
            return this._stepOffset;
          },
          set: function set(value) {
            if (this._stepOffset === value) return;
            this._stepOffset = Math.abs(value);
            if (this._cct) {
              this._cct.setStepOffset(value);
            }
          }
        }, {
          key: "slopeLimit",
          get: function get() {
            return this._slopeLimit;
          },
          set: function set(value) {
            if (this._slopeLimit === value) return;
            this._slopeLimit = Math.abs(value);
            if (this._cct) {
              this._cct.setSlopeLimit(value);
            }
          }
        }, {
          key: "skinWidth",
          get: function get() {
            return this._skinWidth;
          },
          set: function set(value) {
            if (this._skinWidth === value) return;
            this._skinWidth = Math.abs(value);
            if (this._cct) {
              this._cct.setContactOffset(Math.max(0.0001, value));
            }
          }
        }, {
          key: "center",
          get: function get() {
            return this._center;
          },
          set: function set(value) {
            if (Vec3.equals(this._center, value)) return;
            Vec3.copy(this._center, value);
          }
        }, {
          key: "_isInitialized",
          get: function get() {
            if (this._cct === null || !this._initialized) {
              return false;
            } else {
              return true;
            }
          }
        }, {
          key: "centerWorldPosition",
          get: function get() {
            if (this._isInitialized) this._cct.getPosition(this._centerWorldPosition);
            return this._centerWorldPosition;
          },
          set: function set(value) {
            if (this._isInitialized) this._cct.setPosition(value);
          }
        }, {
          key: "velocity",
          get: function get() {
            return this._velocity;
          }
        }, {
          key: "isGrounded",
          get: function get() {
            return this._cct.onGround();
          }
        }, {
          key: "needCollisionEvent",
          get: function get() {
            return this._needCollisionEvent;
          }
        }, {
          key: "needTriggerEvent",
          get: function get() {
            return this._needTriggerEvent;
          }
        }]);
        return CharacterController;
      }(Eventify(Component)), (_applyDecoratedDescriptor(_class2$j.prototype, "group", [_dec2$k], Object.getOwnPropertyDescriptor(_class2$j.prototype, "group"), _class2$j.prototype), _applyDecoratedDescriptor(_class2$j.prototype, "minMoveDistance", [_dec3$i], Object.getOwnPropertyDescriptor(_class2$j.prototype, "minMoveDistance"), _class2$j.prototype), _applyDecoratedDescriptor(_class2$j.prototype, "stepOffset", [_dec4$f], Object.getOwnPropertyDescriptor(_class2$j.prototype, "stepOffset"), _class2$j.prototype), _applyDecoratedDescriptor(_class2$j.prototype, "slopeLimit", [_dec5$e], Object.getOwnPropertyDescriptor(_class2$j.prototype, "slopeLimit"), _class2$j.prototype), _applyDecoratedDescriptor(_class2$j.prototype, "skinWidth", [_dec6$7], Object.getOwnPropertyDescriptor(_class2$j.prototype, "skinWidth"), _class2$j.prototype), _applyDecoratedDescriptor(_class2$j.prototype, "center", [_dec7$5], Object.getOwnPropertyDescriptor(_class2$j.prototype, "center"), _class2$j.prototype), _initializer$i = applyDecoratedInitializer(_class2$j.prototype, "_group", [serializable$j], function () {
        return PhysicsSystem.PhysicsGroup.DEFAULT;
      }), _initializer2$i = applyDecoratedInitializer(_class2$j.prototype, "_minMoveDistance", [serializable$j], function () {
        return 0.001;
      }), _initializer3$e = applyDecoratedInitializer(_class2$j.prototype, "_stepOffset", [serializable$j], function () {
        return 0.5;
      }), _initializer4$c = applyDecoratedInitializer(_class2$j.prototype, "_slopeLimit", [serializable$j], function () {
        return 45.0;
      }), _initializer5$9 = applyDecoratedInitializer(_class2$j.prototype, "_skinWidth", [serializable$j], function () {
        return 0.01;
      }), _initializer6$6 = applyDecoratedInitializer(_class2$j.prototype, "_center", [serializable$j], function () {
        return new Vec3();
      })), _class2$j)) || _class$m) || _class$m));

      var _dec$l, _dec2$j, _dec3$h, _dec4$e, _dec5$d, _class$l, _class2$i, _initializer$h, _initializer2$h, _initializer3$d;
      new Vec3(0, 0, 0);
      var BoxCharacterController = exports('f3', (_dec$l = ccclass$n('cc.BoxCharacterController'), _dec2$j = executionOrder$1(-1), _dec3$h = type$7(CCFloat), _dec4$e = type$7(CCFloat), _dec5$d = type$7(CCFloat), _dec$l(_class$l = _dec2$j(_class$l = (_class2$i = function (_CharacterController) {
        _inheritsLoose(BoxCharacterController, _CharacterController);
        function BoxCharacterController() {
          var _this;
          _this = _CharacterController.call(this, ECharacterControllerType.BOX) || this;
          _this._halfHeight = _initializer$h && _initializer$h();
          _this._halfSideExtent = _initializer2$h && _initializer2$h();
          _this._halfForwardExtent = _initializer3$d && _initializer3$d();
          return _this;
        }
        _createClass(BoxCharacterController, [{
          key: "halfHeight",
          get: function get() {
            return this._halfHeight;
          },
          set: function set(value) {
            if (this._halfHeight === value) return;
            this._halfHeight = Math.abs(value);
            if (this._cct) {
              this._cct.setHalfHeight(value);
            }
          }
        }, {
          key: "halfSideExtent",
          get: function get() {
            return this._halfSideExtent;
          },
          set: function set(value) {
            if (this._halfSideExtent === value) return;
            this._halfSideExtent = Math.abs(value);
            if (this._cct) {
              this._cct.setHalfSideExtent(value);
            }
          }
        }, {
          key: "halfForwardExtent",
          get: function get() {
            return this._halfForwardExtent;
          },
          set: function set(value) {
            if (this._halfForwardExtent === value) return;
            this._halfForwardExtent = Math.abs(value);
            if (this._cct) {
              this._cct.setHalfForwardExtent(value);
            }
          }
        }]);
        return BoxCharacterController;
      }(CharacterController), (_applyDecoratedDescriptor(_class2$i.prototype, "halfHeight", [_dec3$h], Object.getOwnPropertyDescriptor(_class2$i.prototype, "halfHeight"), _class2$i.prototype), _applyDecoratedDescriptor(_class2$i.prototype, "halfSideExtent", [_dec4$e], Object.getOwnPropertyDescriptor(_class2$i.prototype, "halfSideExtent"), _class2$i.prototype), _applyDecoratedDescriptor(_class2$i.prototype, "halfForwardExtent", [_dec5$d], Object.getOwnPropertyDescriptor(_class2$i.prototype, "halfForwardExtent"), _class2$i.prototype), _initializer$h = applyDecoratedInitializer(_class2$i.prototype, "_halfHeight", [serializable$j], function () {
        return 0.5;
      }), _initializer2$h = applyDecoratedInitializer(_class2$i.prototype, "_halfSideExtent", [serializable$j], function () {
        return 0.5;
      }), _initializer3$d = applyDecoratedInitializer(_class2$i.prototype, "_halfForwardExtent", [serializable$j], function () {
        return 0.5;
      })), _class2$i)) || _class$l) || _class$l));

      var _dec$k, _dec2$i, _dec3$g, _dec4$d, _class$k, _class2$h, _initializer$g, _initializer2$g;
      new Vec3(0, 0, 0);
      var CapsuleCharacterController = exports('f2', (_dec$k = ccclass$n('cc.CapsuleCharacterController'), _dec2$i = executionOrder$1(-1), _dec3$g = type$7(CCFloat), _dec4$d = type$7(CCFloat), _dec$k(_class$k = _dec2$i(_class$k = (_class2$h = function (_CharacterController) {
        _inheritsLoose(CapsuleCharacterController, _CharacterController);
        function CapsuleCharacterController() {
          var _this;
          _this = _CharacterController.call(this, ECharacterControllerType.CAPSULE) || this;
          _this._radius = _initializer$g && _initializer$g();
          _this._height = _initializer2$g && _initializer2$g();
          return _this;
        }
        _createClass(CapsuleCharacterController, [{
          key: "radius",
          get: function get() {
            return this._radius;
          },
          set: function set(value) {
            if (this._radius === value) return;
            this._radius = Math.abs(value);
            if (this._cct) {
              this._cct.setRadius(value);
            }
          }
        }, {
          key: "height",
          get: function get() {
            return this._height;
          },
          set: function set(value) {
            if (this._height === value) return;
            this._height = Math.abs(value);
            if (this._cct) {
              this._cct.setHeight(value);
            }
          }
        }]);
        return CapsuleCharacterController;
      }(CharacterController), (_applyDecoratedDescriptor(_class2$h.prototype, "radius", [_dec3$g], Object.getOwnPropertyDescriptor(_class2$h.prototype, "radius"), _class2$h.prototype), _applyDecoratedDescriptor(_class2$h.prototype, "height", [_dec4$d], Object.getOwnPropertyDescriptor(_class2$h.prototype, "height"), _class2$h.prototype), _initializer$g = applyDecoratedInitializer(_class2$h.prototype, "_radius", [serializable$j], function () {
        return 0.5;
      }), _initializer2$g = applyDecoratedInitializer(_class2$h.prototype, "_height", [serializable$j], function () {
        return 1.0;
      })), _class2$h)) || _class$k) || _class$k));

      var CharacterControllerContact = function CharacterControllerContact() {
        this.worldPosition = new Vec3();
        this.worldNormal = new Vec3();
        this.motionDirection = new Vec3();
        this.motionLength = 0;
      };

      legacyCC.PhysicsSystem = PhysicsSystem;
      legacyCC.PhysicsMaterial = PhysicsMaterial;
      legacyCC.PhysicsRayResult = PhysicsRayResult;
      legacyCC.ConstantForce = ConstantForce;

      var physics = /*#__PURE__*/Object.freeze({
        __proto__: null,
        PhysicsSystem: PhysicsSystem,
        PhysicsRayResult: PhysicsRayResult,
        PhysicsLineStripCastResult: PhysicsLineStripCastResult,
        get Collider () { return Collider; },
        BoxCollider: BoxCollider,
        SphereCollider: SphereCollider,
        CapsuleCollider: CapsuleCollider,
        MeshCollider: MeshCollider,
        CylinderCollider: CylinderCollider,
        ConeCollider: ConeCollider,
        TerrainCollider: TerrainCollider,
        get SimplexCollider () { return SimplexCollider; },
        PlaneCollider: PlaneCollider,
        get Constraint () { return Constraint$1; },
        HingeConstraint: HingeConstraint,
        FixedConstraint: FixedConstraint,
        PointToPointConstraint: PointToPointConstraint,
        ConfigurableConstraint: ConfigurableConstraint,
        get RigidBody () { return RigidBody; },
        PhysicsMaterial: PhysicsMaterial,
        ConstantForce: ConstantForce,
        CharacterController: CharacterController,
        BoxCharacterController: BoxCharacterController,
        CapsuleCharacterController: CapsuleCharacterController,
        selector: selector,
        utils: util,
        CharacterControllerContact: CharacterControllerContact,
        get ERigidBodyType () { return ERigidBodyType; },
        get EAxisDirection () { return EAxisDirection; },
        get ED6Axis () { return ED6Axis; },
        get ESimplexType () { return ESimplexType; },
        get EColliderType () { return EColliderType; },
        get EConstraintType () { return EConstraintType; },
        get EConstraintMode () { return EConstraintMode; },
        get EDriverMode () { return EDriverMode; },
        get ECharacterControllerType () { return ECharacterControllerType; },
        get PhysicsGroup () { return PhysicsGroup; }
      });
      exports('eH', physics);

      var v3_cannon0$1 = new cannon.Vec3();
      var v3_cannon1 = new cannon.Vec3();
      var CannonRigidBody = function () {
        function CannonRigidBody() {
          this._rigidBody = void 0;
          this._sharedBody = void 0;
          this._isEnabled = false;
        }
        var _proto = CannonRigidBody.prototype;
        _proto.setAllowSleep = function setAllowSleep(v) {
          if (this.impl.type !== cannon.Body.DYNAMIC) return;
          this.impl.allowSleep = v;
          this._wakeUpIfSleep();
        };
        _proto.setMass = function setMass(value) {
          if (this.impl.type !== cannon.Body.DYNAMIC) return;
          this.impl.mass = value;
          this.impl.updateMassProperties();
          this._wakeUpIfSleep();
        };
        _proto.setType = function setType(v) {
          switch (v) {
            case ERigidBodyType.DYNAMIC:
              this.impl.type = cannon.Body.DYNAMIC;
              this.impl.allowSleep = this._rigidBody.allowSleep;
              this.setMass(this._rigidBody.mass);
              break;
            case ERigidBodyType.KINEMATIC:
              this.impl.type = cannon.Body.KINEMATIC;
              this.impl.mass = 0;
              this.impl.allowSleep = false;
              this.impl.sleepState = cannon.Body.AWAKE;
              this.impl.updateMassProperties();
              break;
            case ERigidBodyType.STATIC:
            default:
              this.impl.type = cannon.Body.STATIC;
              this.impl.mass = 0;
              this.impl.allowSleep = true;
              this.impl.updateMassProperties();
              this.clearState();
              break;
          }
        };
        _proto.setLinearDamping = function setLinearDamping(value) {
          this.impl.linearDamping = value;
        };
        _proto.setAngularDamping = function setAngularDamping(value) {
          this.impl.angularDamping = value;
        };
        _proto.useGravity = function useGravity(value) {
          this.impl.useGravity = value;
          this._wakeUpIfSleep();
        };
        _proto.useCCD = function useCCD(value) {
          this.impl.ccdSpeedThreshold = value ? 0.01 : -1;
        };
        _proto.isUsingCCD = function isUsingCCD() {
          return this.impl.ccdSpeedThreshold !== -1;
        };
        _proto.setLinearFactor = function setLinearFactor(value) {
          Vec3.copy(this.impl.linearFactor, value);
          this._wakeUpIfSleep();
        };
        _proto.setAngularFactor = function setAngularFactor(value) {
          Vec3.copy(this.impl.angularFactor, value);
          var fixR = Vec3.equals(this.impl.angularFactor, Vec3.ZERO);
          if (fixR !== this.impl.fixedRotation) {
            this.impl.fixedRotation = fixR;
            this.impl.updateMassProperties();
          }
          this._wakeUpIfSleep();
        };
        _proto.initialize = function initialize(com) {
          this._rigidBody = com;
          this._sharedBody = PhysicsSystem.instance.physicsWorld.getSharedBody(this._rigidBody.node, this);
          this._sharedBody.reference = true;
          this._sharedBody.wrappedBody = this;
        };
        _proto.onLoad = function onLoad() {};
        _proto.onEnable = function onEnable() {
          this._isEnabled = true;
          this.setType(this._rigidBody.type);
          this.setMass(this._rigidBody.mass);
          this.setAllowSleep(this._rigidBody.allowSleep);
          this.setLinearDamping(this._rigidBody.linearDamping);
          this.setAngularDamping(this._rigidBody.angularDamping);
          this.useGravity(this._rigidBody.useGravity);
          this.setLinearFactor(this._rigidBody.linearFactor);
          this.setAngularFactor(this._rigidBody.angularFactor);
          this._sharedBody.enabled = true;
        };
        _proto.onDisable = function onDisable() {
          this._isEnabled = false;
          this._sharedBody.enabled = false;
        };
        _proto.onDestroy = function onDestroy() {
          this._sharedBody.reference = false;
          this._rigidBody = null;
          this._sharedBody = null;
        };
        _proto.clearVelocity = function clearVelocity() {
          this.impl.velocity.setZero();
          this.impl.angularVelocity.setZero();
        };
        _proto.clearForces = function clearForces() {
          this.impl.force.setZero();
          this.impl.torque.setZero();
        };
        _proto.clearState = function clearState() {
          this.clearVelocity();
          this.clearForces();
        };
        _proto.wakeUp = function wakeUp() {
          return this.impl.wakeUp();
        };
        _proto.sleep = function sleep() {
          return this.impl.sleep();
        };
        _proto.setSleepThreshold = function setSleepThreshold(v) {
          this.impl.sleepSpeedLimit = v;
          this._wakeUpIfSleep();
        };
        _proto.getSleepThreshold = function getSleepThreshold() {
          return this.impl.sleepSpeedLimit;
        };
        _proto.getLinearVelocity = function getLinearVelocity(out) {
          Vec3.copy(out, this.impl.velocity);
          return out;
        };
        _proto.setLinearVelocity = function setLinearVelocity(value) {
          this._wakeUpIfSleep();
          Vec3.copy(this.impl.velocity, value);
        };
        _proto.getAngularVelocity = function getAngularVelocity(out) {
          Vec3.copy(out, this.impl.angularVelocity);
          return out;
        };
        _proto.setAngularVelocity = function setAngularVelocity(value) {
          this._wakeUpIfSleep();
          Vec3.copy(this.impl.angularVelocity, value);
        };
        _proto.applyForce = function applyForce(force, worldPoint) {
          this._sharedBody.syncSceneToPhysics();
          this._wakeUpIfSleep();
          if (worldPoint == null) worldPoint = Vec3.ZERO;
          this.impl.applyForce(Vec3.copy(v3_cannon0$1, force), Vec3.copy(v3_cannon1, worldPoint));
        };
        _proto.applyImpulse = function applyImpulse(impulse, worldPoint) {
          this._sharedBody.syncSceneToPhysics();
          this._wakeUpIfSleep();
          if (worldPoint == null) worldPoint = Vec3.ZERO;
          this.impl.applyImpulse(Vec3.copy(v3_cannon0$1, impulse), Vec3.copy(v3_cannon1, worldPoint));
        };
        _proto.applyLocalForce = function applyLocalForce(force, localPoint) {
          this._sharedBody.syncSceneToPhysics();
          this._wakeUpIfSleep();
          if (localPoint == null) localPoint = Vec3.ZERO;
          this.impl.applyLocalForce(Vec3.copy(v3_cannon0$1, force), Vec3.copy(v3_cannon1, localPoint));
        };
        _proto.applyLocalImpulse = function applyLocalImpulse(impulse, localPoint) {
          this._sharedBody.syncSceneToPhysics();
          this._wakeUpIfSleep();
          if (localPoint == null) localPoint = Vec3.ZERO;
          this.impl.applyLocalImpulse(Vec3.copy(v3_cannon0$1, impulse), Vec3.copy(v3_cannon1, localPoint));
        };
        _proto.applyTorque = function applyTorque(torque) {
          this._sharedBody.syncSceneToPhysics();
          this._wakeUpIfSleep();
          Vec3.add(this.impl.torque, this.impl.torque, torque);
        };
        _proto.applyLocalTorque = function applyLocalTorque(torque) {
          this._sharedBody.syncSceneToPhysics();
          this._wakeUpIfSleep();
          Vec3.copy(v3_cannon0$1, torque);
          this.impl.vectorToWorldFrame(v3_cannon0$1, v3_cannon0$1);
          Vec3.add(this.impl.torque, this.impl.torque, v3_cannon0$1);
        };
        _proto.getGroup = function getGroup() {
          return this.impl.collisionFilterGroup;
        };
        _proto.setGroup = function setGroup(v) {
          this.impl.collisionFilterGroup = v;
          this._wakeUpIfSleep();
        };
        _proto.addGroup = function addGroup(v) {
          this.impl.collisionFilterGroup |= v;
          this._wakeUpIfSleep();
        };
        _proto.removeGroup = function removeGroup(v) {
          this.impl.collisionFilterGroup &= ~v;
          this._wakeUpIfSleep();
        };
        _proto.getMask = function getMask() {
          return this.impl.collisionFilterMask;
        };
        _proto.setMask = function setMask(v) {
          this.impl.collisionFilterMask = v;
          this._wakeUpIfSleep();
        };
        _proto.addMask = function addMask(v) {
          this.impl.collisionFilterMask |= v;
          this._wakeUpIfSleep();
        };
        _proto.removeMask = function removeMask(v) {
          this.impl.collisionFilterMask &= ~v;
          this._wakeUpIfSleep();
        };
        _proto._wakeUpIfSleep = function _wakeUpIfSleep() {
          if (!this.impl.isAwake()) this.impl.wakeUp();
        };
        _createClass(CannonRigidBody, [{
          key: "isAwake",
          get: function get() {
            return this.impl.isAwake();
          }
        }, {
          key: "isSleepy",
          get: function get() {
            return this.impl.isSleepy();
          }
        }, {
          key: "isSleeping",
          get: function get() {
            return this.impl.isSleeping();
          }
        }, {
          key: "impl",
          get: function get() {
            return this._sharedBody.body;
          }
        }, {
          key: "rigidBody",
          get: function get() {
            return this._rigidBody;
          }
        }, {
          key: "sharedBody",
          get: function get() {
            return this._sharedBody;
          }
        }, {
          key: "isEnabled",
          get: function get() {
            return this._isEnabled;
          }
        }]);
        return CannonRigidBody;
      }();

      function toCannonRaycastOptions(out, options) {
        out.checkCollisionResponse = !options.queryTrigger;
        out.collisionFilterGroup = -1;
        out.collisionFilterMask = options.mask;
      }
      function fillRaycastResult(result, cannonResult) {
        result._assign(cannonResult.hitPointWorld, cannonResult.distance, getWrap(cannonResult.shape).collider, cannonResult.hitNormalWorld);
      }
      function commitShapeUpdates(body) {
        body.aabbNeedsUpdate = true;
        body.updateMassProperties();
        body.updateBoundingRadius();
      }

      var TriggerEventObject = {
        type: 'onTriggerEnter',
        selfCollider: null,
        otherCollider: null,
        impl: null
      };
      var cannonQuat_0 = new cannon.Quaternion();
      var cannonVec3_0 = new cannon.Vec3();
      var cannonVec3_1 = new cannon.Vec3();
      var CannonShape = function () {
        function CannonShape() {
          this._collider = void 0;
          this._shape = void 0;
          this._offset = new cannon.Vec3();
          this._orient = new cannon.Quaternion();
          this._index = -1;
          this._sharedBody = void 0;
          this.onTriggerListener = this._onTrigger.bind(this);
          this._isBinding = false;
        }
        var _proto = CannonShape.prototype;
        _proto.updateEventListener = function updateEventListener() {};
        _proto.setMaterial = function setMaterial(mat) {
          var mat1 = mat == null ? PhysicsSystem.instance.defaultMaterial : mat;
          if (CannonShape.idToMaterial[mat1.id] == null) {
            CannonShape.idToMaterial[mat1.id] = new cannon.Material(mat1.id);
          }
          this._shape.material = CannonShape.idToMaterial[mat1.id];
          var smat = this._shape.material;
          smat.friction = mat1.friction;
          smat.restitution = mat1.restitution;
          var coef = cannon.CC_CONFIG.correctInelastic;
          smat.correctInelastic = smat.restitution === 0 ? coef : 0;
        };
        _proto.setAsTrigger = function setAsTrigger(v) {
          this._shape.collisionResponse = !v;
          if (this._index >= 0) {
            this._body.updateHasTrigger();
          }
        };
        _proto.setCenter = function setCenter(v) {
          this._setCenter(v);
          if (this._index >= 0) {
            commitShapeUpdates(this._body);
          }
        };
        _proto.setAttachedBody = function setAttachedBody(v) {
          if (v) {
            if (this._sharedBody) {
              if (this._sharedBody.wrappedBody === v.body) return;
              this._sharedBody.reference = false;
            }
            this._sharedBody = PhysicsSystem.instance.physicsWorld.getSharedBody(v.node);
            this._sharedBody.reference = true;
          } else {
            if (this._sharedBody) {
              this._sharedBody.reference = false;
            }
            this._sharedBody = PhysicsSystem.instance.physicsWorld.getSharedBody(this._collider.node);
            this._sharedBody.reference = true;
          }
        };
        _proto.getAABB = function getAABB(v) {
          Quat.copy(cannonQuat_0, this._collider.node.worldRotation);
          this._shape.calculateWorldAABB(cannon.Vec3.ZERO, cannonQuat_0, cannonVec3_0, cannonVec3_1);
          Vec3.subtract(v.halfExtents, cannonVec3_1, cannonVec3_0);
          Vec3.multiplyScalar(v.halfExtents, v.halfExtents, 0.5);
          Vec3.add(v.center, this._collider.node.worldPosition, this._collider.center);
        };
        _proto.getBoundingSphere = function getBoundingSphere(v) {
          v.radius = this._shape.boundingSphereRadius;
          Vec3.add(v.center, this._collider.node.worldPosition, this._collider.center);
        };
        _proto.initialize = function initialize(comp) {
          this._collider = comp;
          this._isBinding = true;
          this._sharedBody = PhysicsSystem.instance.physicsWorld.getSharedBody(this._collider.node);
          this._sharedBody.reference = true;
          this.onComponentSet();
          setWrap(this._shape, this);
          this._shape.addEventListener('cc-trigger', this.onTriggerListener);
        };
        _proto.onComponentSet = function onComponentSet() {};
        _proto.onLoad = function onLoad() {
          this.setMaterial(this._collider.sharedMaterial);
          this.setCenter(this._collider.center);
          this.setAsTrigger(this._collider.isTrigger);
        };
        _proto.onEnable = function onEnable() {
          this._sharedBody.addShape(this);
          this._sharedBody.enabled = true;
        };
        _proto.onDisable = function onDisable() {
          this._sharedBody.removeShape(this);
          this._sharedBody.enabled = false;
        };
        _proto.onDestroy = function onDestroy() {
          this._sharedBody.reference = false;
          this._shape.removeEventListener('cc-trigger', this.onTriggerListener);
          delete cannon.World.idToShapeMap[this._shape.id];
          this._sharedBody = null;
          setWrap(this._shape, null);
          this._offset = null;
          this._orient = null;
          this._shape = null;
          this._collider = null;
          this.onTriggerListener = null;
        };
        _proto.getGroup = function getGroup() {
          return this._body.collisionFilterGroup;
        };
        _proto.setGroup = function setGroup(v) {
          this._body.collisionFilterGroup = v;
          if (!this._body.isAwake()) this._body.wakeUp();
        };
        _proto.addGroup = function addGroup(v) {
          this._body.collisionFilterGroup |= v;
          if (!this._body.isAwake()) this._body.wakeUp();
        };
        _proto.removeGroup = function removeGroup(v) {
          this._body.collisionFilterGroup &= ~v;
          if (!this._body.isAwake()) this._body.wakeUp();
        };
        _proto.getMask = function getMask() {
          return this._body.collisionFilterMask;
        };
        _proto.setMask = function setMask(v) {
          this._body.collisionFilterMask = v;
          if (!this._body.isAwake()) this._body.wakeUp();
        };
        _proto.addMask = function addMask(v) {
          this._body.collisionFilterMask |= v;
          if (!this._body.isAwake()) this._body.wakeUp();
        };
        _proto.removeMask = function removeMask(v) {
          this._body.collisionFilterMask &= ~v;
          if (!this._body.isAwake()) this._body.wakeUp();
        };
        _proto.setScale = function setScale(scale) {
          this._setCenter(this._collider.center);
        };
        _proto.setIndex = function setIndex(index) {
          this._index = index;
        };
        _proto.setOffsetAndOrient = function setOffsetAndOrient(offset, orient) {
          Vec3.copy(offset, this._offset);
          Quat.copy(orient, this._orient);
          this._offset = offset;
          this._orient = orient;
        };
        _proto._setCenter = function _setCenter(v) {
          var lpos = this._offset;
          Vec3.subtract(lpos, this._sharedBody.node.worldPosition, this._collider.node.worldPosition);
          Vec3.add(lpos, lpos, v);
          Vec3.multiply(lpos, lpos, this._collider.node.worldScale);
        };
        _proto._onTrigger = function _onTrigger(event) {
          TriggerEventObject.type = event.event;
          var self = getWrap(event.selfShape);
          var other = getWrap(event.otherShape);
          if (self && self.collider.needTriggerEvent) {
            TriggerEventObject.selfCollider = self.collider;
            TriggerEventObject.otherCollider = other ? other.collider : null;
            TriggerEventObject.impl = event;
            this._collider.emit(TriggerEventObject.type, TriggerEventObject);
          }
        };
        _createClass(CannonShape, [{
          key: "impl",
          get: function get() {
            return this._shape;
          }
        }, {
          key: "collider",
          get: function get() {
            return this._collider;
          }
        }, {
          key: "attachedRigidBody",
          get: function get() {
            if (this._sharedBody.wrappedBody) {
              return this._sharedBody.wrappedBody.rigidBody;
            }
            return null;
          }
        }, {
          key: "sharedBody",
          get: function get() {
            return this._sharedBody;
          }
        }, {
          key: "_body",
          get: function get() {
            return this._sharedBody.body;
          }
        }]);
        return CannonShape;
      }();
      CannonShape.idToMaterial = {};

      legacyCC.physics = physics;

      var quat = new Quat();
      var CannonContactEquation = function () {
        function CannonContactEquation(event) {
          this.impl = null;
          this.event = void 0;
          this.event = event;
        }
        var _proto = CannonContactEquation.prototype;
        _proto.getLocalPointOnA = function getLocalPointOnA(out) {
          if (this.impl) Vec3.copy(out, this.impl.rj);
        };
        _proto.getLocalPointOnB = function getLocalPointOnB(out) {
          if (this.impl) Vec3.copy(out, this.impl.ri);
        };
        _proto.getWorldPointOnA = function getWorldPointOnA(out) {
          if (this.impl) Vec3.add(out, this.impl.rj, this.impl.bj.position);
        };
        _proto.getWorldPointOnB = function getWorldPointOnB(out) {
          if (this.impl) Vec3.add(out, this.impl.ri, this.impl.bi.position);
        };
        _proto.getLocalNormalOnA = function getLocalNormalOnA(out) {
          if (this.impl) {
            this.getWorldNormalOnA(out);
            Quat.conjugate(quat, this.impl.bi.quaternion);
            Vec3.transformQuat(out, out, quat);
          }
        };
        _proto.getLocalNormalOnB = function getLocalNormalOnB(out) {
          if (this.impl) {
            Quat.conjugate(quat, this.impl.bj.quaternion);
            Vec3.transformQuat(out, this.impl.ni, quat);
          }
        };
        _proto.getWorldNormalOnA = function getWorldNormalOnA(out) {
          if (this.impl) {
            this.getWorldNormalOnB(out);
            if (!this.isBodyA) Vec3.negate(out, out);
          }
        };
        _proto.getWorldNormalOnB = function getWorldNormalOnB(out) {
          if (this.impl) Vec3.copy(out, this.impl.ni);
        };
        _createClass(CannonContactEquation, [{
          key: "isBodyA",
          get: function get() {
            if (this.impl) {
              var si = this.event.selfCollider.shape.impl;
              var bj = this.impl.bj;
              return si.body.id === bj.id;
            }
            return false;
          }
        }]);
        return CannonContactEquation;
      }();

      var v3_0$3 = new Vec3();
      var quat_0$1 = new Quat();
      var contactsPool = [];
      var CollisionEventObject = {
        type: 'onCollisionEnter',
        selfCollider: null,
        otherCollider: null,
        contacts: [],
        impl: null
      };
      var CannonSharedBody = function () {
        CannonSharedBody.getSharedBody = function getSharedBody(node, wrappedWorld, wrappedBody) {
          var key = node.uuid;
          var newSB;
          if (CannonSharedBody.sharedBodesMap.has(key)) {
            newSB = CannonSharedBody.sharedBodesMap.get(key);
          } else {
            newSB = new CannonSharedBody(node, wrappedWorld);
            var g = PhysicsGroup.DEFAULT;
            var m = PhysicsSystem.instance.collisionMatrix[g];
            newSB.body.collisionFilterGroup = g;
            newSB.body.collisionFilterMask = m;
            newSB.body.position = new cannon.Vec3(node.worldPosition.x, node.worldPosition.y, node.worldPosition.z);
            newSB.body.quaternion = new cannon.Quaternion(node.worldRotation.x, node.worldRotation.y, node.worldRotation.z, node.worldRotation.w);
            CannonSharedBody.sharedBodesMap.set(node.uuid, newSB);
          }
          if (wrappedBody) {
            newSB.wrappedBody = wrappedBody;
            var _g = wrappedBody.rigidBody.group;
            var _m = PhysicsSystem.instance.collisionMatrix[_g];
            newSB.body.collisionFilterGroup = _g;
            newSB.body.collisionFilterMask = _m;
            newSB.body.position = new cannon.Vec3(node.worldPosition.x, node.worldPosition.y, node.worldPosition.z);
            newSB.body.quaternion = new cannon.Quaternion(node.worldRotation.x, node.worldRotation.y, node.worldRotation.z, node.worldRotation.w);
          }
          return newSB;
        };
        function CannonSharedBody(node, wrappedWorld) {
          this.node = void 0;
          this.wrappedWorld = void 0;
          this.body = void 0;
          this.wrappedShapes = [];
          this.wrappedJoints0 = [];
          this.wrappedJoints1 = [];
          this.wrappedBody = null;
          this.index = -1;
          this.ref = 0;
          this.onCollidedListener = this.onCollided.bind(this);
          this.wrappedWorld = wrappedWorld;
          this.node = node;
          this.body = new cannon.Body();
          setWrap(this.body, this);
          this.body.collisionFilterGroup = PhysicsSystem.PhysicsGroup.DEFAULT;
          this.body.sleepSpeedLimit = PhysicsSystem.instance.sleepThreshold;
          this.body.material = this.wrappedWorld.impl.defaultMaterial;
          this.body.addEventListener('cc-collide', this.onCollidedListener);
        }
        var _proto = CannonSharedBody.prototype;
        _proto.addShape = function addShape(v) {
          var index = this.wrappedShapes.indexOf(v);
          if (index < 0) {
            var _index = this.body.shapes.length;
            this.body.addShape(v.impl);
            this.wrappedShapes.push(v);
            v.setIndex(_index);
            var offset = this.body.shapeOffsets[_index];
            var orient = this.body.shapeOrientations[_index];
            v.setOffsetAndOrient(offset, orient);
            if (this.body.isSleeping()) this.body.wakeUp();
          }
        };
        _proto.removeShape = function removeShape(v) {
          var index = this.wrappedShapes.indexOf(v);
          if (index >= 0) {
            fastRemoveAt$2(this.wrappedShapes, index);
            this.body.removeShape(v.impl);
            v.setIndex(-1);
            if (this.body.isSleeping()) this.body.wakeUp();
          }
        };
        _proto.addJoint = function addJoint(v, type) {
          if (type) {
            var i = this.wrappedJoints1.indexOf(v);
            if (i < 0) this.wrappedJoints1.push(v);
          } else {
            var _i = this.wrappedJoints0.indexOf(v);
            if (_i < 0) this.wrappedJoints0.push(v);
          }
        };
        _proto.removeJoint = function removeJoint(v, type) {
          if (type) {
            var i = this.wrappedJoints1.indexOf(v);
            if (i >= 0) fastRemoveAt$2(this.wrappedJoints1, i);
          } else {
            var _i2 = this.wrappedJoints0.indexOf(v);
            if (_i2 >= 0) fastRemoveAt$2(this.wrappedJoints0, _i2);
          }
        };
        _proto.syncSceneToPhysics = function syncSceneToPhysics() {
          var node = this.node;
          var body = this.body;
          if (node.hasChangedFlags) {
            if (body.isSleeping()) body.wakeUp();
            Vec3.copy(body.position, node.worldPosition);
            Quat.copy(body.quaternion, node.worldRotation);
            body.aabbNeedsUpdate = true;
            if (node.hasChangedFlags & TransformBit.SCALE) this.syncScale();
          }
        };
        _proto.syncPhysicsToScene = function syncPhysicsToScene() {
          var n = this.node;
          var b = this.body;
          if (b.type === ERigidBodyType.DYNAMIC) {
            if (!b.isSleeping()) {
              Vec3.copy(v3_0$3, b.position);
              Quat.copy(quat_0$1, b.quaternion);
              n.worldPosition = v3_0$3;
              n.worldRotation = quat_0$1;
            }
          }
        };
        _proto.syncInitial = function syncInitial() {
          var n = this.node;
          var b = this.body;
          Vec3.copy(b.position, n.worldPosition);
          Quat.copy(b.quaternion, n.worldRotation);
          Vec3.copy(b.previousPosition, n.worldPosition);
          Quat.copy(b.previousQuaternion, n.worldRotation);
          b.aabbNeedsUpdate = true;
          this.syncScale();
          if (b.isSleeping()) b.wakeUp();
        };
        _proto.syncScale = function syncScale() {
          for (var i = 0; i < this.wrappedShapes.length; i++) {
            this.wrappedShapes[i].setScale(this.node.worldScale);
          }
          for (var _i3 = 0; _i3 < this.wrappedJoints0.length; _i3++) {
            this.wrappedJoints0[_i3].updateScale0();
          }
          for (var _i4 = 0; _i4 < this.wrappedJoints1.length; _i4++) {
            this.wrappedJoints1[_i4].updateScale1();
          }
          commitShapeUpdates(this.body);
        };
        _proto.destroy = function destroy() {
          setWrap(this.body, null);
          this.body.removeEventListener('cc-collide', this.onCollidedListener);
          CannonSharedBody.sharedBodesMap["delete"](this.node.uuid);
          delete cannon.World.idToBodyMap[this.body.id];
          this.node = null;
          this.wrappedWorld = null;
          this.body = null;
          this.wrappedShapes = null;
          this.wrappedJoints0 = null;
          this.wrappedJoints1 = null;
          this.onCollidedListener = null;
        };
        _proto.onCollided = function onCollided(event) {
          CollisionEventObject.type = event.event;
          var self = getWrap(event.selfShape);
          var other = getWrap(event.otherShape);
          if (self && self.collider.needCollisionEvent) {
            contactsPool.push.apply(contactsPool, CollisionEventObject.contacts);
            CollisionEventObject.contacts.length = 0;
            CollisionEventObject.impl = event;
            CollisionEventObject.selfCollider = self.collider;
            CollisionEventObject.otherCollider = other ? other.collider : null;
            var i = 0;
            if (CollisionEventObject.type !== 'onCollisionExit') {
              for (i = 0; i < event.contacts.length; i++) {
                var cq = event.contacts[i];
                if (contactsPool.length > 0) {
                  var c = contactsPool.pop();
                  c.impl = cq;
                  CollisionEventObject.contacts.push(c);
                } else {
                  var _c = new CannonContactEquation(CollisionEventObject);
                  _c.impl = cq;
                  CollisionEventObject.contacts.push(_c);
                }
              }
            }
            for (i = 0; i < this.wrappedShapes.length; i++) {
              var shape = this.wrappedShapes[i];
              shape.collider.emit(CollisionEventObject.type, CollisionEventObject);
            }
          }
        };
        _createClass(CannonSharedBody, [{
          key: "enabled",
          set: function set(v) {
            if (v) {
              if (this.index < 0) {
                this.index = this.wrappedWorld.bodies.length;
                this.wrappedWorld.addSharedBody(this);
                this.syncInitial();
              }
            } else if (this.index >= 0) {
              var isRemove = this.wrappedShapes.length === 0 && this.wrappedBody == null || this.wrappedShapes.length === 0 && this.wrappedBody != null && !this.wrappedBody.isEnabled;
              if (isRemove) {
                this.body.sleep();
                this.index = -1;
                this.wrappedWorld.removeSharedBody(this);
              }
            }
          }
        }, {
          key: "reference",
          set: function set(v) {
            v ? this.ref++ : this.ref--;
            if (this.ref === 0) {
              this.destroy();
            }
          }
        }]);
        return CannonSharedBody;
      }();
      CannonSharedBody.sharedBodesMap = new Map();

      var CannonWorld = function () {
        var _proto = CannonWorld.prototype;
        _proto.setDefaultMaterial = function setDefaultMaterial(mat) {
          this._world.defaultMaterial.friction = mat.friction;
          this._world.defaultMaterial.restitution = mat.restitution;
          if (CannonShape.idToMaterial[mat.id] != null) {
            CannonShape.idToMaterial[mat.id] = this._world.defaultMaterial;
          }
        };
        _proto.setAllowSleep = function setAllowSleep(v) {
          this._world.allowSleep = v;
        };
        _proto.setGravity = function setGravity(gravity) {
          Vec3.copy(this._world.gravity, gravity);
        };
        function CannonWorld() {
          this.bodies = [];
          this.constraints = [];
          this._world = void 0;
          this._world = new cannon.World();
          this._world.broadphase = new cannon.NaiveBroadphase();
          this._world.solver.iterations = 10;
          this._world.solver.tolerance = 0.0001;
          this._world.defaultContactMaterial.contactEquationStiffness = 1000000;
          this._world.defaultContactMaterial.frictionEquationStiffness = 1000000;
          this._world.defaultContactMaterial.contactEquationRelaxation = 3;
          this._world.defaultContactMaterial.frictionEquationRelaxation = 3;
        }
        _proto.sweepBox = function sweepBox(worldRay, halfExtent, orientation, options, pool, results) {
          warnID(9641);
          return false;
        };
        _proto.sweepBoxClosest = function sweepBoxClosest(worldRay, halfExtent, orientation, options, result) {
          warnID(9641);
          return false;
        };
        _proto.sweepSphere = function sweepSphere(worldRay, radius, options, pool, results) {
          warnID(9641);
          return false;
        };
        _proto.sweepSphereClosest = function sweepSphereClosest(worldRay, radius, options, result) {
          warnID(9641);
          return false;
        };
        _proto.sweepCapsule = function sweepCapsule(worldRay, radius, height, orientation, options, pool, results) {
          warnID(9641);
          return false;
        };
        _proto.sweepCapsuleClosest = function sweepCapsuleClosest(worldRay, radius, height, orientation, options, result) {
          warnID(9641);
          return false;
        };
        _proto.destroy = function destroy() {
          if (this.constraints.length || this.bodies.length) error('You should destroy all physics component first.');
          this._world.broadphase = null;
          this._world = null;
        };
        _proto.emitEvents = function emitEvents() {
          this._world.emitTriggeredEvents();
          this._world.emitCollisionEvents();
        };
        _proto.syncSceneToPhysics = function syncSceneToPhysics() {
          for (var i = 0; i < this.bodies.length; i++) {
            this.bodies[i].syncSceneToPhysics();
          }
        };
        _proto.syncAfterEvents = function syncAfterEvents() {
          this.syncSceneToPhysics();
        };
        _proto.step = function step(deltaTime, timeSinceLastCalled, maxSubStep) {
          if (this.bodies.length === 0) return;
          this._world.step(deltaTime, timeSinceLastCalled, maxSubStep);
          for (var i = 0; i < this.bodies.length; i++) {
            this.bodies[i].syncPhysicsToScene();
          }
        };
        _proto.raycastClosest = function raycastClosest(worldRay, options, result) {
          setupFromAndTo(worldRay, options.maxDistance);
          toCannonRaycastOptions(raycastOpt, options);
          var hit = this._world.raycastClosest(from, to, raycastOpt, CannonWorld.rayResult);
          if (hit) {
            fillRaycastResult(result, CannonWorld.rayResult);
          }
          return hit;
        };
        _proto.raycast = function raycast(worldRay, options, pool, results) {
          setupFromAndTo(worldRay, options.maxDistance);
          toCannonRaycastOptions(raycastOpt, options);
          var hit = this._world.raycastAll(from, to, raycastOpt, function (result) {
            var r = pool.add();
            fillRaycastResult(r, result);
            results.push(r);
          });
          return hit;
        };
        _proto.getSharedBody = function getSharedBody(node, wrappedBody) {
          return CannonSharedBody.getSharedBody(node, this, wrappedBody);
        };
        _proto.addSharedBody = function addSharedBody(sharedBody) {
          var i = this.bodies.indexOf(sharedBody);
          if (i < 0) {
            this.bodies.push(sharedBody);
            this._world.addBody(sharedBody.body);
          }
        };
        _proto.removeSharedBody = function removeSharedBody(sharedBody) {
          var i = this.bodies.indexOf(sharedBody);
          if (i >= 0) {
            fastRemoveAt$2(this.bodies, i);
            this._world.remove(sharedBody.body);
          }
        };
        _proto.addConstraint = function addConstraint(constraint) {
          var i = this.constraints.indexOf(constraint);
          if (i < 0) {
            this.constraints.push(constraint);
            this._world.addConstraint(constraint.impl);
          }
        };
        _proto.removeConstraint = function removeConstraint(constraint) {
          var i = this.constraints.indexOf(constraint);
          if (i >= 0) {
            fastRemoveAt$2(this.constraints, i);
            this._world.removeConstraint(constraint.impl);
          }
        };
        _createClass(CannonWorld, [{
          key: "impl",
          get: function get() {
            return this._world;
          }
        }]);
        return CannonWorld;
      }();
      CannonWorld.rayResult = new cannon.RaycastResult();
      var from = new cannon.Vec3();
      var to = new cannon.Vec3();
      function setupFromAndTo(worldRay, distance) {
        Vec3.copy(from, worldRay.o);
        worldRay.computeHit(to, distance);
      }
      var raycastOpt = {
        checkCollisionResponse: false,
        collisionFilterGroup: -1,
        collisionFilterMask: -1,
        skipBackfaces: true
      };

      var CannonBoxShape = function (_CannonShape) {
        _inheritsLoose(CannonBoxShape, _CannonShape);
        function CannonBoxShape() {
          var _this;
          _this = _CannonShape.call(this) || this;
          _this.halfExtent = void 0;
          _this.halfExtent = new cannon.Vec3(0.5, 0.5, 0.5);
          _this._shape = new cannon.Box(_this.halfExtent.clone());
          return _this;
        }
        var _proto = CannonBoxShape.prototype;
        _proto.updateSize = function updateSize() {
          Vec3.multiplyScalar(this.halfExtent, this.collider.size, 0.5);
          var ws = absolute(VEC3_0.set(this.collider.node.worldScale));
          var x = this.halfExtent.x * ws.x;
          var y = this.halfExtent.y * ws.y;
          var z = this.halfExtent.z * ws.z;
          var minVolumeSize = PhysicsSystem.instance.minVolumeSize;
          this.impl.halfExtents.x = clamp$1(x, minVolumeSize, Number.MAX_VALUE);
          this.impl.halfExtents.y = clamp$1(y, minVolumeSize, Number.MAX_VALUE);
          this.impl.halfExtents.z = clamp$1(z, minVolumeSize, Number.MAX_VALUE);
          this.impl.updateConvexPolyhedronRepresentation();
          if (this._index !== -1) {
            commitShapeUpdates(this._body);
          }
        };
        _proto.onLoad = function onLoad() {
          _CannonShape.prototype.onLoad.call(this);
          this.updateSize();
        };
        _proto.setScale = function setScale(scale) {
          _CannonShape.prototype.setScale.call(this, scale);
          this.updateSize();
        };
        _createClass(CannonBoxShape, [{
          key: "collider",
          get: function get() {
            return this._collider;
          }
        }, {
          key: "impl",
          get: function get() {
            return this._shape;
          }
        }]);
        return CannonBoxShape;
      }(CannonShape);

      var CannonSphereShape = function (_CannonShape) {
        _inheritsLoose(CannonSphereShape, _CannonShape);
        var _proto = CannonSphereShape.prototype;
        _proto.updateRadius = function updateRadius() {
          var max = Math.abs(absMaxComponent(this.collider.node.worldScale));
          this.impl.radius = clamp$1(this.collider.radius * Math.abs(max), PhysicsSystem.instance.minVolumeSize, Number.MAX_VALUE);
          this.impl.updateBoundingSphereRadius();
          if (this._index !== -1) {
            commitShapeUpdates(this._body);
          }
        };
        function CannonSphereShape(radius) {
          var _this;
          if (radius === void 0) {
            radius = 0.5;
          }
          _this = _CannonShape.call(this) || this;
          _this._shape = new cannon.Sphere(radius);
          return _this;
        }
        _proto.onLoad = function onLoad() {
          _CannonShape.prototype.onLoad.call(this);
          this.updateRadius();
        };
        _proto.setScale = function setScale(scale) {
          _CannonShape.prototype.setScale.call(this, scale);
          this.updateRadius();
        };
        _createClass(CannonSphereShape, [{
          key: "collider",
          get: function get() {
            return this._collider;
          }
        }, {
          key: "impl",
          get: function get() {
            return this._shape;
          }
        }]);
        return CannonSphereShape;
      }(CannonShape);

      var v3_cannon0 = new cannon.Vec3();
      var CannonTrimeshShape = function (_CannonShape) {
        _inheritsLoose(CannonTrimeshShape, _CannonShape);
        function CannonTrimeshShape() {
          return _CannonShape.apply(this, arguments) || this;
        }
        var _proto = CannonTrimeshShape.prototype;
        _proto.setMesh = function setMesh(v) {
          if (!this._isBinding) return;
          var mesh = v;
          if (this._shape != null) {
            if (mesh && mesh.renderingSubMeshes.length > 0) {
              var vertices = mesh.renderingSubMeshes[0].geometricInfo.positions;
              var indices = mesh.renderingSubMeshes[0].geometricInfo.indices;
              if (indices instanceof Uint8Array) {
                this.updateProperties(vertices, new Uint16Array(indices));
              } else if (indices instanceof Uint16Array) {
                this.updateProperties(vertices, indices);
              } else if (indices instanceof Uint32Array) {
                this.updateProperties(vertices, new Uint16Array(indices));
              } else {
                this.updateProperties(vertices, new Uint16Array());
              }
            } else {
              this.updateProperties(new Float32Array(), new Uint16Array());
            }
          } else if (mesh && mesh.renderingSubMeshes.length > 0) {
            var _vertices = mesh.renderingSubMeshes[0].geometricInfo.positions;
            var _indices = mesh.renderingSubMeshes[0].geometricInfo.indices;
            this._shape = new cannon.Trimesh(_vertices, _indices);
          } else {
            this._shape = new cannon.Trimesh(new Float32Array(), new Uint16Array());
          }
        };
        _proto.onComponentSet = function onComponentSet() {
          this.setMesh(this.collider.mesh);
        };
        _proto.onLoad = function onLoad() {
          _CannonShape.prototype.onLoad.call(this);
          this.setMesh(this.collider.mesh);
        };
        _proto.setScale = function setScale(scale) {
          _CannonShape.prototype.setScale.call(this, scale);
          Vec3.copy(v3_cannon0, scale);
          this.impl.setScale(v3_cannon0);
        };
        _proto.updateProperties = function updateProperties(vertices, indices) {
          this.impl.vertices = new Float32Array(vertices);
          this.impl.indices = new Int16Array(indices);
          this.impl.normals = new Float32Array(indices.length);
          this.impl.aabb = new cannon.AABB();
          this.impl.edges = [];
          this.impl.tree = new cannon.Octree(new cannon.AABB());
          this.impl.updateEdges();
          this.impl.updateNormals();
          this.impl.updateAABB();
          this.impl.updateBoundingSphereRadius();
          this.impl.updateTree();
          this.impl.setScale(this.impl.scale);
          if (this._index >= 0) {
            commitShapeUpdates(this._body);
          }
        };
        _createClass(CannonTrimeshShape, [{
          key: "collider",
          get: function get() {
            return this._collider;
          }
        }, {
          key: "impl",
          get: function get() {
            return this._shape;
          }
        }]);
        return CannonTrimeshShape;
      }(CannonShape);

      var CannonCylinderShape = function (_CannonShape) {
        _inheritsLoose(CannonCylinderShape, _CannonShape);
        var _proto = CannonCylinderShape.prototype;
        _proto.setRadius = function setRadius(v) {
          this.updateProperties(this.collider.radius, this.collider.height, cannon.CC_CONFIG.numSegmentsCylinder, this.collider.direction, this.collider.node.worldScale);
          if (this._index !== -1) commitShapeUpdates(this._body);
        };
        _proto.setHeight = function setHeight(v) {
          this.updateProperties(this.collider.radius, this.collider.height, cannon.CC_CONFIG.numSegmentsCylinder, this.collider.direction, this.collider.node.worldScale);
          if (this._index !== -1) commitShapeUpdates(this._body);
        };
        _proto.setDirection = function setDirection(v) {
          this.updateProperties(this.collider.radius, this.collider.height, cannon.CC_CONFIG.numSegmentsCylinder, this.collider.direction, this.collider.node.worldScale);
          if (this._index !== -1) commitShapeUpdates(this._body);
        };
        function CannonCylinderShape(radius, height, direction) {
          var _this;
          if (radius === void 0) {
            radius = 0.5;
          }
          if (height === void 0) {
            height = 2;
          }
          if (direction === void 0) {
            direction = EAxisDirection.Y_AXIS;
          }
          _this = _CannonShape.call(this) || this;
          _this._shape = new cannon.Cylinder(radius, radius, height, cannon.CC_CONFIG.numSegmentsCylinder, direction === EAxisDirection.Y_AXIS);
          return _this;
        }
        _proto.onLoad = function onLoad() {
          _CannonShape.prototype.onLoad.call(this);
          this.setRadius(this.collider.radius);
        };
        _proto.setScale = function setScale(scale) {
          _CannonShape.prototype.setScale.call(this, scale);
          this.setRadius(this.collider.radius);
        };
        _proto.updateProperties = function updateProperties(radius, height, numSegments, direction, scale) {
          var wh = height;
          var wr = radius;
          var cos = Math.cos;
          var sin = Math.sin;
          var abs = Math.abs;
          var max = Math.max;
          if (direction === 1) {
            wh = abs(scale.y) * height;
            wr = max(abs(scale.x), abs(scale.z)) * radius;
          } else if (direction === 2) {
            wh = abs(scale.z) * height;
            wr = max(abs(scale.x), abs(scale.y)) * radius;
          } else {
            wh = abs(scale.x) * height;
            wr = max(abs(scale.y), abs(scale.z)) * radius;
          }
          var N = numSegments;
          var hH = wh / 2;
          var vertices = [];
          var indices = [];
          var axes = [];
          var theta = Math.PI * 2 / N;
          if (direction === 1) {
            var bf = [1];
            var tf = [0];
            for (var i = 0; i < N; i++) {
              var x = wr * cos(theta * i);
              var z = wr * sin(theta * i);
              vertices.push(new cannon.Vec3(x, hH, z));
              vertices.push(new cannon.Vec3(x, -hH, z));
              if (i < N - 1) {
                indices.push([2 * i + 2, 2 * i + 3, 2 * i + 1, 2 * i]);
                tf.push(2 * i + 2);
                bf.push(2 * i + 3);
              } else {
                indices.push([0, 1, 2 * i + 1, 2 * i]);
              }
              if (N % 2 === 1 || i < N / 2) {
                axes.push(new cannon.Vec3(cos(theta * (i + 0.5)), 0, sin(theta * (i + 0.5))));
              }
            }
            indices.push(bf);
            var temp = [];
            for (var _i = 0; _i < tf.length; _i++) {
              temp.push(tf[tf.length - _i - 1]);
            }
            indices.push(temp);
            axes.push(new cannon.Vec3(0, 1, 0));
          } else if (direction === 2) {
            var _bf = [0];
            var _tf = [1];
            for (var _i2 = 0; _i2 < N; _i2++) {
              var _x = wr * cos(theta * _i2);
              var y = wr * sin(theta * _i2);
              vertices.push(new cannon.Vec3(_x, y, hH));
              vertices.push(new cannon.Vec3(_x, y, -hH));
              if (_i2 < N - 1) {
                indices.push([2 * _i2, 2 * _i2 + 1, 2 * _i2 + 3, 2 * _i2 + 2]);
                _bf.push(2 * _i2 + 2);
                _tf.push(2 * _i2 + 3);
              } else {
                indices.push([2 * _i2, 2 * _i2 + 1, 0, 1]);
              }
              if (N % 2 === 1 || _i2 < N / 2) {
                axes.push(new cannon.Vec3(cos(theta * (_i2 + 0.5)), sin(theta * (_i2 + 0.5)), 0));
              }
            }
            indices.push(_bf);
            var _temp = [];
            for (var _i3 = 0; _i3 < _tf.length; _i3++) {
              _temp.push(_tf[_tf.length - _i3 - 1]);
            }
            indices.push(_temp);
            axes.push(new cannon.Vec3(0, 0, 1));
          } else {
            var _bf2 = [0];
            var _tf2 = [1];
            for (var _i4 = 0; _i4 < N; _i4++) {
              var _y = wr * cos(theta * _i4);
              var _z = wr * sin(theta * _i4);
              vertices.push(new cannon.Vec3(hH, _y, _z));
              vertices.push(new cannon.Vec3(-hH, _y, _z));
              if (_i4 < N - 1) {
                indices.push([2 * _i4, 2 * _i4 + 1, 2 * _i4 + 3, 2 * _i4 + 2]);
                _bf2.push(2 * _i4 + 2);
                _tf2.push(2 * _i4 + 3);
              } else {
                indices.push([2 * _i4, 2 * _i4 + 1, 0, 1]);
              }
              if (N % 2 === 1 || _i4 < N / 2) {
                axes.push(new cannon.Vec3(0, cos(theta * (_i4 + 0.5)), sin(theta * (_i4 + 0.5))));
              }
            }
            indices.push(_bf2);
            var _temp2 = [];
            for (var _i5 = 0; _i5 < _tf2.length; _i5++) {
              _temp2.push(_tf2[_tf2.length - _i5 - 1]);
            }
            indices.push(_temp2);
            axes.push(new cannon.Vec3(1, 0, 0));
          }
          this.impl.vertices = vertices;
          this.impl.faces = indices;
          this.impl.uniqueAxes = axes;
          this.impl.worldVerticesNeedsUpdate = true;
          this.impl.worldFaceNormalsNeedsUpdate = true;
          this.impl.computeNormals();
          this.impl.computeEdges();
          this.impl.updateBoundingSphereRadius();
        };
        _createClass(CannonCylinderShape, [{
          key: "collider",
          get: function get() {
            return this._collider;
          }
        }, {
          key: "impl",
          get: function get() {
            return this._shape;
          }
        }]);
        return CannonCylinderShape;
      }(CannonShape);

      var v3_0$2 = new Vec3();
      var v3_1 = new Vec3();
      var CannonConeShape = function (_CannonShape) {
        _inheritsLoose(CannonConeShape, _CannonShape);
        var _proto = CannonConeShape.prototype;
        _proto.setRadius = function setRadius(v) {
          this.updateProperties(this.collider.radius, this.collider.height, cannon.CC_CONFIG.numSegmentsCone, this.collider.direction, this.collider.node.worldScale);
          if (this._index !== -1) commitShapeUpdates(this._body);
        };
        _proto.setHeight = function setHeight(v) {
          this.updateProperties(this.collider.radius, this.collider.height, cannon.CC_CONFIG.numSegmentsCone, this.collider.direction, this.collider.node.worldScale);
          if (this._index !== -1) commitShapeUpdates(this._body);
        };
        _proto.setDirection = function setDirection(v) {
          this.updateProperties(this.collider.radius, this.collider.height, cannon.CC_CONFIG.numSegmentsCone, this.collider.direction, this.collider.node.worldScale);
          if (this._index !== -1) commitShapeUpdates(this._body);
        };
        function CannonConeShape(radius, height, direction) {
          var _this;
          if (radius === void 0) {
            radius = 0.5;
          }
          if (height === void 0) {
            height = 1;
          }
          if (direction === void 0) {
            direction = EAxisDirection.Y_AXIS;
          }
          _this = _CannonShape.call(this) || this;
          _this._shape = new cannon.Cylinder(0, radius, height, cannon.CC_CONFIG.numSegmentsCone, direction === EAxisDirection.Y_AXIS);
          return _this;
        }
        _proto.onLoad = function onLoad() {
          _CannonShape.prototype.onLoad.call(this);
          this.setRadius(this.collider.radius);
        };
        _proto.setScale = function setScale(scale) {
          _CannonShape.prototype.setScale.call(this, scale);
          this.setRadius(this.collider.radius);
        };
        _proto.updateProperties = function updateProperties(radius, height, numSegments, direction, scale) {
          var wh = height;
          var wr = radius;
          var cos = Math.cos;
          var sin = Math.sin;
          var abs = Math.abs;
          var max = Math.max;
          if (direction === 1) {
            wh = abs(scale.y) * height;
            wr = max(abs(scale.x), abs(scale.z)) * radius;
          } else if (direction === 2) {
            wh = abs(scale.z) * height;
            wr = max(abs(scale.x), abs(scale.y)) * radius;
          } else {
            wh = abs(scale.x) * height;
            wr = max(abs(scale.y), abs(scale.z)) * radius;
          }
          var N = numSegments;
          var hH = wh / 2;
          var vertices = [];
          var indices = [];
          var axes = [];
          var theta = Math.PI * 2 / N;
          if (direction === 1) {
            var bf = [];
            indices.push(bf);
            vertices.push(new cannon.Vec3(0, hH, 0));
            for (var i = 0; i < N; i++) {
              var x = wr * cos(theta * i);
              var z = wr * sin(theta * i);
              vertices.push(new cannon.Vec3(x, -hH, z));
            }
            for (var _i = 0; _i < N; _i++) {
              if (_i !== 0) bf.push(_i);
              var face = void 0;
              if (_i < N - 1) {
                face = [0, _i + 2, _i + 1];
              } else {
                face = [0, 1, _i + 1];
              }
              indices.push(face);
              Vec3.subtract(v3_0$2, vertices[0], vertices[face[1]]);
              Vec3.subtract(v3_1, vertices[face[2]], vertices[face[1]]);
              Vec3.cross(v3_0$2, v3_1, v3_0$2);
              v3_0$2.normalize();
              axes.push(new cannon.Vec3(v3_0$2.x, v3_0$2.y, v3_0$2.z));
            }
            axes.push(new cannon.Vec3(0, -1, 0));
          } else if (direction === 2) {
            var _bf = [];
            indices.push(_bf);
            vertices.push(new cannon.Vec3(0, 0, hH));
            for (var _i2 = 0; _i2 < N; _i2++) {
              var _x = wr * cos(theta * _i2);
              var y = wr * sin(theta * _i2);
              vertices.push(new cannon.Vec3(_x, y, -hH));
            }
            for (var _i3 = 0; _i3 < N; _i3++) {
              if (_i3 !== 0) _bf.push(N - _i3);
              var _face = void 0;
              if (_i3 < N - 1) {
                _face = [0, _i3 + 1, _i3 + 2];
              } else {
                _face = [0, _i3 + 1, 1];
              }
              indices.push(_face);
              Vec3.subtract(v3_0$2, vertices[0], vertices[_face[1]]);
              Vec3.subtract(v3_1, vertices[_face[2]], vertices[_face[1]]);
              Vec3.cross(v3_0$2, v3_0$2, v3_1);
              v3_0$2.normalize();
              axes.push(new cannon.Vec3(v3_0$2.x, v3_0$2.y, v3_0$2.z));
            }
            axes.push(new cannon.Vec3(0, 0, -1));
          } else {
            var _bf2 = [];
            indices.push(_bf2);
            vertices.push(new cannon.Vec3(hH, 0, 0));
            for (var _i4 = 0; _i4 < N; _i4++) {
              var _y = wr * cos(theta * _i4);
              var _z = wr * sin(theta * _i4);
              vertices.push(new cannon.Vec3(-hH, _y, _z));
            }
            for (var _i5 = 0; _i5 < N; _i5++) {
              if (_i5 !== 0) _bf2.push(N - _i5);
              var _face2 = void 0;
              if (_i5 < N - 1) {
                _face2 = [0, _i5 + 1, _i5 + 2];
              } else {
                _face2 = [0, _i5 + 1, 1];
              }
              indices.push(_face2);
              Vec3.subtract(v3_0$2, vertices[0], vertices[_face2[1]]);
              Vec3.subtract(v3_1, vertices[_face2[2]], vertices[_face2[1]]);
              Vec3.cross(v3_0$2, v3_0$2, v3_1);
              v3_0$2.normalize();
              axes.push(new cannon.Vec3(v3_0$2.x, v3_0$2.y, v3_0$2.z));
            }
            axes.push(new cannon.Vec3(-1, 0, 0));
          }
          this.impl.vertices = vertices;
          this.impl.faces = indices;
          this.impl.uniqueAxes = axes;
          this.impl.worldVerticesNeedsUpdate = true;
          this.impl.worldFaceNormalsNeedsUpdate = true;
          this.impl.computeNormals();
          this.impl.computeEdges();
          this.impl.updateBoundingSphereRadius();
        };
        _createClass(CannonConeShape, [{
          key: "collider",
          get: function get() {
            return this._collider;
          }
        }, {
          key: "impl",
          get: function get() {
            return this._shape;
          }
        }]);
        return CannonConeShape;
      }(CannonShape);

      var CANNON_AABB_LOCAL = new cannon.AABB();
      var CANNON_AABB = new cannon.AABB();
      var CANNON_TRANSFORM = new cannon.Transform();
      cannon.Heightfield.prototype.calculateWorldAABB = function (pos, quat, min, max) {
        var frame = CANNON_TRANSFORM;
        var result = CANNON_AABB;
        Vec3.copy(frame.position, pos);
        Quat.copy(frame.quaternion, quat);
        var s = this.elementSize;
        var data = this.data;
        CANNON_AABB_LOCAL.lowerBound.set(0, 0, this.minValue);
        CANNON_AABB_LOCAL.upperBound.set((data.length - 1) * s, (data[0].length - 1) * s, this.maxValue);
        CANNON_AABB_LOCAL.toWorldFrame(frame, result);
        min.copy(result.lowerBound);
        max.copy(result.upperBound);
      };
      var CannonTerrainShape = function (_CannonShape) {
        _inheritsLoose(CannonTerrainShape, _CannonShape);
        var _proto = CannonTerrainShape.prototype;
        _proto.setTerrain = function setTerrain(v) {
          if (v) {
            if (this._terrainID !== v._uuid) {
              var terrain = v;
              var sizeI = terrain.getVertexCountI();
              var sizeJ = terrain.getVertexCountJ();
              this._terrainID = terrain._uuid;
              this.data.length = sizeI - 1;
              for (var i = 0; i < sizeI; i++) {
                if (this.data[i] == null) this.data[i] = [];
                this.data[i].length = sizeJ - 1;
                for (var j = 0; j < sizeJ; j++) {
                  this.data[i][j] = terrain.getHeight(i, sizeJ - 1 - j);
                }
              }
              this.options.elementSize = terrain.tileSize;
              this.updateProperties(this.data, this.options.elementSize);
            }
          } else if (this._terrainID !== '') {
            this._terrainID = '';
            this.data.length = 1;
            this.data[0] = this.data[0] || [];
            this.data[0].length = 0;
            this.options.elementSize = 0;
            this.updateProperties(this.data, this.options.elementSize);
          }
        };
        function CannonTerrainShape() {
          var _this;
          _this = _CannonShape.call(this) || this;
          _this.data = void 0;
          _this.options = void 0;
          _this._terrainID = void 0;
          _this.data = [[]];
          _this.options = {
            elementSize: 0
          };
          _this._terrainID = '';
          return _this;
        }
        _proto.onComponentSet = function onComponentSet() {
          var terrain = this.collider.terrain;
          if (terrain) {
            var sizeI = terrain.getVertexCountI();
            var sizeJ = terrain.getVertexCountJ();
            for (var i = 0; i < sizeI; i++) {
              if (this.data[i] == null) this.data[i] = [];
              for (var j = 0; j < sizeJ; j++) {
                this.data[i][j] = terrain.getHeight(i, sizeJ - 1 - j);
              }
            }
            this.options.elementSize = terrain.tileSize;
            this._terrainID = terrain._uuid;
          }
          this._shape = new cannon.Heightfield(this.data, this.options);
        };
        _proto.onLoad = function onLoad() {
          _CannonShape.prototype.onLoad.call(this);
          this.setTerrain(this.collider.terrain);
        };
        _proto.updateProperties = function updateProperties(data, elementSize) {
          var impl = this.impl;
          impl.data = data;
          impl.elementSize = elementSize;
          impl.updateMinValue();
          impl.updateMaxValue();
          impl.updateBoundingSphereRadius();
          impl.update();
          if (this._index >= 0) {
            commitShapeUpdates(this._body);
          }
        };
        _proto._setCenter = function _setCenter(v) {
          var terrain = this.collider.terrain;
          if (terrain) {
            Quat.fromEuler(this._orient, -90, 0, 0);
            var lpos = this._offset;
            Vec3.set(lpos, 0, 0, (terrain.getVertexCountJ() - 1) * terrain.tileSize);
            Vec3.add(lpos, lpos, v);
          }
        };
        _createClass(CannonTerrainShape, [{
          key: "collider",
          get: function get() {
            return this._collider;
          }
        }, {
          key: "impl",
          get: function get() {
            return this._shape;
          }
        }]);
        return CannonTerrainShape;
      }(CannonShape);

      var CannonSimplexShape = function (_CannonShape) {
        _inheritsLoose(CannonSimplexShape, _CannonShape);
        function CannonSimplexShape() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _CannonShape.call.apply(_CannonShape, [this].concat(args)) || this;
          _this.vertices = [];
          return _this;
        }
        var _proto = CannonSimplexShape.prototype;
        _proto.setShapeType = function setShapeType(v) {
          if (this._isBinding) ;
        };
        _proto.setVertices = function setVertices(v) {
          var length = this.vertices.length;
          if (length === 4) {
            var ws = this._collider.node.worldScale;
            for (var i = 0; i < length; i++) {
              Vec3.multiply(this.vertices[i], ws, v[i]);
            }
            var impl = this.impl;
            impl.computeNormals();
            impl.computeEdges();
            impl.updateBoundingSphereRadius();
          }
          if (this._index !== -1) {
            commitShapeUpdates(this._body);
          }
        };
        _proto.onComponentSet = function onComponentSet() {
          var type = this.collider.shapeType;
          if (type === SimplexCollider.ESimplexType.TETRAHEDRON) {
            for (var i = 0; i < 4; i++) {
              this.vertices[i] = new cannon.Vec3(0, 0, 0);
            }
            this._shape = createTetra(this.vertices);
          } else {
            if (type !== SimplexCollider.ESimplexType.VERTEX) ;
            this._shape = new cannon.Particle();
          }
        };
        _proto.onLoad = function onLoad() {
          _CannonShape.prototype.onLoad.call(this);
          this.collider.updateVertices();
        };
        _proto.setScale = function setScale(scale) {
          _CannonShape.prototype.setScale.call(this, scale);
          this.collider.updateVertices();
        };
        _createClass(CannonSimplexShape, [{
          key: "collider",
          get: function get() {
            return this._collider;
          }
        }, {
          key: "impl",
          get: function get() {
            return this._shape;
          }
        }]);
        return CannonSimplexShape;
      }(CannonShape);
      var createTetra = function () {
        var faces = [[0, 3, 2], [0, 1, 3], [0, 2, 1], [1, 2, 3]];
        return function (verts) {
          return new cannon.ConvexPolyhedron(verts, faces);
        };
      }();

      var CannonPlaneShape = function (_CannonShape) {
        _inheritsLoose(CannonPlaneShape, _CannonShape);
        function CannonPlaneShape() {
          var _this;
          _this = _CannonShape.call(this) || this;
          _this._shape = new cannon.Plane();
          return _this;
        }
        var _proto = CannonPlaneShape.prototype;
        _proto.setNormal = function setNormal(v) {
          Quat.rotationTo(this._orient, Vec3.UNIT_Z, v);
          if (this._index !== -1) {
            commitShapeUpdates(this._body);
          }
        };
        _proto.setConstant = function setConstant(v) {
          Vec3.scaleAndAdd(this._offset, this._collider.center, this.collider.normal, v);
        };
        _proto.onLoad = function onLoad() {
          _CannonShape.prototype.onLoad.call(this);
          this.setConstant(this.collider.constant);
          this.setNormal(this.collider.normal);
        };
        _proto._setCenter = function _setCenter(v) {
          _CannonShape.prototype._setCenter.call(this, v);
          this.setConstant(this.collider.constant);
        };
        _createClass(CannonPlaneShape, [{
          key: "collider",
          get: function get() {
            return this._collider;
          }
        }, {
          key: "impl",
          get: function get() {
            return this._shape;
          }
        }]);
        return CannonPlaneShape;
      }(CannonShape);

      cannon.World.staticBody = new cannon.Body();
      cannon.World.idToConstraintMap = {};
      var CannonConstraint = function () {
        function CannonConstraint() {
          this._impl = void 0;
          this._com = void 0;
          this._rigidBody = void 0;
          this._connectedBody = void 0;
        }
        var _proto = CannonConstraint.prototype;
        _proto.setConnectedBody = function setConnectedBody(v) {
          if (this._connectedBody === v) return;
          var oldBody2 = this._connectedBody;
          if (oldBody2) {
            var oldSB2 = oldBody2.body.sharedBody;
            oldSB2.removeJoint(this, 1);
          }
          var sb = this._rigidBody.body.sharedBody;
          sb.removeJoint(this, 0);
          if (this._impl) {
            sb.wrappedWorld.removeConstraint(this);
            delete cannon.World.idToConstraintMap[this._impl.id];
            this._impl = null;
          }
          this._connectedBody = v;
          var connect = this._connectedBody;
          this.onComponentSet();
          this.setEnableCollision(this._com.enableCollision);
          cannon.World.idToConstraintMap[this._impl.id] = this._impl;
          sb.wrappedWorld.addConstraint(this);
          sb.addJoint(this, 0);
          if (connect) {
            var newSB2 = connect.body.sharedBody;
            newSB2.addJoint(this, 1);
          }
        };
        _proto.setEnableCollision = function setEnableCollision(v) {
          this._impl.collideConnected = v;
        };
        _proto.initialize = function initialize(v) {
          this._com = v;
          this._rigidBody = v.attachedBody;
          this._connectedBody = v.connectedBody;
          this.onComponentSet();
          this.setEnableCollision(v.enableCollision);
          cannon.World.idToConstraintMap[this._impl.id] = this._impl;
        };
        _proto.onComponentSet = function onComponentSet() {};
        _proto.updateScale0 = function updateScale0() {};
        _proto.updateScale1 = function updateScale1() {};
        _proto.onEnable = function onEnable() {
          var sb = this._rigidBody.body.sharedBody;
          sb.wrappedWorld.addConstraint(this);
          sb.addJoint(this, 0);
          var connect = this._connectedBody;
          if (connect) {
            var sb2 = connect.body.sharedBody;
            sb2.addJoint(this, 1);
          }
        };
        _proto.onDisable = function onDisable() {
          var sb = this._rigidBody.body.sharedBody;
          sb.wrappedWorld.removeConstraint(this);
          sb.removeJoint(this, 0);
          var connect = this._connectedBody;
          if (connect) {
            var sb2 = connect.body.sharedBody;
            sb2.removeJoint(this, 1);
          }
        };
        _proto.onDestroy = function onDestroy() {
          delete cannon.World.idToConstraintMap[this._impl.id];
          this._com = null;
          this._rigidBody = null;
          this._connectedBody = null;
          this._impl = null;
        };
        _createClass(CannonConstraint, [{
          key: "impl",
          get: function get() {
            return this._impl;
          }
        }, {
          key: "constraint",
          get: function get() {
            return this._com;
          }
        }]);
        return CannonConstraint;
      }();

      var v3_0$1 = new Vec3();
      var CannonPointToPointConstraint = function (_CannonConstraint) {
        _inheritsLoose(CannonPointToPointConstraint, _CannonConstraint);
        function CannonPointToPointConstraint() {
          return _CannonConstraint.apply(this, arguments) || this;
        }
        var _proto = CannonPointToPointConstraint.prototype;
        _proto.setPivotA = function setPivotA(v) {
          var cs = this.constraint;
          Vec3.multiply(this.impl.pivotA, cs.node.worldScale, cs.pivotA);
          if (!cs.connectedBody) this.setPivotB(cs.pivotB);
        };
        _proto.setPivotB = function setPivotB(v) {
          var cs = this.constraint;
          var cb = cs.connectedBody;
          if (cb) {
            Vec3.multiply(this.impl.pivotB, cb.node.worldScale, cs.pivotB);
          } else {
            var node = cs.node;
            Vec3.multiply(v3_0$1, node.worldScale, cs.pivotA);
            Vec3.transformQuat(v3_0$1, v3_0$1, node.worldRotation);
            Vec3.add(v3_0$1, v3_0$1, node.worldPosition);
            Vec3.copy(this.impl.pivotB, v3_0$1);
          }
        };
        _proto.onComponentSet = function onComponentSet() {
          var bodyA = this._rigidBody.body.impl;
          var cb = this.constraint.connectedBody;
          var bodyB = cannon.World.staticBody;
          if (cb) {
            bodyB = cb.body.impl;
          }
          this._impl = new cannon.PointToPointConstraint(bodyA, null, bodyB);
          this.setPivotA(this.constraint.pivotA);
          this.setPivotB(this.constraint.pivotB);
        };
        _proto.updateScale0 = function updateScale0() {
          this.setPivotA(this.constraint.pivotA);
        };
        _proto.updateScale1 = function updateScale1() {
          this.setPivotB(this.constraint.pivotB);
        };
        _createClass(CannonPointToPointConstraint, [{
          key: "impl",
          get: function get() {
            return this._impl;
          }
        }, {
          key: "constraint",
          get: function get() {
            return this._com;
          }
        }]);
        return CannonPointToPointConstraint;
      }(CannonConstraint);

      var v3_0 = new Vec3();
      var quat_0 = new Quat();
      var CannonHingeConstraint = function (_CannonConstraint) {
        _inheritsLoose(CannonHingeConstraint, _CannonConstraint);
        function CannonHingeConstraint() {
          return _CannonConstraint.apply(this, arguments) || this;
        }
        var _proto = CannonHingeConstraint.prototype;
        _proto.setPivotA = function setPivotA(v) {
          var cs = this.constraint;
          Vec3.multiply(this.impl.pivotA, this.constraint.node.worldScale, cs.pivotA);
          if (!cs.connectedBody) this.setPivotB(cs.pivotB);
        };
        _proto.setPivotB = function setPivotB(v) {
          var cs = this.constraint;
          var cb = cs.connectedBody;
          if (cb) {
            Vec3.multiply(this.impl.pivotB, cb.node.worldScale, cs.pivotB);
          } else {
            var node = this.constraint.node;
            Vec3.multiply(v3_0, node.worldScale, cs.pivotA);
            Vec3.transformQuat(v3_0, v3_0, node.worldRotation);
            Vec3.add(v3_0, v3_0, node.worldPosition);
            Vec3.copy(this.impl.pivotB, v3_0);
          }
        };
        _proto.setAxis = function setAxis(v) {
          var equations = this.impl.equations;
          Vec3.copy(this.impl.axisA, v);
          Vec3.copy(equations[3].axisA, v);
          Vec3.copy(equations[4].axisA, v);
          Vec3.copy(equations[5].axisA, v);
          if (this.constraint.connectedBody) {
            Vec3.transformQuat(this.impl.axisB, v, this.constraint.node.worldRotation);
            Quat.invert(quat_0, this.constraint.connectedBody.node.worldRotation);
            Vec3.transformQuat(this.impl.axisB, this.impl.axisB, quat_0);
            Vec3.copy(equations[3].axisB, this.impl.axisB);
            Vec3.copy(equations[4].axisB, this.impl.axisB);
            Vec3.copy(equations[5].axisB, this.impl.axisB);
          } else {
            Vec3.transformQuat(this.impl.axisB, v, this.constraint.node.worldRotation);
            Vec3.copy(equations[3].axisB, this.impl.axisB);
            Vec3.copy(equations[4].axisB, this.impl.axisB);
            Vec3.copy(equations[5].axisB, this.impl.axisB);
          }
        };
        _proto.setLimitEnabled = function setLimitEnabled(v) {
          warnID(9613);
        };
        _proto.setLowerLimit = function setLowerLimit(min) {
          warnID(9613);
        };
        _proto.setUpperLimit = function setUpperLimit(max) {
          warnID(9613);
        };
        _proto.setMotorEnabled = function setMotorEnabled(v) {
          warnID(9613);
        };
        _proto.setMotorVelocity = function setMotorVelocity(v) {
          warnID(9613);
        };
        _proto.setMotorForceLimit = function setMotorForceLimit(v) {
          warnID(9613);
        };
        _proto.onComponentSet = function onComponentSet() {
          var bodyA = this._rigidBody.body.impl;
          var cb = this.constraint.connectedBody;
          var bodyB = cannon.World.staticBody;
          if (cb) {
            bodyB = cb.body.impl;
          }
          this._impl = new cannon.HingeConstraint(bodyA, bodyB);
          this.setPivotA(this.constraint.pivotA);
          this.setPivotB(this.constraint.pivotB);
          this.setAxis(this.constraint.axis);
        };
        _proto.updateScale0 = function updateScale0() {
          this.setPivotA(this.constraint.pivotA);
        };
        _proto.updateScale1 = function updateScale1() {
          this.setPivotB(this.constraint.pivotB);
        };
        _createClass(CannonHingeConstraint, [{
          key: "impl",
          get: function get() {
            return this._impl;
          }
        }, {
          key: "constraint",
          get: function get() {
            return this._com;
          }
        }]);
        return CannonHingeConstraint;
      }(CannonConstraint);

      var CannonLockConstraint = function (_CannonConstraint) {
        _inheritsLoose(CannonLockConstraint, _CannonConstraint);
        function CannonLockConstraint() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _CannonConstraint.call.apply(_CannonConstraint, [this].concat(args)) || this;
          _this._breakForce = 1e9;
          return _this;
        }
        var _proto = CannonLockConstraint.prototype;
        _proto.setBreakForce = function setBreakForce(v) {
          this._breakForce = v;
          this.updateFrame();
        };
        _proto.setBreakTorque = function setBreakTorque(v) {};
        _proto.onComponentSet = function onComponentSet() {
          this._breakForce = this.constraint.breakForce;
          this.updateFrame();
        };
        _proto.updateFrame = function updateFrame() {
          var bodyA = this._rigidBody.body.impl;
          var cb = this.constraint.connectedBody;
          var bodyB = cannon.World.staticBody;
          if (cb) {
            bodyB = cb.body.impl;
          }
          this._impl = new cannon.LockConstraint(bodyA, bodyB, {
            maxForce: this._breakForce
          });
        };
        _proto.updateScale0 = function updateScale0() {
          this.updateFrame();
        };
        _proto.updateScale1 = function updateScale1() {
          this.updateFrame();
        };
        _createClass(CannonLockConstraint, [{
          key: "impl",
          get: function get() {
            return this._impl;
          }
        }, {
          key: "constraint",
          get: function get() {
            return this._com;
          }
        }]);
        return CannonLockConstraint;
      }(CannonConstraint);

      game.once(Game.EVENT_PRE_SUBSYSTEM_INIT, function () {
        selector.register('cannon.js', {
          PhysicsWorld: CannonWorld,
          RigidBody: CannonRigidBody,
          BoxShape: CannonBoxShape,
          SphereShape: CannonSphereShape,
          TrimeshShape: CannonTrimeshShape,
          CylinderShape: CannonCylinderShape,
          ConeShape: CannonConeShape,
          TerrainShape: CannonTerrainShape,
          SimplexShape: CannonSimplexShape,
          PlaneShape: CannonPlaneShape,
          PointToPointConstraint: CannonPointToPointConstraint,
          HingeConstraint: CannonHingeConstraint,
          FixedConstraint: CannonLockConstraint
        });
      });

      if (globalThis) globalThis.CANNON = cannon;
      cannon.CC_CONFIG = {
        numSegmentsCone: 12,
        numSegmentsCylinder: 12,
        ignoreSelfBody: true,
        correctInelastic: 3
      };
      cannon.ArrayCollisionMatrix.prototype.reset = function reset() {
        for (var key in this.matrix) {
          delete this.matrix[key];
        }
      };
      cannon.Ray.perBodyFilter = function (r, b) {
        return (r.collisionFilterMask & b.collisionFilterGroup) !== 0;
      };

      var _dec$j, _dec2$h, _class$j, _class2$g, _initializer$f, _initializer2$f, _class3$b;
      var PrimitiveType;
      (function (PrimitiveType) {
        PrimitiveType[PrimitiveType["BOX"] = 0] = "BOX";
        PrimitiveType[PrimitiveType["SPHERE"] = 1] = "SPHERE";
        PrimitiveType[PrimitiveType["CYLINDER"] = 2] = "CYLINDER";
        PrimitiveType[PrimitiveType["CONE"] = 3] = "CONE";
        PrimitiveType[PrimitiveType["CAPSULE"] = 4] = "CAPSULE";
        PrimitiveType[PrimitiveType["TORUS"] = 5] = "TORUS";
        PrimitiveType[PrimitiveType["PLANE"] = 6] = "PLANE";
        PrimitiveType[PrimitiveType["QUAD"] = 7] = "QUAD";
      })(PrimitiveType || (PrimitiveType = {}));
      ccenum(PrimitiveType);
      var Primitive = exports('f8', (_dec$j = ccclass$n('cc.Primitive'), _dec2$h = type$7(PrimitiveType), _dec$j(_class$j = (_class2$g = (_class3$b = function (_Mesh) {
        _inheritsLoose(Primitive, _Mesh);
        function Primitive(type) {
          var _this;
          if (type === void 0) {
            type = PrimitiveType.BOX;
          }
          _this = _Mesh.call(this) || this;
          _this.type = _initializer$f && _initializer$f();
          _this.info = _initializer2$f && _initializer2$f();
          _this.type = type;
          return _this;
        }
        var _proto = Primitive.prototype;
        _proto.onLoaded = function onLoaded() {
          _createMesh(primitives[PrimitiveType[this.type].toLowerCase()](this.info), this);
        };
        return Primitive;
      }(Mesh), _class3$b.PrimitiveType = PrimitiveType, _class3$b), (_initializer$f = applyDecoratedInitializer(_class2$g.prototype, "type", [_dec2$h], function () {
        return PrimitiveType.BOX;
      }), _initializer2$f = applyDecoratedInitializer(_class2$g.prototype, "info", [serializable$j], function () {
        return {};
      })), _class2$g)) || _class$j));
      legacyCC.Primitive = Primitive;

      legacyCC.primitives = primitives;

      var Counter = function () {
        function Counter(id, opts, now) {
          this._opts = void 0;
          this._total = 0;
          this._value = 0;
          this._averageValue = 0;
          this._accumValue = 0;
          this._accumSamples = 0;
          this._id = id;
          this._opts = opts;
          this._accumStart = now;
        }
        var _proto = Counter.prototype;
        _proto.sample = function sample(now) {
          this._average(this._value, now);
        };
        _proto.human = function human() {
          var _this$_opts = this._opts,
            average = _this$_opts.average,
            isInteger = _this$_opts.isInteger;
          var v = average ? this._averageValue : this._value;
          return isInteger ? Math.round(v) : Math.round(v * 100) / 100;
        };
        _proto.alarm = function alarm() {
          return this._opts.below && this._value < this._opts.below || this._opts.over && this._value > this._opts.over;
        };
        _proto._average = function _average(v, now) {
          if (now === void 0) {
            now = 0;
          }
          if (this._opts.average) {
            this._accumValue += v;
            ++this._accumSamples;
            var t = now;
            if (t - this._accumStart >= this._opts.average) {
              this._averageValue = this._accumValue / this._accumSamples;
              this._accumValue = 0;
              this._accumStart = t;
              this._accumSamples = 0;
            }
          }
        };
        _createClass(Counter, [{
          key: "value",
          get: function get() {
            return this._value;
          },
          set: function set(val) {
            this._value = val;
          }
        }]);
        return Counter;
      }();

      var _dec$i, _class$i;
      var PerfCounter = (_dec$i = ccclass$n('cc.PerfCounter'), _dec$i(_class$i = function (_Counter) {
        _inheritsLoose(PerfCounter, _Counter);
        function PerfCounter(id, opts, now) {
          var _this;
          _this = _Counter.call(this, id, opts, now) || this;
          _this._time = now;
          return _this;
        }
        var _proto = PerfCounter.prototype;
        _proto.start = function start(now) {
          if (now === void 0) {
            now = 0;
          }
          this._time = now;
        };
        _proto.end = function end(now) {
          if (now === void 0) {
            now = 0;
          }
          this._value = now - this._time;
          this._average(this._value);
        };
        _proto.tick = function tick() {
          this.end();
          this.start();
        };
        _proto.frame = function frame(now) {
          var t = now;
          var e = t - this._time;
          this._total++;
          var avg = this._opts.average || 1000;
          if (e > avg) {
            this._value = this._total * 1000 / e;
            this._total = 0;
            this._time = t;
            this._average(this._value);
          }
        };
        return PerfCounter;
      }(Counter)) || _class$i);

      var _characters = '0123456789. ';
      var _average = 500;
      var _string2offset = {
        0: 0,
        1: 1,
        2: 2,
        3: 3,
        4: 4,
        5: 5,
        6: 6,
        7: 7,
        8: 8,
        9: 9,
        '.': 10
      };
      var _profileInfo = {
        fps: {
          desc: "Framerate (FPS)",
          below: 30,
          average: _average,
          isInteger: true
        },
        draws: {
          desc: 'Draw call',
          isInteger: true
        },
        frame: {
          desc: 'Frame time (ms)',
          min: 0,
          max: 50,
          average: _average
        },
        instances: {
          desc: 'Instance Count',
          isInteger: true
        },
        tricount: {
          desc: 'Triangle',
          isInteger: true
        },
        logic: {
          desc: 'Game Logic (ms)',
          min: 0,
          max: 50,
          average: _average,
          color: '#080'
        },
        physics: {
          desc: 'Physics (ms)',
          min: 0,
          max: 50,
          average: _average
        },
        render: {
          desc: 'Renderer (ms)',
          min: 0,
          max: 50,
          average: _average,
          color: '#f90'
        },
        present: {
          desc: 'Present (ms)',
          min: 0,
          max: 50,
          average: _average,
          color: '#f90'
        },
        textureMemory: {
          desc: 'GFX Texture Mem(M)'
        },
        bufferMemory: {
          desc: 'GFX Buffer Mem(M)'
        }
      };
      var _constants = {
        fontSize: 23,
        quadHeight: 0.4,
        segmentsPerLine: 8,
        textureWidth: 280,
        textureHeight: 280
      };
      var Profiler = exports('f9', function (_System) {
        _inheritsLoose(Profiler, _System);
        function Profiler() {
          var _this;
          _this = _System.call(this) || this;
          _this._profilerStats = null;
          _this._showFPS = false;
          _this._rootNode = null;
          _this._device = null;
          _this._swapchain = null;
          _this._meshRenderer = null;
          _this._canvas = null;
          _this._ctx = null;
          _this._texture = null;
          _this._region = new BufferTextureCopy();
          _this._canvasArr = [];
          _this._regionArr = [_this._region];
          _this.digitsData = null;
          _this.offsetData = null;
          _this.pass = null;
          _this._canvasDone = false;
          _this._statsDone = false;
          _this._inited = false;
          _this._lineHeight = _constants.textureHeight / (Object.keys(_profileInfo).length + 1);
          _this._wordHeight = 0;
          _this._eachNumWidth = 0;
          _this._totalLines = 0;
          _this.lastTime = 0;
          {
            _this._canvas = ccwindow.document.createElement('canvas');
            _this._ctx = _this._canvas.getContext('2d');
            _this._canvasArr.push(_this._canvas);
          }
          return _this;
        }
        var _proto = Profiler.prototype;
        _proto.init = function init() {
          var showFPS = !!settings.querySettings(Settings.Category.PROFILING, 'showFPS');
          if (showFPS) {
            this.showStats();
          } else {
            this.hideStats();
          }
        };
        _proto.isShowingStats = function isShowingStats() {
          return this._showFPS;
        };
        _proto.hideStats = function hideStats() {
          if (this._showFPS) {
            if (this._rootNode) {
              this._rootNode.active = false;
            }
            legacyCC.director.off(legacyCC.Director.EVENT_BEFORE_UPDATE, this.beforeUpdate, this);
            legacyCC.director.off(legacyCC.Director.EVENT_AFTER_UPDATE, this.afterUpdate, this);
            legacyCC.director.off(legacyCC.Director.EVENT_BEFORE_PHYSICS, this.beforePhysics, this);
            legacyCC.director.off(legacyCC.Director.EVENT_AFTER_PHYSICS, this.afterPhysics, this);
            legacyCC.director.off(legacyCC.Director.EVENT_BEFORE_DRAW, this.beforeDraw, this);
            legacyCC.director.off(legacyCC.Director.EVENT_AFTER_RENDER, this.afterRender, this);
            legacyCC.director.off(legacyCC.Director.EVENT_AFTER_DRAW, this.afterPresent, this);
            this._showFPS = false;
            director.root.pipeline.profiler = null;
            legacyCC.game.config.showFPS = false;
          }
        };
        _proto.showStats = function showStats() {
          if (!this._showFPS) {
            if (!this._device) {
              var root = legacyCC.director.root;
              this._device = deviceManager.gfxDevice;
              this._swapchain = root.mainWindow.swapchain;
            }
            this.generateCanvas();
            this.generateStats();
            legacyCC.game.once(legacyCC.Game.EVENT_ENGINE_INITED, this.generateNode, this);
            legacyCC.game.on(legacyCC.Game.EVENT_RESTART, this.generateNode, this);
            if (this._rootNode) {
              this._rootNode.active = true;
            }
            legacyCC.director.on(legacyCC.Director.EVENT_BEFORE_UPDATE, this.beforeUpdate, this);
            legacyCC.director.on(legacyCC.Director.EVENT_AFTER_UPDATE, this.afterUpdate, this);
            legacyCC.director.on(legacyCC.Director.EVENT_BEFORE_PHYSICS, this.beforePhysics, this);
            legacyCC.director.on(legacyCC.Director.EVENT_AFTER_PHYSICS, this.afterPhysics, this);
            legacyCC.director.on(legacyCC.Director.EVENT_BEFORE_DRAW, this.beforeDraw, this);
            legacyCC.director.on(legacyCC.Director.EVENT_AFTER_RENDER, this.afterRender, this);
            legacyCC.director.on(legacyCC.Director.EVENT_AFTER_DRAW, this.afterPresent, this);
            this._showFPS = true;
            this._canvasDone = true;
            this._statsDone = true;
            legacyCC.game.config.showFPS = true;
          }
        };
        _proto.generateCanvas = function generateCanvas() {
          if (this._canvasDone) {
            return;
          }
          var textureWidth = _constants.textureWidth,
            textureHeight = _constants.textureHeight;
          if (!this._ctx || !this._canvas) {
            return;
          }
          this._canvas.width = textureWidth;
          this._canvas.height = textureHeight;
          this._canvas.style.width = "" + this._canvas.width;
          this._canvas.style.height = "" + this._canvas.height;
          this._ctx.font = _constants.fontSize + "px Arial";
          this._ctx.textBaseline = 'top';
          this._ctx.fillStyle = '#fff';
          this._texture = this._device.createTexture(new TextureInfo(TextureType.TEX2D, TextureUsageBit.SAMPLED | TextureUsageBit.TRANSFER_DST, Format.RGBA8, textureWidth, textureHeight));
          this._region.texExtent.width = textureWidth;
          this._region.texExtent.height = textureHeight;
        };
        _proto.generateStats = function generateStats() {
          if (this._statsDone || !this._ctx || !this._canvas) {
            return;
          }
          this._profilerStats = null;
          var now = performance.now();
          this._ctx.textAlign = 'left';
          var i = 0;
          for (var id in _profileInfo) {
            var element = _profileInfo[id];
            this._ctx.fillText(element.desc, 0, i * this._lineHeight);
            element.counter = new PerfCounter(id, element, now);
            i++;
          }
          this._totalLines = i;
          this._wordHeight = this._totalLines * this._lineHeight / this._canvas.height;
          for (var j = 0; j < _characters.length; ++j) {
            var offset = this._ctx.measureText(_characters[j]).width;
            this._eachNumWidth = Math.max(this._eachNumWidth, offset);
          }
          for (var _j = 0; _j < _characters.length; ++_j) {
            this._ctx.fillText(_characters[_j], _j * this._eachNumWidth, this._totalLines * this._lineHeight);
          }
          this._eachNumWidth /= this._canvas.width;
          this._profilerStats = _profileInfo;
          this._canvasArr[0] = this._canvas;
          this._device.copyTexImagesToTexture(this._canvasArr, this._texture, this._regionArr);
        };
        _proto.generateNode = function generateNode() {
          if (this._rootNode && this._rootNode.isValid) {
            return;
          }
          this._rootNode = new Node$1('PROFILER_NODE');
          this._rootNode._objFlags = legacyCC.Object.Flags.DontSave | legacyCC.Object.Flags.HideInHierarchy;
          legacyCC.game.addPersistRootNode(this._rootNode);
          var managerNode = new Node$1('Profiler_Root');
          managerNode.parent = this._rootNode;
          var height = _constants.quadHeight;
          var rowHeight = height / this._totalLines;
          var lWidth = height / this._wordHeight;
          var scale = rowHeight / _constants.fontSize;
          var columnWidth = this._eachNumWidth * this._canvas.width * scale;
          var vertexPos = [0, height, 0, lWidth, height, 0, lWidth, 0, 0, 0, 0, 0];
          var vertexindices = [0, 2, 1, 0, 3, 2];
          var vertexUV = [0, 0, -1, 0, 1, 0, -1, 0, 1, this._wordHeight, -1, 0, 0, this._wordHeight, -1, 0];
          var offset = 0;
          for (var i = 0; i < this._totalLines; i++) {
            for (var j = 0; j < _constants.segmentsPerLine; j++) {
              vertexPos.push(lWidth + j * columnWidth, height - i * rowHeight, 0);
              vertexPos.push(lWidth + (j + 1) * columnWidth, height - i * rowHeight, 0);
              vertexPos.push(lWidth + (j + 1) * columnWidth, height - (i + 1) * rowHeight, 0);
              vertexPos.push(lWidth + j * columnWidth, height - (i + 1) * rowHeight, 0);
              offset = (i * _constants.segmentsPerLine + j + 1) * 4;
              vertexindices.push(0 + offset, 2 + offset, 1 + offset, 0 + offset, 3 + offset, 2 + offset);
              var idx = i * _constants.segmentsPerLine + j;
              var z = Math.floor(idx / 4);
              var w = idx - z * 4;
              vertexUV.push(0, this._wordHeight, z, w);
              vertexUV.push(this._eachNumWidth, this._wordHeight, z, w);
              vertexUV.push(this._eachNumWidth, 1, z, w);
              vertexUV.push(0, 1, z, w);
            }
          }
          this._meshRenderer = managerNode.addComponent(MeshRenderer);
          this._meshRenderer.mesh = _createMesh({
            positions: vertexPos,
            indices: vertexindices,
            colors: vertexUV
          });
          var _material = new Material();
          _material.initialize({
            effectName: 'util/profiler'
          });
          var pass = this.pass = _material.passes[0];
          var hTexture = pass.getBinding('mainTexture');
          var bDigits = pass.getBinding('digits');
          var bOffset = pass.getBinding('offset');
          pass.bindTexture(hTexture, this._texture);
          this.digitsData = pass.blocks[bDigits];
          this.offsetData = pass.blocks[bOffset];
          this.offsetData[3] = -1;
          this._meshRenderer.material = _material;
          this._meshRenderer.node.layer = Layers.Enum.PROFILER;
          this._inited = true;
        };
        _proto.beforeUpdate = function beforeUpdate() {
          if (!this._profilerStats) {
            return;
          }
          var now = performance.now();
          this._profilerStats.frame.counter.start(now);
          this._profilerStats.logic.counter.start(now);
        };
        _proto.afterUpdate = function afterUpdate() {
          if (!this._profilerStats) {
            return;
          }
          var now = performance.now();
          if (legacyCC.director.isPaused()) {
            this._profilerStats.frame.counter.start(now);
          } else {
            this._profilerStats.logic.counter.end(now);
          }
        };
        _proto.beforePhysics = function beforePhysics() {
          if (!this._profilerStats) {
            return;
          }
          var now = performance.now();
          this._profilerStats.physics.counter.start(now);
        };
        _proto.afterPhysics = function afterPhysics() {
          if (!this._profilerStats) {
            return;
          }
          var now = performance.now();
          this._profilerStats.physics.counter.end(now);
        };
        _proto.beforeDraw = function beforeDraw() {
          if (!this._profilerStats || !this._inited) {
            return;
          }
          var surfaceTransform = this._swapchain.surfaceTransform;
          var clipSpaceSignY = this._device.capabilities.clipSpaceSignY;
          if (surfaceTransform !== this.offsetData[3]) {
            var preTransform = preTransforms[surfaceTransform];
            var x = -0.9;
            var y = -0.9 * clipSpaceSignY;
            if (sys.isXR) {
              x = -0.5;
              y = -0.5 * clipSpaceSignY;
            }
            this.offsetData[0] = x * preTransform[0] + y * preTransform[2];
            this.offsetData[1] = x * preTransform[1] + y * preTransform[3];
            this.offsetData[2] = this._eachNumWidth;
            this.offsetData[3] = surfaceTransform;
          }
          this.pass.setRootBufferDirty(true);
          if (this._meshRenderer.model) {
            director.root.pipeline.profiler = this._meshRenderer.model;
          } else {
            director.root.pipeline.profiler = null;
          }
          var now = performance.now();
          this._profilerStats.render.counter.start(now);
        };
        _proto.afterRender = function afterRender() {
          if (!this._profilerStats || !this._inited) {
            return;
          }
          var now = performance.now();
          this._profilerStats.render.counter.end(now);
          this._profilerStats.present.counter.start(now);
        };
        _proto.afterPresent = function afterPresent() {
          if (!this._profilerStats || !this._inited) {
            return;
          }
          var now = performance.now();
          this._profilerStats.frame.counter.end(now);
          this._profilerStats.fps.counter.frame(now);
          this._profilerStats.present.counter.end(now);
          if (now - this.lastTime < _average) {
            return;
          }
          this.lastTime = now;
          var device = this._device;
          this._profilerStats.draws.counter.value = device.numDrawCalls;
          this._profilerStats.instances.counter.value = device.numInstances;
          this._profilerStats.bufferMemory.counter.value = device.memoryStatus.bufferSize / (1024 * 1024);
          this._profilerStats.textureMemory.counter.value = device.memoryStatus.textureSize / (1024 * 1024);
          this._profilerStats.tricount.counter.value = device.numTris;
          var i = 0;
          var view = this.digitsData;
          for (var id in this._profilerStats) {
            var stat = this._profilerStats[id];
            stat.counter.sample(now);
            var result = stat.counter.human().toString();
            for (var j = _constants.segmentsPerLine - 1; j >= 0; j--) {
              var index = i * _constants.segmentsPerLine + j;
              var character = result[result.length - (_constants.segmentsPerLine - j)];
              var offset = _string2offset[character];
              if (offset === undefined) {
                offset = 11;
              }
              view[index] = offset;
            }
            i++;
          }
        };
        _createClass(Profiler, [{
          key: "_stats",
          get: function get() {
            warn('Profiler._stats is deprecated, please use Profiler.stats instead.');
            return this._profilerStats;
          }
        }, {
          key: "stats",
          get: function get() {
            return this._profilerStats;
          }
        }]);
        return Profiler;
      }(System));
      var profiler = exports('fa', new Profiler());
      director.registerSystem('profiler', profiler, 0);
      legacyCC.profiler = profiler;

      var DataPoolManager = function () {
        function DataPoolManager(device) {
          this.jointTexturePool = void 0;
          this.jointAnimationInfo = void 0;
          this.jointTexturePool = new JointTexturePool(device);
          this.jointAnimationInfo = new JointAnimationInfo(device);
        }
        var _proto = DataPoolManager.prototype;
        _proto.releaseSkeleton = function releaseSkeleton(skeleton) {
          this.jointTexturePool.releaseSkeleton(skeleton);
        };
        _proto.releaseAnimationClip = function releaseAnimationClip(clip) {
          this.jointTexturePool.releaseAnimationClip(clip);
        };
        _proto.clear = function clear() {
          this.jointTexturePool.clear();
          this.jointAnimationInfo.clear();
        };
        return DataPoolManager;
      }();
      legacyCC.internal.DataPoolManager = DataPoolManager;

      var m4_1$1 = new Mat4();
      var m4_2$1 = new Mat4();
      var SkeletalAnimationState = exports('fc', function (_AnimationState) {
        _inheritsLoose(SkeletalAnimationState, _AnimationState);
        function SkeletalAnimationState(clip, name) {
          var _this;
          if (name === void 0) {
            name = '';
          }
          _this = _AnimationState.call(this, clip, name) || this;
          _this._frames = 1;
          _this._bakedDuration = 0;
          _this._animInfo = null;
          _this._sockets = [];
          _this._animInfoMgr = void 0;
          _this._parent = null;
          _this._curvesInited = false;
          _this._animInfoMgr = legacyCC.director.root.dataPoolManager.jointAnimationInfo;
          return _this;
        }
        var _proto = SkeletalAnimationState.prototype;
        _proto.initialize = function initialize(root) {
          if (this._curveLoaded) {
            return;
          }
          this._parent = root.getComponent('cc.SkeletalAnimation');
          var baked = this._parent.useBakedAnimation;
          this._doNotCreateEval = baked;
          _AnimationState.prototype.initialize.call(this, root);
          this._curvesInited = !baked;
          var _SkelAnimDataHub$getO = SkelAnimDataHub.getOrExtract(this.clip),
            frames = _SkelAnimDataHub$getO.frames,
            samples = _SkelAnimDataHub$getO.samples;
          this._frames = frames - 1;
          this._animInfo = this._animInfoMgr.getData(root.uuid);
          this._bakedDuration = this._frames / samples;
          this.setUseBaked(baked);
        };
        _proto.onPlay = function onPlay() {
          var _this2 = this;
          _AnimationState.prototype.onPlay.call(this);
          var baked = this._parent.useBakedAnimation;
          if (baked) {
            this._animInfoMgr.switchClip(this._animInfo, this.clip);
            var users = this._parent.getUsers();
            users.forEach(function (user) {
              user.uploadAnimation(_this2.clip);
            });
          }
        };
        _proto.setUseBaked = function setUseBaked(useBaked) {
          if (useBaked) {
            this._sampleCurves = this._sampleCurvesBaked;
            this.duration = this._bakedDuration;
          } else {
            this._sampleCurves = _AnimationState.prototype._sampleCurves;
            this.duration = this.clip.duration;
            if (!this._curvesInited) {
              this._curveLoaded = false;
              _AnimationState.prototype.initialize.call(this, this._targetNode);
              this._curvesInited = true;
            }
          }
        };
        _proto.rebuildSocketCurves = function rebuildSocketCurves(sockets) {
          this._sockets.length = 0;
          if (!this._targetNode) {
            return;
          }
          var root = this._targetNode;
          for (var i = 0; i < sockets.length; ++i) {
            var socket = sockets[i];
            var targetNode = root.getChildByPath(socket.path);
            if (!socket.target) {
              continue;
            }
            var clipData = SkelAnimDataHub.getOrExtract(this.clip);
            var animPath = socket.path;
            var source = clipData.joints[animPath];
            var animNode = targetNode;
            var downstream = void 0;
            while (!source) {
              var idx = animPath.lastIndexOf('/');
              animPath = animPath.substring(0, idx);
              source = clipData.joints[animPath];
              if (animNode) {
                if (!downstream) {
                  downstream = Mat4.identity(m4_2$1);
                }
                Mat4.fromRTS(m4_1$1, animNode.rotation, animNode.position, animNode.scale);
                Mat4.multiply(downstream, m4_1$1, downstream);
                animNode = animNode.parent;
              }
              if (idx < 0) {
                break;
              }
            }
            var curveData = source && source.transforms;
            var frames = clipData.frames;
            var transforms = [];
            for (var f = 0; f < frames; f++) {
              var mat = void 0;
              if (curveData && downstream) {
                mat = Mat4.multiply(m4_1$1, curveData[f], downstream);
              } else if (curveData) {
                mat = curveData[f];
              } else if (downstream) {
                mat = downstream;
              } else {
                mat = new Mat4();
              }
              var tfm = {
                pos: new Vec3(),
                rot: new Quat(),
                scale: new Vec3()
              };
              Mat4.toRTS(mat, tfm.rot, tfm.pos, tfm.scale);
              transforms.push(tfm);
            }
            this._sockets.push({
              target: socket.target,
              frames: transforms
            });
          }
        };
        _proto._sampleCurvesBaked = function _sampleCurvesBaked(time) {
          var ratio = time / this.duration;
          var info = this._animInfo;
          var clip = this.clip;
          if (info.currentClip !== clip) {
            this._animInfoMgr.switchClip(this._animInfo, clip);
            var users = this._parent.getUsers();
            users.forEach(function (user) {
              user.uploadAnimation(clip);
            });
            info.data[0] = -1;
          }
          var curFrame = ratio * this._frames + 0.5 | 0;
          if (curFrame === info.data[0]) {
            return;
          }
          info.data[0] = curFrame;
          info.dirty = true;
          for (var i = 0; i < this._sockets.length; ++i) {
            var _this$_sockets$i = this._sockets[i],
              target = _this$_sockets$i.target,
              frames = _this$_sockets$i.frames;
            var _frames$curFrame = frames[curFrame],
              pos = _frames$curFrame.pos,
              rot = _frames$curFrame.rot,
              scale = _frames$curFrame.scale;
            target.setRTS(rot, pos, scale);
          }
        };
        return SkeletalAnimationState;
      }(AnimationState));

      var _dec$h, _dec2$g, _class$h, _class2$f, _initializer$e, _initializer2$e, _dec3$f, _dec4$c, _dec5$c, _dec6$6, _class4, _class5$1, _initializer3$c, _initializer4$b, _class6;
      var Socket = exports('fd', (_dec$h = ccclass$n('cc.SkeletalAnimation.Socket'), _dec2$g = type$7(Node$1), _dec$h(_class$h = (_class2$f = function Socket(path, target) {
        if (path === void 0) {
          path = '';
        }
        if (target === void 0) {
          target = null;
        }
        this.path = _initializer$e && _initializer$e();
        this.target = _initializer2$e && _initializer2$e();
        this.path = path;
        this.target = target;
      }, (_initializer$e = applyDecoratedInitializer(_class2$f.prototype, "path", [serializable$j], function () {
        return '';
      }), _initializer2$e = applyDecoratedInitializer(_class2$f.prototype, "target", [_dec2$g], function () {
        return null;
      })), _class2$f)) || _class$h));
      setClassAlias(Socket, 'cc.SkeletalAnimationComponent.Socket');
      var m4_1 = new Mat4();
      var m4_2 = new Mat4();
      function collectRecursively(node, prefix, out) {
        if (prefix === void 0) {
          prefix = '';
        }
        if (out === void 0) {
          out = [];
        }
        for (var i = 0; i < node.children.length; i++) {
          var child = node.children[i];
          if (!child) {
            continue;
          }
          var path = prefix ? prefix + "/" + child.name : child.name;
          out.push(path);
          collectRecursively(child, path, out);
        }
        return out;
      }
      var SkeletalAnimation = exports('fe', (_dec3$f = ccclass$n('cc.SkeletalAnimation'), _dec4$c = executionOrder$1(99), _dec5$c = type$7([Socket]), _dec6$6 = type$7([Socket]), _dec3$f(_class4 = _dec4$c(_class4 = (_class5$1 = (_class6 = function (_Animation) {
        _inheritsLoose(SkeletalAnimation, _Animation);
        function SkeletalAnimation() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Animation.call.apply(_Animation, [this].concat(args)) || this;
          _this._useBakedAnimation = _initializer3$c && _initializer3$c();
          _this._sockets = _initializer4$b && _initializer4$b();
          _this._users = new Set();
          _this._currentBakedState = null;
          return _this;
        }
        var _proto = SkeletalAnimation.prototype;
        _proto.onLoad = function onLoad() {
          _Animation.prototype.onLoad.call(this);
          var comps = this.node.getComponentsInChildren(SkinnedMeshRenderer);
          for (var i = 0; i < comps.length; ++i) {
            var comp = comps[i];
            if (comp.skinningRoot === this.node) {
              this.notifySkinnedMeshAdded(comp);
            }
          }
        };
        _proto.onDestroy = function onDestroy() {
          _Animation.prototype.onDestroy.call(this);
          legacyCC.director.root.dataPoolManager.jointAnimationInfo.destroy(this.node.uuid);
          getGlobalAnimationManager().removeSockets(this.node, this._sockets);
          this._removeAllUsers();
        };
        _proto.onEnable = function onEnable() {
          var _this$_currentBakedSt;
          _Animation.prototype.onEnable.call(this);
          (_this$_currentBakedSt = this._currentBakedState) === null || _this$_currentBakedSt === void 0 ? void 0 : _this$_currentBakedSt.resume();
        };
        _proto.onDisable = function onDisable() {
          var _this$_currentBakedSt2;
          _Animation.prototype.onDisable.call(this);
          (_this$_currentBakedSt2 = this._currentBakedState) === null || _this$_currentBakedSt2 === void 0 ? void 0 : _this$_currentBakedSt2.pause();
        };
        _proto.start = function start() {
          this.sockets = this._sockets;
          this._applyBakeFlagChange();
          _Animation.prototype.start.call(this);
        };
        _proto.pause = function pause() {
          if (!this._useBakedEffectively) {
            _Animation.prototype.pause.call(this);
          } else {
            var _this$_currentBakedSt3;
            (_this$_currentBakedSt3 = this._currentBakedState) === null || _this$_currentBakedSt3 === void 0 ? void 0 : _this$_currentBakedSt3.pause();
          }
        };
        _proto.resume = function resume() {
          if (!this._useBakedEffectively) {
            _Animation.prototype.resume.call(this);
          } else {
            var _this$_currentBakedSt4;
            (_this$_currentBakedSt4 = this._currentBakedState) === null || _this$_currentBakedSt4 === void 0 ? void 0 : _this$_currentBakedSt4.resume();
          }
        };
        _proto.stop = function stop() {
          if (!this._useBakedEffectively) {
            _Animation.prototype.stop.call(this);
          } else if (this._currentBakedState) {
            this._currentBakedState.stop();
            this._currentBakedState = null;
          }
        };
        _proto.querySockets = function querySockets() {
          var animPaths = this._defaultClip && Object.keys(SkelAnimDataHub.getOrExtract(this._defaultClip).joints).sort().reduce(function (acc, cur) {
            return cur.startsWith(acc[acc.length - 1] + "/") ? acc : (acc.push(cur), acc);
          }, []) || [];
          if (!animPaths.length) {
            return ['please specify a valid default animation clip first'];
          }
          var out = [];
          for (var i = 0; i < animPaths.length; i++) {
            var path = animPaths[i];
            var node = this.node.getChildByPath(path);
            if (!node) {
              continue;
            }
            out.push(path);
            collectRecursively(node, path, out);
          }
          return out;
        };
        _proto.rebuildSocketAnimations = function rebuildSocketAnimations() {
          for (var _iterator = _createForOfIteratorHelperLoose(this._sockets), _step; !(_step = _iterator()).done;) {
            var socket = _step.value;
            var joint = this.node.getChildByPath(socket.path);
            var target = socket.target;
            if (joint && target) {
              target.name = socket.path.substring(socket.path.lastIndexOf('/') + 1) + " Socket";
              target.parent = this.node;
              getWorldTransformUntilRoot(joint, this.node, m4_1);
              Mat4.fromRTS(m4_2, target.rotation, target.position, target.scale);
              if (!Mat4.equals(m4_2, m4_1)) {
                target.matrix = m4_1;
              }
            }
          }
          for (var _i = 0, _Object$keys = Object.keys(this._nameToState); _i < _Object$keys.length; _i++) {
            var stateName = _Object$keys[_i];
            var state = this._nameToState[stateName];
            state.rebuildSocketCurves(this._sockets);
          }
        };
        _proto.createSocket = function createSocket(path) {
          var socket = this._sockets.find(function (s) {
            return s.path === path;
          });
          if (socket) {
            return socket.target;
          }
          var joint = this.node.getChildByPath(path);
          if (!joint) {
            warn('illegal socket path');
            return null;
          }
          var target = new Node$1();
          target.parent = this.node;
          this._sockets.push(new Socket(path, target));
          this.rebuildSocketAnimations();
          return target;
        };
        _proto.notifySkinnedMeshAdded = function notifySkinnedMeshAdded(skinnedMeshRenderer) {
          var _useBakedEffectively = this._useBakedEffectively;
          var formerBound = skinnedMeshRenderer.associatedAnimation;
          if (formerBound) {
            formerBound._users["delete"](skinnedMeshRenderer);
          }
          skinnedMeshRenderer.associatedAnimation = this;
          skinnedMeshRenderer.setUseBakedAnimation(_useBakedEffectively, true);
          if (_useBakedEffectively) {
            var playingState = this._currentBakedState;
            if (playingState) {
              skinnedMeshRenderer.uploadAnimation(playingState.clip);
            }
          }
          this._users.add(skinnedMeshRenderer);
        };
        _proto.notifySkinnedMeshRemoved = function notifySkinnedMeshRemoved(skinnedMeshRenderer) {
          assertIsTrue(skinnedMeshRenderer.associatedAnimation === this || skinnedMeshRenderer.associatedAnimation === null);
          skinnedMeshRenderer.setUseBakedAnimation(false);
          skinnedMeshRenderer.associatedAnimation = null;
          this._users["delete"](skinnedMeshRenderer);
        };
        _proto.getUsers = function getUsers() {
          return this._users;
        };
        _proto._createState = function _createState(clip, name) {
          return new SkeletalAnimationState(clip, name);
        };
        _proto._doCreateState = function _doCreateState(clip, name) {
          var state = _Animation.prototype._doCreateState.call(this, clip, name);
          state.rebuildSocketCurves(this._sockets);
          return state;
        };
        _proto.doPlayOrCrossFade = function doPlayOrCrossFade(state, duration) {
          if (this._useBakedEffectively) {
            if (this._currentBakedState) {
              this._currentBakedState.stop();
            }
            var skeletalAnimationState = state;
            this._currentBakedState = skeletalAnimationState;
            skeletalAnimationState.play();
          } else {
            _Animation.prototype.doPlayOrCrossFade.call(this, state, duration);
          }
        };
        _proto._removeAllUsers = function _removeAllUsers() {
          var _this2 = this;
          Array.from(this._users).forEach(function (user) {
            _this2.notifySkinnedMeshRemoved(user);
          });
        };
        _proto._applyBakeFlagChange = function _applyBakeFlagChange() {
          var useBakedEffectively = this._useBakedEffectively;
          for (var stateName in this._nameToState) {
            var state = this._nameToState[stateName];
            state.setUseBaked(useBakedEffectively);
          }
          this._users.forEach(function (user) {
            user.setUseBakedAnimation(useBakedEffectively);
          });
          if (useBakedEffectively) {
            getGlobalAnimationManager().removeSockets(this.node, this._sockets);
          } else {
            getGlobalAnimationManager().addSockets(this.node, this._sockets);
            this._currentBakedState = null;
          }
        };
        _createClass(SkeletalAnimation, [{
          key: "sockets",
          get: function get() {
            return this._sockets;
          },
          set: function set(val) {
            if (!this._useBakedEffectively) {
              var animMgr = getGlobalAnimationManager();
              animMgr.removeSockets(this.node, this._sockets);
              animMgr.addSockets(this.node, val);
            }
            this._sockets = val;
            this.rebuildSocketAnimations();
          }
        }, {
          key: "useBakedAnimation",
          get: function get() {
            return this._useBakedAnimation;
          },
          set: function set(value) {
            this._useBakedAnimation = value;
            this._applyBakeFlagChange();
          }
        }, {
          key: "_useBakedEffectively",
          get: function get() {
            {
              return this._useBakedAnimation;
            }
          }
        }]);
        return SkeletalAnimation;
      }(Animation), _class6.Socket = Socket, _class6), (_applyDecoratedDescriptor(_class5$1.prototype, "sockets", [_dec5$c], Object.getOwnPropertyDescriptor(_class5$1.prototype, "sockets"), _class5$1.prototype), _initializer3$c = applyDecoratedInitializer(_class5$1.prototype, "_useBakedAnimation", [serializable$j], function () {
        return true;
      }), _initializer4$b = applyDecoratedInitializer(_class5$1.prototype, "_sockets", [_dec6$6], function () {
        return [];
      })), _class5$1)) || _class4) || _class4));

      var Action = function () {
        function Action() {
          this.originalTarget = null;
          this.target = null;
          this.tag = Action.TAG_INVALID;
        }
        var _proto = Action.prototype;
        _proto.clone = function clone() {
          var action = new Action();
          action.originalTarget = null;
          action.target = null;
          action.tag = this.tag;
          return action;
        };
        _proto.isDone = function isDone() {
          return true;
        };
        _proto.startWithTarget = function startWithTarget(target) {
          this.originalTarget = target;
          this.target = target;
        };
        _proto.stop = function stop() {
          this.target = null;
        };
        _proto.step = function step(dt) {
          logID(1006);
        };
        _proto.update = function update(dt) {
          logID(1007);
        };
        _proto.getTarget = function getTarget() {
          return this.target;
        };
        _proto.setTarget = function setTarget(target) {
          this.target = target;
        };
        _proto.getOriginalTarget = function getOriginalTarget() {
          return this.originalTarget;
        };
        _proto.setOriginalTarget = function setOriginalTarget(originalTarget) {
          this.originalTarget = originalTarget;
        };
        _proto.getTag = function getTag() {
          return this.tag;
        };
        _proto.setTag = function setTag(tag) {
          this.tag = tag;
        };
        _proto.reverse = function reverse() {
          logID(1008);
          return null;
        };
        _proto.retain = function retain() {};
        _proto.release = function release() {};
        return Action;
      }();
      Action.TAG_INVALID = -1;
      var FiniteTimeAction = function (_Action) {
        _inheritsLoose(FiniteTimeAction, _Action);
        function FiniteTimeAction() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Action.call.apply(_Action, [this].concat(args)) || this;
          _this._duration = 0;
          _this._timesForRepeat = 1;
          return _this;
        }
        var _proto2 = FiniteTimeAction.prototype;
        _proto2.getDuration = function getDuration() {
          return this._duration * (this._timesForRepeat || 1);
        };
        _proto2.setDuration = function setDuration(duration) {
          this._duration = duration;
        };
        _proto2.clone = function clone() {
          return new FiniteTimeAction();
        };
        return FiniteTimeAction;
      }(Action);
      (function (_Action2) {
        _inheritsLoose(Speed, _Action2);
        function Speed(action, speed) {
          var _this2;
          if (speed === void 0) {
            speed = 1;
          }
          _this2 = _Action2.call(this) || this;
          _this2._speed = 0;
          _this2._innerAction = null;
          action && _this2.initWithAction(action, speed);
          return _this2;
        }
        var _proto3 = Speed.prototype;
        _proto3.getSpeed = function getSpeed() {
          return this._speed;
        };
        _proto3.setSpeed = function setSpeed(speed) {
          this._speed = speed;
        };
        _proto3.initWithAction = function initWithAction(action, speed) {
          if (!action) {
            errorID(1021);
            return false;
          }
          this._innerAction = action;
          this._speed = speed;
          return true;
        };
        _proto3.clone = function clone() {
          var action = new Speed();
          action.initWithAction(this._innerAction.clone(), this._speed);
          return action;
        };
        _proto3.startWithTarget = function startWithTarget(target) {
          Action.prototype.startWithTarget.call(this, target);
          this._innerAction.startWithTarget(target);
        };
        _proto3.stop = function stop() {
          this._innerAction.stop();
          Action.prototype.stop.call(this);
        };
        _proto3.step = function step(dt) {
          this._innerAction.step(dt * this._speed);
        };
        _proto3.isDone = function isDone() {
          return this._innerAction.isDone();
        };
        _proto3.reverse = function reverse() {
          return new Speed(this._innerAction.reverse(), this._speed);
        };
        _proto3.setInnerAction = function setInnerAction(action) {
          if (this._innerAction !== action) {
            this._innerAction = action;
          }
        };
        _proto3.getInnerAction = function getInnerAction() {
          return this._innerAction;
        };
        return Speed;
      })(Action);

      var ID_COUNTER = 0;
      var HashElement = function HashElement() {
        this.actions = [];
        this.target = null;
        this.actionIndex = 0;
        this.currentAction = null;
        this.paused = false;
        this.lock = false;
      };
      var ActionManager = function () {
        function ActionManager() {
          this._hashTargets = new Map();
          this._arrayTargets = [];
          this._currentTarget = void 0;
          this._elementPool = [];
        }
        var _proto = ActionManager.prototype;
        _proto._searchElementByTarget = function _searchElementByTarget(arr, target) {
          for (var k = 0; k < arr.length; k++) {
            if (target === arr[k].target) return arr[k];
          }
          return null;
        };
        _proto._getElement = function _getElement(target, paused) {
          var element = this._elementPool.pop();
          if (!element) {
            element = new HashElement();
          }
          element.target = target;
          element.paused = !!paused;
          return element;
        };
        _proto._putElement = function _putElement(element) {
          element.actions.length = 0;
          element.actionIndex = 0;
          element.currentAction = null;
          element.paused = false;
          element.target = null;
          element.lock = false;
          this._elementPool.push(element);
        };
        _proto.addAction = function addAction(action, target, paused) {
          if (!action || !target) {
            errorID(1000);
            return;
          }
          if (target.uuid == null) {
            target.uuid = "_TWEEN_UUID_" + ID_COUNTER++;
          }
          var element = this._hashTargets.get(target);
          if (!element) {
            element = this._getElement(target, paused);
            this._hashTargets.set(target, element);
            this._arrayTargets.push(element);
          } else if (!element.actions) {
            element.actions = [];
          }
          element.target = target;
          element.actions.push(action);
          action.startWithTarget(target);
        };
        _proto.removeAllActions = function removeAllActions() {
          var locTargets = this._arrayTargets;
          for (var i = 0; i < locTargets.length; i++) {
            var element = locTargets[i];
            if (element) this._putElement(element);
          }
          this._arrayTargets.length = 0;
          this._hashTargets = new Map();
        };
        _proto.removeAllActionsFromTarget = function removeAllActionsFromTarget(target) {
          if (target == null) return;
          var element = this._hashTargets.get(target);
          if (element) {
            element.actions.length = 0;
            this._deleteHashElement(element);
          }
        };
        _proto.removeAction = function removeAction(action) {
          if (action == null) return;
          var target = action.getOriginalTarget();
          var element = this._hashTargets.get(target);
          if (element) {
            for (var i = 0; i < element.actions.length; i++) {
              if (element.actions[i] === action) {
                element.actions.splice(i, 1);
                if (element.actionIndex >= i) element.actionIndex--;
                break;
              }
            }
          }
        };
        _proto._removeActionByTag = function _removeActionByTag(tag, element, target) {
          for (var i = 0, l = element.actions.length; i < l; ++i) {
            var action = element.actions[i];
            if (action && action.getTag() === tag) {
              if (target && action.getOriginalTarget() !== target) {
                continue;
              }
              this._removeActionAtIndex(i, element);
              break;
            }
          }
        };
        _proto._removeAllActionsByTag = function _removeAllActionsByTag(tag, element, target) {
          for (var i = element.actions.length - 1; i >= 0; --i) {
            var action = element.actions[i];
            if (action && action.getTag() === tag) {
              if (target && action.getOriginalTarget() !== target) {
                continue;
              }
              this._removeActionAtIndex(i, element);
            }
          }
        };
        _proto.removeActionByTag = function removeActionByTag(tag, target) {
          var _this = this;
          if (tag === Action.TAG_INVALID) logID(1002);
          var hashTargets = this._hashTargets;
          if (target) {
            var element = hashTargets.get(target);
            if (element) {
              this._removeActionByTag(tag, element, target);
            }
          } else {
            hashTargets.forEach(function (element) {
              _this._removeActionByTag(tag, element);
            });
          }
        };
        _proto.removeAllActionsByTag = function removeAllActionsByTag(tag, target) {
          var _this2 = this;
          if (tag === Action.TAG_INVALID) logID(1002);
          var hashTargets = this._hashTargets;
          if (target) {
            var element = hashTargets.get(target);
            if (element) {
              this._removeAllActionsByTag(tag, element, target);
            }
          } else {
            hashTargets.forEach(function (element) {
              _this2._removeAllActionsByTag(tag, element);
            });
          }
        };
        _proto.getActionByTag = function getActionByTag(tag, target) {
          if (tag === Action.TAG_INVALID) logID(1004);
          var element = this._hashTargets.get(target);
          if (element) {
            if (element.actions != null) {
              for (var i = 0; i < element.actions.length; ++i) {
                var action = element.actions[i];
                if (action && action.getTag() === tag) {
                  return action;
                }
              }
            }
            logID(1005, tag);
          }
          return null;
        };
        _proto.getNumberOfRunningActionsInTarget = function getNumberOfRunningActionsInTarget(target) {
          var element = this._hashTargets.get(target);
          if (element) {
            return element.actions ? element.actions.length : 0;
          }
          return 0;
        };
        _proto.pauseTarget = function pauseTarget(target) {
          var element = this._hashTargets.get(target);
          if (element) element.paused = true;
        };
        _proto.resumeTarget = function resumeTarget(target) {
          var element = this._hashTargets.get(target);
          if (element) element.paused = false;
        };
        _proto.pauseAllRunningActions = function pauseAllRunningActions() {
          var idsWithActions = [];
          var locTargets = this._arrayTargets;
          for (var i = 0; i < locTargets.length; i++) {
            var element = locTargets[i];
            if (element && !element.paused) {
              element.paused = true;
              idsWithActions.push(element.target);
            }
          }
          return idsWithActions;
        };
        _proto.resumeTargets = function resumeTargets(targetsToResume) {
          if (!targetsToResume) return;
          for (var i = 0; i < targetsToResume.length; i++) {
            if (targetsToResume[i]) this.resumeTarget(targetsToResume[i]);
          }
        };
        _proto.pauseTargets = function pauseTargets(targetsToPause) {
          if (!targetsToPause) return;
          for (var i = 0; i < targetsToPause.length; i++) {
            if (targetsToPause[i]) this.pauseTarget(targetsToPause[i]);
          }
        };
        _proto.purgeSharedManager = function purgeSharedManager() {
          legacyCC.director.getScheduler().unscheduleUpdate(this);
        };
        _proto._removeActionAtIndex = function _removeActionAtIndex(index, element) {
          element.actions[index];
          element.actions.splice(index, 1);
          if (element.actionIndex >= index) element.actionIndex--;
          if (element.actions.length === 0) {
            this._deleteHashElement(element);
          }
        };
        _proto._deleteHashElement = function _deleteHashElement(element) {
          var ret = false;
          if (element && !element.lock) {
            if (this._hashTargets.get(element.target)) {
              this._hashTargets["delete"](element.target);
              var targets = this._arrayTargets;
              for (var i = 0, l = targets.length; i < l; i++) {
                if (targets[i] === element) {
                  targets.splice(i, 1);
                  break;
                }
              }
              this._putElement(element);
              ret = true;
            }
          }
          return ret;
        };
        _proto.update = function update(dt) {
          var locTargets = this._arrayTargets;
          var locCurrTarget;
          for (var elt = 0; elt < locTargets.length; elt++) {
            this._currentTarget = locTargets[elt];
            locCurrTarget = this._currentTarget;
            var target = locCurrTarget.target;
            if (isCCObject(target) && !target.isValid) {
              this.removeAllActionsFromTarget(target);
              elt--;
              continue;
            }
            if (!locCurrTarget.paused && locCurrTarget.actions) {
              locCurrTarget.lock = true;
              for (locCurrTarget.actionIndex = 0; locCurrTarget.actionIndex < locCurrTarget.actions.length; locCurrTarget.actionIndex++) {
                locCurrTarget.currentAction = locCurrTarget.actions[locCurrTarget.actionIndex];
                if (!locCurrTarget.currentAction) continue;
                locCurrTarget.currentAction.step(dt * (this._isActionInternal(locCurrTarget.currentAction) ? locCurrTarget.currentAction.getSpeed() : 1));
                if (locCurrTarget.currentAction && locCurrTarget.currentAction.isDone()) {
                  locCurrTarget.currentAction.stop();
                  var action = locCurrTarget.currentAction;
                  locCurrTarget.currentAction = null;
                  this.removeAction(action);
                }
                locCurrTarget.currentAction = null;
              }
              locCurrTarget.lock = false;
            }
            if (locCurrTarget.actions.length === 0) {
              if (this._deleteHashElement(locCurrTarget)) {
                elt--;
              }
            }
          }
        };
        _proto._isActionInternal = function _isActionInternal(action) {
          return typeof action._speedMethod !== 'undefined';
        };
        return ActionManager;
      }();

      var TweenSystem = exports('ff', function (_System) {
        _inheritsLoose(TweenSystem, _System);
        function TweenSystem() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _System.call.apply(_System, [this].concat(args)) || this;
          _this.actionMgr = new ActionManager();
          return _this;
        }
        var _proto = TweenSystem.prototype;
        _proto.update = function update(dt) {
          {
            this.actionMgr.update(dt);
          }
        };
        _createClass(TweenSystem, [{
          key: "ActionManager",
          get: function get() {
            return this.actionMgr;
          }
        }]);
        return TweenSystem;
      }(System));
      TweenSystem.ID = 'TWEEN';
      TweenSystem.instance = void 0;
      director.on(Director.EVENT_INIT, function () {
        var sys = new TweenSystem();
        TweenSystem.instance = sys;
        director.registerSystem(TweenSystem.ID, sys, System.Priority.MEDIUM);
      });

      var ActionInstant = function (_FiniteTimeAction) {
        _inheritsLoose(ActionInstant, _FiniteTimeAction);
        function ActionInstant() {
          return _FiniteTimeAction.apply(this, arguments) || this;
        }
        var _proto = ActionInstant.prototype;
        _proto.isDone = function isDone() {
          return true;
        };
        _proto.step = function step(dt) {
          this.update(1);
        };
        _proto.update = function update(dt) {};
        _proto.reverse = function reverse() {
          return this.clone();
        };
        _proto.clone = function clone() {
          return new ActionInstant();
        };
        return ActionInstant;
      }(FiniteTimeAction);
      var Show = function (_ActionInstant) {
        _inheritsLoose(Show, _ActionInstant);
        function Show() {
          return _ActionInstant.apply(this, arguments) || this;
        }
        var _proto2 = Show.prototype;
        _proto2.update = function update(dt) {
          var _renderComps = this.target.getComponentsInChildren(Renderer);
          for (var i = 0; i < _renderComps.length; ++i) {
            var render = _renderComps[i];
            render.enabled = true;
          }
        };
        _proto2.reverse = function reverse() {
          return new Hide();
        };
        _proto2.clone = function clone() {
          return new Show();
        };
        return Show;
      }(ActionInstant);
      function show() {
        return new Show();
      }
      var Hide = function (_ActionInstant2) {
        _inheritsLoose(Hide, _ActionInstant2);
        function Hide() {
          return _ActionInstant2.apply(this, arguments) || this;
        }
        var _proto3 = Hide.prototype;
        _proto3.update = function update(dt) {
          var _renderComps = this.target.getComponentsInChildren(Renderer);
          for (var i = 0; i < _renderComps.length; ++i) {
            var render = _renderComps[i];
            render.enabled = false;
          }
        };
        _proto3.reverse = function reverse() {
          return new Show();
        };
        _proto3.clone = function clone() {
          return new Hide();
        };
        return Hide;
      }(ActionInstant);
      function hide() {
        return new Hide();
      }
      (function (_ActionInstant3) {
        _inheritsLoose(ToggleVisibility, _ActionInstant3);
        function ToggleVisibility() {
          return _ActionInstant3.apply(this, arguments) || this;
        }
        var _proto4 = ToggleVisibility.prototype;
        _proto4.update = function update(dt) {
          var _renderComps = this.target.getComponentsInChildren(Renderer);
          for (var i = 0; i < _renderComps.length; ++i) {
            var render = _renderComps[i];
            render.enabled = !render.enabled;
          }
        };
        _proto4.reverse = function reverse() {
          return new ToggleVisibility();
        };
        _proto4.clone = function clone() {
          return new ToggleVisibility();
        };
        return ToggleVisibility;
      })(ActionInstant);
      var RemoveSelf = function (_ActionInstant4) {
        _inheritsLoose(RemoveSelf, _ActionInstant4);
        function RemoveSelf(isNeedCleanUp) {
          var _this;
          _this = _ActionInstant4.call(this) || this;
          _this._isNeedCleanUp = true;
          isNeedCleanUp !== undefined && _this.init(isNeedCleanUp);
          return _this;
        }
        var _proto5 = RemoveSelf.prototype;
        _proto5.update = function update(dt) {
          this.target.removeFromParent();
          if (this._isNeedCleanUp) {
            this.target.destroy();
          }
        };
        _proto5.init = function init(isNeedCleanUp) {
          this._isNeedCleanUp = isNeedCleanUp;
          return true;
        };
        _proto5.reverse = function reverse() {
          return new RemoveSelf(this._isNeedCleanUp);
        };
        _proto5.clone = function clone() {
          return new RemoveSelf(this._isNeedCleanUp);
        };
        return RemoveSelf;
      }(ActionInstant);
      function removeSelf(isNeedCleanUp) {
        return new RemoveSelf(isNeedCleanUp);
      }
      var CallFunc = function (_ActionInstant5) {
        _inheritsLoose(CallFunc, _ActionInstant5);
        function CallFunc(selector, selectorTarget, data) {
          var _this2;
          _this2 = _ActionInstant5.call(this) || this;
          _this2._selectorTarget = null;
          _this2._function = null;
          _this2._data = null;
          _this2.initWithFunction(selector, selectorTarget, data);
          return _this2;
        }
        var _proto6 = CallFunc.prototype;
        _proto6.initWithFunction = function initWithFunction(selector, selectorTarget, data) {
          if (selector) {
            this._function = selector;
          }
          if (selectorTarget) {
            this._selectorTarget = selectorTarget;
          }
          if (data !== undefined) {
            this._data = data;
          }
          return true;
        };
        _proto6.execute = function execute() {
          if (this._function) {
            this._function.call(this._selectorTarget, this.target, this._data);
          }
        };
        _proto6.update = function update(dt) {
          this.execute();
        };
        _proto6.getTargetCallback = function getTargetCallback() {
          return this._selectorTarget;
        };
        _proto6.setTargetCallback = function setTargetCallback(sel) {
          if (sel !== this._selectorTarget) {
            if (this._selectorTarget) {
              this._selectorTarget = null;
            }
            this._selectorTarget = sel;
          }
        };
        _proto6.clone = function clone() {
          var action = new CallFunc();
          action.initWithFunction(this._function, this._selectorTarget, this._data);
          return action;
        };
        return CallFunc;
      }(ActionInstant);
      function callFunc(selector, selectorTarget, data) {
        return new CallFunc(selector, selectorTarget, data);
      }

      var _class2$e, _class5;
      var ActionInterval = function (_FiniteTimeAction) {
        _inheritsLoose(ActionInterval, _FiniteTimeAction);
        function ActionInterval(d) {
          var _this;
          _this = _FiniteTimeAction.call(this) || this;
          _this.MAX_VALUE = 2;
          _this._elapsed = 0;
          _this._firstTick = false;
          _this._easeList = [];
          _this._speed = 1;
          _this._repeatForever = false;
          _this._repeatMethod = false;
          _this._speedMethod = false;
          if (d !== undefined && !isNaN(d)) {
            _this.initWithDuration(d);
          }
          return _this;
        }
        var _proto = ActionInterval.prototype;
        _proto.getElapsed = function getElapsed() {
          return this._elapsed;
        };
        _proto.initWithDuration = function initWithDuration(d) {
          this._duration = d === 0 ? macro.FLT_EPSILON : d;
          this._elapsed = 0;
          this._firstTick = true;
          return true;
        };
        _proto.isDone = function isDone() {
          return this._elapsed >= this._duration;
        };
        _proto._cloneDecoration = function _cloneDecoration(action) {
          action._repeatForever = this._repeatForever;
          action._speed = this._speed;
          action._timesForRepeat = this._timesForRepeat;
          action._easeList = this._easeList;
          action._speedMethod = this._speedMethod;
          action._repeatMethod = this._repeatMethod;
        };
        _proto._reverseEaseList = function _reverseEaseList(action) {
          if (this._easeList) {
            action._easeList = [];
            for (var i = 0; i < this._easeList.length; i++) {
              action._easeList.push(this._easeList[i]);
            }
          }
        };
        _proto.clone = function clone() {
          var action = new ActionInterval(this._duration);
          this._cloneDecoration(action);
          return action;
        };
        _proto.easing = function easing(easeObj) {
          if (this._easeList) this._easeList.length = 0;else this._easeList = [];
          for (var i = 0; i < arguments.length; i++) this._easeList.push(arguments[i]);
          return this;
        };
        _proto._computeEaseTime = function _computeEaseTime(dt) {
          return dt;
        };
        _proto.step = function step(dt) {
          if (this._firstTick) {
            this._firstTick = false;
            this._elapsed = 0;
          } else this._elapsed += dt;
          var t = this._elapsed / (this._duration > 0.0000001192092896 ? this._duration : 0.0000001192092896);
          t = t < 1 ? t : 1;
          this.update(t > 0 ? t : 0);
          if (this._repeatMethod && this._timesForRepeat > 1 && this.isDone()) {
            if (!this._repeatForever) {
              this._timesForRepeat--;
            }
            this.startWithTarget(this.target);
            this.step(this._elapsed - this._duration);
          }
        };
        _proto.startWithTarget = function startWithTarget(target) {
          Action.prototype.startWithTarget.call(this, target);
          this._elapsed = 0;
          this._firstTick = true;
        };
        _proto.reverse = function reverse() {
          logID(1010);
          return this;
        };
        _proto.setAmplitudeRate = function setAmplitudeRate(amp) {
          logID(1011);
        };
        _proto.getAmplitudeRate = function getAmplitudeRate() {
          logID(1012);
          return 0;
        };
        _proto.speed = function speed(_speed) {
          if (_speed <= 0) {
            logID(1013);
            return this;
          }
          this._speedMethod = true;
          this._speed *= _speed;
          return this;
        };
        _proto.getSpeed = function getSpeed() {
          return this._speed;
        };
        _proto.setSpeed = function setSpeed(speed) {
          this._speed = speed;
          return this;
        };
        _proto.repeat = function repeat(times) {
          times = Math.round(times);
          if (isNaN(times) || times < 1) {
            logID(1014);
            return this;
          }
          this._repeatMethod = true;
          this._timesForRepeat *= times;
          return this;
        };
        _proto.repeatForever = function repeatForever() {
          this._repeatMethod = true;
          this._timesForRepeat = this.MAX_VALUE;
          this._repeatForever = true;
          return this;
        };
        return ActionInterval;
      }(FiniteTimeAction);
      var Sequence = function (_ActionInterval) {
        _inheritsLoose(Sequence, _ActionInterval);
        function Sequence(tempArray) {
          var _this2;
          _this2 = _ActionInterval.call(this) || this;
          _this2._actions = [];
          _this2._split = 0;
          _this2._last = 0;
          _this2._reversed = false;
          var paramArray = tempArray instanceof Array ? tempArray : arguments;
          if (paramArray.length === 1) {
            errorID(1019);
            return _assertThisInitialized(_this2);
          }
          var last = paramArray.length - 1;
          if (last >= 0 && paramArray[last] == null) logID(1015);
          if (last >= 0) {
            var prev = paramArray[0];
            var action1;
            for (var i = 1; i < last; i++) {
              if (paramArray[i]) {
                action1 = prev;
                prev = Sequence._actionOneTwo(action1, paramArray[i]);
              }
            }
            _this2.initWithTwoActions(prev, paramArray[last]);
          }
          return _this2;
        }
        var _proto2 = Sequence.prototype;
        _proto2.initWithTwoActions = function initWithTwoActions(actionOne, actionTwo) {
          if (!actionOne || !actionTwo) {
            errorID(1025);
            return false;
          }
          var durationOne = actionOne._duration;
          var durationTwo = actionTwo._duration;
          durationOne *= actionOne._repeatMethod ? actionOne._timesForRepeat : 1;
          durationTwo *= actionTwo._repeatMethod ? actionTwo._timesForRepeat : 1;
          var d = durationOne + durationTwo;
          this.initWithDuration(d);
          this._actions[0] = actionOne;
          this._actions[1] = actionTwo;
          return true;
        };
        _proto2.clone = function clone() {
          var action = new Sequence();
          this._cloneDecoration(action);
          action.initWithTwoActions(this._actions[0].clone(), this._actions[1].clone());
          return action;
        };
        _proto2.startWithTarget = function startWithTarget(target) {
          ActionInterval.prototype.startWithTarget.call(this, target);
          this._split = this._actions[0]._duration / this._duration;
          this._split *= this._actions[0]._repeatMethod ? this._actions[0]._timesForRepeat : 1;
          this._last = -1;
        };
        _proto2.stop = function stop() {
          if (this._last !== -1) this._actions[this._last].stop();
          Action.prototype.stop.call(this);
        };
        _proto2.update = function update(dt) {
          var new_t;
          var found = 0;
          var locSplit = this._split;
          var locActions = this._actions;
          var locLast = this._last;
          var actionFound;
          dt = this._computeEaseTime(dt);
          if (dt < locSplit) {
            new_t = locSplit !== 0 ? dt / locSplit : 1;
            if (found === 0 && locLast === 1 && this._reversed) {
              locActions[1].update(0);
              locActions[1].stop();
            }
          } else {
            found = 1;
            new_t = locSplit === 1 ? 1 : (dt - locSplit) / (1 - locSplit);
            if (locLast === -1) {
              locActions[0].startWithTarget(this.target);
              locActions[0].update(1);
              locActions[0].stop();
            }
            if (locLast === 0) {
              locActions[0].update(1);
              locActions[0].stop();
            }
          }
          actionFound = locActions[found];
          if (locLast === found && actionFound.isDone()) return;
          if (locLast !== found) actionFound.startWithTarget(this.target);
          new_t *= actionFound._timesForRepeat;
          actionFound.update(new_t > 1 ? new_t % 1 : new_t);
          this._last = found;
        };
        _proto2.reverse = function reverse() {
          var action = Sequence._actionOneTwo(this._actions[1].reverse(), this._actions[0].reverse());
          this._cloneDecoration(action);
          this._reverseEaseList(action);
          action._reversed = true;
          return action;
        };
        return Sequence;
      }(ActionInterval);
      _class2$e = Sequence;
      Sequence._actionOneTwo = function (actionOne, actionTwo) {
        var sequence = new _class2$e();
        sequence.initWithTwoActions(actionOne, actionTwo);
        return sequence;
      };
      function sequence(tempArray) {
        var paramArray = tempArray instanceof Array ? tempArray : arguments;
        if (paramArray.length === 1) {
          errorID(1019);
          return null;
        }
        var last = paramArray.length - 1;
        if (last >= 0 && paramArray[last] == null) logID(1015);
        var result = null;
        if (last >= 0) {
          result = paramArray[0];
          for (var i = 1; i <= last; i++) {
            if (paramArray[i]) {
              result = Sequence._actionOneTwo(result, paramArray[i]);
            }
          }
        }
        return result;
      }
      var Repeat = function (_ActionInterval2) {
        _inheritsLoose(Repeat, _ActionInterval2);
        function Repeat(action, times) {
          var _this3;
          _this3 = _ActionInterval2.call(this) || this;
          _this3._times = 0;
          _this3._total = 0;
          _this3._nextDt = 0;
          _this3._actionInstant = false;
          _this3._innerAction = null;
          times !== undefined && _this3.initWithAction(action, times);
          return _this3;
        }
        var _proto3 = Repeat.prototype;
        _proto3.initWithAction = function initWithAction(action, times) {
          var duration = action._duration * times;
          if (this.initWithDuration(duration)) {
            this._times = times;
            this._innerAction = action;
            if (action instanceof ActionInstant) {
              this._actionInstant = true;
              this._times -= 1;
            }
            this._total = 0;
            return true;
          }
          return false;
        };
        _proto3.clone = function clone() {
          var action = new Repeat();
          this._cloneDecoration(action);
          action.initWithAction(this._innerAction.clone(), this._times);
          return action;
        };
        _proto3.startWithTarget = function startWithTarget(target) {
          this._total = 0;
          this._nextDt = this._innerAction._duration / this._duration;
          ActionInterval.prototype.startWithTarget.call(this, target);
          this._innerAction.startWithTarget(target);
        };
        _proto3.stop = function stop() {
          this._innerAction.stop();
          Action.prototype.stop.call(this);
        };
        _proto3.update = function update(dt) {
          dt = this._computeEaseTime(dt);
          var locInnerAction = this._innerAction;
          var locDuration = this._duration;
          var locTimes = this._times;
          var locNextDt = this._nextDt;
          if (dt >= locNextDt) {
            while (dt > locNextDt && this._total < locTimes) {
              locInnerAction.update(1);
              this._total++;
              locInnerAction.stop();
              locInnerAction.startWithTarget(this.target);
              locNextDt += locInnerAction._duration / locDuration;
              this._nextDt = locNextDt > 1 ? 1 : locNextDt;
            }
            if (dt >= 1.0 && this._total < locTimes) {
              locInnerAction.update(1);
              this._total++;
            }
            if (!this._actionInstant) {
              if (this._total === locTimes) {
                locInnerAction.stop();
              } else {
                locInnerAction.update(dt - (locNextDt - locInnerAction._duration / locDuration));
              }
            }
          } else {
            locInnerAction.update(dt * locTimes % 1.0);
          }
        };
        _proto3.isDone = function isDone() {
          return this._total === this._times;
        };
        _proto3.reverse = function reverse() {
          var action = new Repeat(this._innerAction.reverse(), this._times);
          this._cloneDecoration(action);
          this._reverseEaseList(action);
          return action;
        };
        _proto3.setInnerAction = function setInnerAction(action) {
          if (this._innerAction !== action) {
            this._innerAction = action;
          }
        };
        _proto3.getInnerAction = function getInnerAction() {
          return this._innerAction;
        };
        return Repeat;
      }(ActionInterval);
      function repeat(action, times) {
        return new Repeat(action, times);
      }
      var RepeatForever = function (_ActionInterval3) {
        _inheritsLoose(RepeatForever, _ActionInterval3);
        function RepeatForever(action) {
          var _this4;
          _this4 = _ActionInterval3.call(this) || this;
          _this4._innerAction = null;
          action && _this4.initWithAction(action);
          return _this4;
        }
        var _proto4 = RepeatForever.prototype;
        _proto4.initWithAction = function initWithAction(action) {
          if (!action) {
            errorID(1026);
            return false;
          }
          this._innerAction = action;
          return true;
        };
        _proto4.clone = function clone() {
          var action = new RepeatForever();
          this._cloneDecoration(action);
          action.initWithAction(this._innerAction.clone());
          return action;
        };
        _proto4.startWithTarget = function startWithTarget(target) {
          ActionInterval.prototype.startWithTarget.call(this, target);
          this._innerAction.startWithTarget(target);
        };
        _proto4.step = function step(dt) {
          var locInnerAction = this._innerAction;
          locInnerAction.step(dt);
          if (locInnerAction.isDone()) {
            locInnerAction.startWithTarget(this.target);
            locInnerAction.step(locInnerAction.getElapsed() - locInnerAction._duration);
          }
        };
        _proto4.isDone = function isDone() {
          return false;
        };
        _proto4.reverse = function reverse() {
          var action = new RepeatForever(this._innerAction.reverse());
          this._cloneDecoration(action);
          this._reverseEaseList(action);
          return action;
        };
        _proto4.setInnerAction = function setInnerAction(action) {
          if (this._innerAction !== action) {
            this._innerAction = action;
          }
        };
        _proto4.getInnerAction = function getInnerAction() {
          return this._innerAction;
        };
        return RepeatForever;
      }(ActionInterval);
      function repeatForever(action) {
        return new RepeatForever(action);
      }
      var Spawn = function (_ActionInterval4) {
        _inheritsLoose(Spawn, _ActionInterval4);
        function Spawn(tempArray) {
          var _this5;
          _this5 = _ActionInterval4.call(this) || this;
          _this5._one = null;
          _this5._two = null;
          var paramArray = tempArray instanceof Array ? tempArray : arguments;
          if (paramArray.length === 1) {
            errorID(1020);
            return _assertThisInitialized(_this5);
          }
          var last = paramArray.length - 1;
          if (last >= 0 && paramArray[last] == null) logID(1015);
          if (last >= 0) {
            var prev = paramArray[0];
            var action1;
            for (var i = 1; i < last; i++) {
              if (paramArray[i]) {
                action1 = prev;
                prev = Spawn._actionOneTwo(action1, paramArray[i]);
              }
            }
            _this5.initWithTwoActions(prev, paramArray[last]);
          }
          return _this5;
        }
        var _proto5 = Spawn.prototype;
        _proto5.initWithTwoActions = function initWithTwoActions(action1, action2) {
          if (!action1 || !action2) {
            errorID(1027);
            return false;
          }
          var ret = false;
          var d1 = action1._duration;
          var d2 = action2._duration;
          if (this.initWithDuration(Math.max(d1, d2))) {
            this._one = action1;
            this._two = action2;
            if (d1 > d2) {
              this._two = Sequence._actionOneTwo(action2, delayTime(d1 - d2));
            } else if (d1 < d2) {
              this._one = Sequence._actionOneTwo(action1, delayTime(d2 - d1));
            }
            ret = true;
          }
          return ret;
        };
        _proto5.clone = function clone() {
          var action = new Spawn();
          this._cloneDecoration(action);
          action.initWithTwoActions(this._one.clone(), this._two.clone());
          return action;
        };
        _proto5.startWithTarget = function startWithTarget(target) {
          ActionInterval.prototype.startWithTarget.call(this, target);
          this._one.startWithTarget(target);
          this._two.startWithTarget(target);
        };
        _proto5.stop = function stop() {
          this._one.stop();
          this._two.stop();
          Action.prototype.stop.call(this);
        };
        _proto5.update = function update(dt) {
          dt = this._computeEaseTime(dt);
          if (this._one) this._one.update(dt);
          if (this._two) this._two.update(dt);
        };
        _proto5.reverse = function reverse() {
          var action = Spawn._actionOneTwo(this._one.reverse(), this._two.reverse());
          this._cloneDecoration(action);
          this._reverseEaseList(action);
          return action;
        };
        return Spawn;
      }(ActionInterval);
      _class5 = Spawn;
      Spawn._actionOneTwo = function (action1, action2) {
        var pSpawn = new _class5();
        pSpawn.initWithTwoActions(action1, action2);
        return pSpawn;
      };
      function spawn(tempArray) {
        var paramArray = tempArray instanceof Array ? tempArray : arguments;
        if (paramArray.length === 1) {
          errorID(1020);
          return null;
        }
        if (paramArray.length > 0 && paramArray[paramArray.length - 1] == null) logID(1015);
        var prev = paramArray[0];
        for (var i = 1; i < paramArray.length; i++) {
          if (paramArray[i] != null) prev = Spawn._actionOneTwo(prev, paramArray[i]);
        }
        return prev;
      }
      var DelayTime = function (_ActionInterval5) {
        _inheritsLoose(DelayTime, _ActionInterval5);
        function DelayTime() {
          return _ActionInterval5.apply(this, arguments) || this;
        }
        var _proto6 = DelayTime.prototype;
        _proto6.update = function update(dt) {};
        _proto6.reverse = function reverse() {
          var action = new DelayTime(this._duration);
          this._cloneDecoration(action);
          this._reverseEaseList(action);
          return action;
        };
        _proto6.clone = function clone() {
          var action = new DelayTime();
          this._cloneDecoration(action);
          action.initWithDuration(this._duration);
          return action;
        };
        return DelayTime;
      }(ActionInterval);
      function delayTime(d) {
        return new DelayTime(d);
      }
      var ReverseTime = function (_ActionInterval6) {
        _inheritsLoose(ReverseTime, _ActionInterval6);
        function ReverseTime(action) {
          var _this6;
          _this6 = _ActionInterval6.call(this) || this;
          _this6._other = null;
          action && _this6.initWithAction(action);
          return _this6;
        }
        var _proto7 = ReverseTime.prototype;
        _proto7.initWithAction = function initWithAction(action) {
          if (!action) {
            errorID(1028);
            return false;
          }
          if (action === this._other) {
            errorID(1029);
            return false;
          }
          if (ActionInterval.prototype.initWithDuration.call(this, action._duration)) {
            this._other = action;
            return true;
          }
          return false;
        };
        _proto7.clone = function clone() {
          var action = new ReverseTime();
          this._cloneDecoration(action);
          action.initWithAction(this._other.clone());
          return action;
        };
        _proto7.startWithTarget = function startWithTarget(target) {
          ActionInterval.prototype.startWithTarget.call(this, target);
          this._other.startWithTarget(target);
        };
        _proto7.update = function update(dt) {
          dt = this._computeEaseTime(dt);
          if (this._other) this._other.update(1 - dt);
        };
        _proto7.reverse = function reverse() {
          return this._other.clone();
        };
        _proto7.stop = function stop() {
          this._other.stop();
          Action.prototype.stop.call(this);
        };
        return ReverseTime;
      }(ActionInterval);
      function reverseTime(action) {
        return new ReverseTime(action);
      }

      function TweenEasingAdapter(easingName) {
        var initialChar = easingName.charAt(0);
        if (/[A-Z]/.test(initialChar)) {
          easingName = easingName.replace(initialChar, initialChar.toLowerCase());
          var arr = easingName.split('-');
          if (arr.length === 2) {
            var str0 = arr[0];
            if (str0 === 'linear') {
              easingName = 'linear';
            } else {
              var str1 = arr[1];
              switch (str0) {
                case 'quadratic':
                  easingName = "quad" + str1;
                  break;
                case 'quartic':
                  easingName = "quart" + str1;
                  break;
                case 'quintic':
                  easingName = "quint" + str1;
                  break;
                case 'sinusoidal':
                  easingName = "sine" + str1;
                  break;
                case 'exponential':
                  easingName = "expo" + str1;
                  break;
                case 'circular':
                  easingName = "circ" + str1;
                  break;
                default:
                  easingName = str0 + str1;
                  break;
              }
            }
          }
        }
        return easingName;
      }
      function TweenOptionChecker(opts) {
        var header = ' [Tween:] ';
        var message = " option is not support in v + " + engineVersion;
        var _opts = opts;
        if (_opts.delay) {
          warn(header + "delay" + message);
        }
        if (_opts.repeat) {
          warn(header + "repeat" + message);
        }
        if (_opts.repeatDelay) {
          warn(header + "repeatDelay" + message);
        }
        if (_opts.interpolation) {
          warn(header + "interpolation" + message);
        }
        if (_opts.onStop) {
          warn(header + "onStop" + message);
        }
      }
      var TweenAction = exports('fj', function (_ActionInterval) {
        _inheritsLoose(TweenAction, _ActionInterval);
        function TweenAction(duration, props, opts) {
          var _this;
          _this = _ActionInterval.call(this) || this;
          _this._opts = void 0;
          _this._props = void 0;
          _this._originProps = void 0;
          if (opts == null) {
            opts = Object.create(null);
          } else {
            TweenOptionChecker(opts);
            if (opts.easing && typeof opts.easing === 'string') {
              opts.easing = TweenEasingAdapter(opts.easing);
            }
            if (!opts.progress) {
              opts.progress = _this.progress;
            }
            if (opts.easing && typeof opts.easing === 'string') {
              var easingName = opts.easing;
              opts.easing = easing[easingName];
              if (!opts.easing) {
                warnID(1031, easingName);
              }
            }
          }
          _this._opts = opts;
          _this._props = Object.create(null);
          for (var name in props) {
            if (!props.hasOwnProperty(name)) continue;
            var value = props[name];
            if (typeof value === 'function') {
              value = value();
            }
            if (value == null || typeof value === 'string') continue;
            var customEasing = void 0;
            var progress = void 0;
            if (value.value !== undefined && (value.easing || value.progress)) {
              if (typeof value.easing === 'string') {
                customEasing = easing[value.easing];
                if (!customEasing) warnID(1031, value.easing);
              } else {
                customEasing = value.easing;
              }
              progress = value.progress;
              value = value.value;
            }
            var prop = Object.create(null);
            prop.value = value;
            prop.easing = customEasing;
            prop.progress = progress;
            _this._props[name] = prop;
          }
          _this._originProps = props;
          _this.initWithDuration(duration);
          return _this;
        }
        var _proto = TweenAction.prototype;
        _proto.clone = function clone() {
          var action = new TweenAction(this._duration, this._originProps, this._opts);
          this._cloneDecoration(action);
          return action;
        };
        _proto.startWithTarget = function startWithTarget(target) {
          ActionInterval.prototype.startWithTarget.call(this, target);
          var relative = !!this._opts.relative;
          var props = this._props;
          for (var property in props) {
            var _t = target[property];
            if (_t === undefined) {
              continue;
            }
            var prop = props[property];
            var value = prop.value;
            if (typeof _t === 'number') {
              prop.start = _t;
              prop.current = _t;
              prop.end = relative ? _t + value : value;
            } else if (typeof _t === 'object') {
              if (prop.start == null) {
                prop.start = {};
                prop.current = {};
                prop.end = {};
              }
              for (var k in value) {
                if (isNaN(_t[k])) continue;
                prop.start[k] = _t[k];
                prop.current[k] = _t[k];
                prop.end[k] = relative ? _t[k] + value[k] : value[k];
              }
            }
          }
          if (this._opts.onStart) {
            this._opts.onStart(this.target);
          }
        };
        _proto.update = function update(t) {
          var target = this.target;
          if (!target) return;
          var props = this._props;
          var opts = this._opts;
          var easingTime = t;
          if (opts.easing) easingTime = opts.easing(t);
          var progress = opts.progress;
          for (var name in props) {
            var prop = props[name];
            var time = prop.easing ? prop.easing(t) : easingTime;
            var interpolation = prop.progress ? prop.progress : progress;
            var start = prop.start;
            var end = prop.end;
            if (typeof start === 'number') {
              prop.current = interpolation(start, end, prop.current, time);
            } else if (typeof start === 'object') {
              for (var k in start) {
                prop.current[k] = interpolation(start[k], end[k], prop.current[k], time);
              }
            }
            target[name] = prop.current;
          }
          if (opts.onUpdate) {
            opts.onUpdate(this.target, t);
          }
          if (t === 1 && opts.onComplete) {
            opts.onComplete(this.target);
          }
        };
        _proto.progress = function progress(start, end, current, t) {
          return start + (end - start) * t;
        };
        return TweenAction;
      }(ActionInterval));

      var SetAction = function (_ActionInstant) {
        _inheritsLoose(SetAction, _ActionInstant);
        function SetAction(props) {
          var _this;
          _this = _ActionInstant.call(this) || this;
          _this._props = void 0;
          _this._props = {};
          props !== undefined && _this.init(props);
          return _this;
        }
        var _proto = SetAction.prototype;
        _proto.init = function init(props) {
          for (var name in props) {
            this._props[name] = props[name];
          }
          return true;
        };
        _proto.update = function update() {
          var props = this._props;
          var target = this.target;
          for (var name in props) {
            target[name] = props[name];
          }
        };
        _proto.clone = function clone() {
          var action = new SetAction();
          action.init(this._props);
          return action;
        };
        return SetAction;
      }(ActionInstant);

      var Tween = exports('fi', function () {
        function Tween(target) {
          this._actions = [];
          this._finalAction = null;
          this._target = null;
          this._tag = Action.TAG_INVALID;
          this._target = target === undefined ? null : target;
        }
        var _proto = Tween.prototype;
        _proto.tag = function tag(_tag) {
          this._tag = _tag;
          return this;
        };
        _proto.then = function then(other) {
          if (other instanceof Action) {
            this._actions.push(other.clone());
          } else {
            this._actions.push(other._union());
          }
          return this;
        };
        _proto.target = function target(_target) {
          this._target = _target;
          return this;
        };
        _proto.start = function start() {
          if (!this._target) {
            warn('Please set target to tween first');
            return this;
          }
          if (this._finalAction) {
            TweenSystem.instance.ActionManager.removeAction(this._finalAction);
          }
          this._finalAction = this._union();
          this._finalAction.setTag(this._tag);
          TweenSystem.instance.ActionManager.addAction(this._finalAction, this._target, false);
          return this;
        };
        _proto.stop = function stop() {
          if (this._finalAction) {
            TweenSystem.instance.ActionManager.removeAction(this._finalAction);
          }
          return this;
        };
        _proto.clone = function clone(target) {
          var action = this._union();
          return tween(target).then(action.clone());
        };
        _proto.union = function union() {
          var action = this._union();
          this._actions.length = 0;
          this._actions.push(action);
          return this;
        };
        _proto.to = function to(duration, props, opts) {
          opts = opts || Object.create(null);
          opts.relative = false;
          var action = new TweenAction(duration, props, opts);
          this._actions.push(action);
          return this;
        };
        _proto.by = function by(duration, props, opts) {
          opts = opts || Object.create(null);
          opts.relative = true;
          var action = new TweenAction(duration, props, opts);
          this._actions.push(action);
          return this;
        };
        _proto.set = function set(props) {
          var action = new SetAction(props);
          this._actions.push(action);
          return this;
        };
        _proto.delay = function delay(duration) {
          var action = delayTime(duration);
          this._actions.push(action);
          return this;
        };
        _proto.call = function call(callback) {
          var action = callFunc(callback);
          this._actions.push(action);
          return this;
        };
        _proto.sequence = function sequence() {
          var action = Tween._wrappedSequence.apply(Tween, arguments);
          this._actions.push(action);
          return this;
        };
        _proto.parallel = function parallel() {
          var action = Tween._wrappedParallel.apply(Tween, arguments);
          this._actions.push(action);
          return this;
        };
        _proto.repeat = function repeat$1(repeatTimes, embedTween) {
          if (repeatTimes === Infinity) {
            return this.repeatForever(embedTween);
          }
          var actions = this._actions;
          var action;
          if (embedTween instanceof Tween) {
            action = embedTween._union();
          } else {
            action = actions.pop();
          }
          actions.push(repeat(action, repeatTimes));
          return this;
        };
        _proto.repeatForever = function repeatForever$1(embedTween) {
          var actions = this._actions;
          var action;
          if (embedTween instanceof Tween) {
            action = embedTween._union();
          } else {
            action = actions.pop();
          }
          actions.push(repeatForever(action));
          return this;
        };
        _proto.reverseTime = function reverseTime$1(embedTween) {
          var actions = this._actions;
          var action;
          if (embedTween instanceof Tween) {
            action = embedTween._union();
          } else {
            action = actions.pop();
          }
          actions.push(reverseTime(action));
          return this;
        };
        _proto.hide = function hide$1() {
          var action = hide();
          this._actions.push(action);
          return this;
        };
        _proto.show = function show$1() {
          var action = show();
          this._actions.push(action);
          return this;
        };
        _proto.removeSelf = function removeSelf$1() {
          var action = removeSelf(false);
          this._actions.push(action);
          return this;
        };
        _proto.destroySelf = function destroySelf() {
          var action = removeSelf(true);
          this._actions.push(action);
          return this;
        };
        Tween.stopAll = function stopAll() {
          TweenSystem.instance.ActionManager.removeAllActions();
        };
        Tween.stopAllByTag = function stopAllByTag(tag, target) {
          TweenSystem.instance.ActionManager.removeAllActionsByTag(tag, target);
        };
        Tween.stopAllByTarget = function stopAllByTarget(target) {
          TweenSystem.instance.ActionManager.removeAllActionsFromTarget(target);
        };
        _proto._union = function _union() {
          var actions = this._actions;
          var action;
          if (actions.length === 1) {
            action = actions[0];
          } else {
            action = sequence(actions);
          }
          return action;
        };
        _proto._destroy = function _destroy() {
          this.stop();
        };
        Tween._wrappedSequence = function _wrappedSequence() {
          var tmp_args = Tween._tmp_args;
          tmp_args.length = 0;
          for (var l = arguments.length, i = 0; i < l; i++) {
            var arg = tmp_args[i] = i < 0 || arguments.length <= i ? undefined : arguments[i];
            if (arg instanceof Tween) {
              tmp_args[i] = arg._union();
            }
          }
          return sequence.apply(sequence, tmp_args);
        };
        Tween._wrappedParallel = function _wrappedParallel() {
          var tmp_args = Tween._tmp_args;
          tmp_args.length = 0;
          for (var l = arguments.length, i = 0; i < l; i++) {
            var arg = tmp_args[i] = i < 0 || arguments.length <= i ? undefined : arguments[i];
            if (arg instanceof Tween) {
              tmp_args[i] = arg._union();
            }
          }
          return spawn.apply(spawn, tmp_args);
        };
        return Tween;
      }());
      Tween._tmp_args = [];
      legacyCC.Tween = Tween;
      function tween(target) {
        return new Tween(target);
      }
      legacyCC.tween = tween;
      function tweenUtil(target) {
        warn('tweenUtil\' is deprecated, please use \'tween\' instead ');
        return new Tween(target);
      }
      legacyCC.tweenUtil = tweenUtil;

      var DeviceType;
      (function (DeviceType) {
        DeviceType[DeviceType["Other"] = 0] = "Other";
        DeviceType[DeviceType["Left"] = 1] = "Left";
        DeviceType[DeviceType["Right"] = 2] = "Right";
      })(DeviceType || (DeviceType = {}));
      var XrUIPressEventType;
      (function (XrUIPressEventType) {
        XrUIPressEventType["XRUI_HOVER_ENTERED"] = "xrui-hover-entered";
        XrUIPressEventType["XRUI_HOVER_EXITED"] = "xrui-hover-exited";
        XrUIPressEventType["XRUI_HOVER_STAY"] = "xrui-hover-stay";
        XrUIPressEventType["XRUI_CLICK"] = "xrui-click";
        XrUIPressEventType["XRUI_UNCLICK"] = "xrui-unclick";
      })(XrUIPressEventType || (XrUIPressEventType = {}));
      var XrKeyboardEventType;
      (function (XrKeyboardEventType) {
        XrKeyboardEventType["XR_CAPS_LOCK"] = "xr-caps-lock";
        XrKeyboardEventType["XR_KEYBOARD_INIT"] = "xr-keyboard-init";
        XrKeyboardEventType["XR_KEYBOARD_INPUT"] = "xr-keyboard-input";
        XrKeyboardEventType["TO_LATIN"] = "to-latin";
        XrKeyboardEventType["TO_SYMBOL"] = "to-symbol";
        XrKeyboardEventType["TO_MATH_SYMBOL"] = "to-math-symbol";
      })(XrKeyboardEventType || (XrKeyboardEventType = {}));
      (function (_Event) {
        _inheritsLoose(XrUIPressEvent, _Event);
        function XrUIPressEvent() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Event.call.apply(_Event, [this].concat(args)) || this;
          _this.deviceType = DeviceType.Other;
          _this.hitPoint = new Vec3();
          return _this;
        }
        return XrUIPressEvent;
      })(Event);

      var _dec$g, _dec2$f, _dec3$e, _dec4$b, _dec5$b, _dec6$5, _dec7$4, _dec8$3, _dec9$3, _dec10$1, _class$g, _class2$d, _initializer$d, _initializer2$d, _initializer3$b, _initializer4$a, _initializer5$8, _initializer6$5, _initializer7$5, _initializer8$5, _initializer9$5, _initializer10$5, _initializer11$5, _initializer12$4, _initializer13$3, _initializer14$2, _class3$a;
      var _tempColor$1 = new Color$1();
      var Transition;
      (function (Transition) {
        Transition[Transition["NONE"] = 0] = "NONE";
        Transition[Transition["COLOR"] = 1] = "COLOR";
        Transition[Transition["SPRITE"] = 2] = "SPRITE";
        Transition[Transition["SCALE"] = 3] = "SCALE";
      })(Transition || (Transition = {}));
      ccenum(Transition);
      var State;
      (function (State) {
        State["NORMAL"] = "normal";
        State["HOVER"] = "hover";
        State["PRESSED"] = "pressed";
        State["DISABLED"] = "disabled";
      })(State || (State = {}));
      var EventType$4;
      (function (EventType) {
        EventType["CLICK"] = "click";
      })(EventType$4 || (EventType$4 = {}));
      var Button = exports('fk', (_dec$g = ccclass$n('cc.Button'), _dec2$f = executionOrder$1(110), _dec3$e = requireComponent(UITransform), _dec4$b = type$7(Node$1), _dec5$b = type$7(Transition), _dec6$5 = type$7(SpriteFrame), _dec7$4 = type$7(SpriteFrame), _dec8$3 = type$7(SpriteFrame), _dec9$3 = type$7(SpriteFrame), _dec10$1 = type$7([EventHandler]), _dec$g(_class$g = _dec2$f(_class$g = _dec3$e(_class$g = (_class2$d = (_class3$a = function (_Component) {
        _inheritsLoose(Button, _Component);
        function Button() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Component.call.apply(_Component, [this].concat(args)) || this;
          _this.clickEvents = _initializer$d && _initializer$d();
          _this._interactable = _initializer2$d && _initializer2$d();
          _this._transition = _initializer3$b && _initializer3$b();
          _this._normalColor = _initializer4$a && _initializer4$a();
          _this._hoverColor = _initializer5$8 && _initializer5$8();
          _this._pressedColor = _initializer6$5 && _initializer6$5();
          _this._disabledColor = _initializer7$5 && _initializer7$5();
          _this._normalSprite = _initializer8$5 && _initializer8$5();
          _this._hoverSprite = _initializer9$5 && _initializer9$5();
          _this._pressedSprite = _initializer10$5 && _initializer10$5();
          _this._disabledSprite = _initializer11$5 && _initializer11$5();
          _this._duration = _initializer12$4 && _initializer12$4();
          _this._zoomScale = _initializer13$3 && _initializer13$3();
          _this._target = _initializer14$2 && _initializer14$2();
          _this._pressed = false;
          _this._hovered = false;
          _this._fromColor = new Color$1();
          _this._toColor = new Color$1();
          _this._time = 0;
          _this._transitionFinished = true;
          _this._fromScale = new Vec3();
          _this._toScale = new Vec3();
          _this._originalScale = null;
          _this._sprite = null;
          _this._targetScale = new Vec3();
          return _this;
        }
        var _proto = Button.prototype;
        _proto.__preload = function __preload() {
          if (!this.target) {
            this.target = this.node;
          }
          this._applyTarget();
          this._resetState();
        };
        _proto.onEnable = function onEnable() {
          {
            this._registerNodeEvent();
          }
        };
        _proto.onDisable = function onDisable() {
          this._resetState();
          {
            this._unregisterNodeEvent();
          }
        };
        _proto.onDestroy = function onDestroy() {
          if (this.target.isValid) {
            this._unregisterTargetEvent(this.target);
          }
        };
        _proto.update = function update(dt) {
          var target = this.target;
          if (this._transitionFinished || !target) {
            return;
          }
          if (this._transition !== Transition.COLOR && this._transition !== Transition.SCALE) {
            return;
          }
          this._time += dt;
          var ratio = 1.0;
          if (this._duration > 0) {
            ratio = this._time / this._duration;
          }
          if (ratio >= 1) {
            ratio = 1;
          }
          if (this._transition === Transition.COLOR) {
            var renderComp = target._uiProps.uiComp;
            Color$1.lerp(_tempColor$1, this._fromColor, this._toColor, ratio);
            if (renderComp) {
              renderComp.color = _tempColor$1;
            }
          } else if (this.transition === Transition.SCALE) {
            target.getScale(this._targetScale);
            this._targetScale.x = lerp(this._fromScale.x, this._toScale.x, ratio);
            this._targetScale.y = lerp(this._fromScale.y, this._toScale.y, ratio);
            target.setScale(this._targetScale);
          }
          if (ratio === 1) {
            this._transitionFinished = true;
          }
        };
        _proto._resizeNodeToTargetNode = function _resizeNodeToTargetNode() {
          if (!this.target) {
            return;
          }
          this.target._uiProps.uiTransformComp;
        };
        _proto._resetState = function _resetState() {
          this._pressed = false;
          this._hovered = false;
          var target = this.target;
          if (!target) {
            return;
          }
          var transition = this._transition;
          if (transition === Transition.COLOR && this._interactable) {
            var renderComp = target.getComponent(UIRenderer);
            if (renderComp) {
              renderComp.color = this._normalColor;
            }
          } else if (transition === Transition.SCALE && this._originalScale) {
            target.setScale(this._originalScale);
          }
          this._transitionFinished = true;
        };
        _proto._registerNodeEvent = function _registerNodeEvent() {
          this.node.on(NodeEventType.TOUCH_START, this._onTouchBegan, this);
          this.node.on(NodeEventType.TOUCH_MOVE, this._onTouchMove, this);
          this.node.on(NodeEventType.TOUCH_END, this._onTouchEnded, this);
          this.node.on(NodeEventType.TOUCH_CANCEL, this._onTouchCancel, this);
          this.node.on(NodeEventType.MOUSE_ENTER, this._onMouseMoveIn, this);
          this.node.on(NodeEventType.MOUSE_LEAVE, this._onMouseMoveOut, this);
          this.node.on(XrUIPressEventType.XRUI_HOVER_ENTERED, this._xrHoverEnter, this);
          this.node.on(XrUIPressEventType.XRUI_HOVER_EXITED, this._xrHoverExit, this);
          this.node.on(XrUIPressEventType.XRUI_CLICK, this._xrClick, this);
          this.node.on(XrUIPressEventType.XRUI_UNCLICK, this._xrUnClick, this);
        };
        _proto._registerTargetEvent = function _registerTargetEvent(target) {
          target.on(NodeEventType.TRANSFORM_CHANGED, this._onTargetTransformChanged, this);
        };
        _proto._unregisterNodeEvent = function _unregisterNodeEvent() {
          this.node.off(NodeEventType.TOUCH_START, this._onTouchBegan, this);
          this.node.off(NodeEventType.TOUCH_MOVE, this._onTouchMove, this);
          this.node.off(NodeEventType.TOUCH_END, this._onTouchEnded, this);
          this.node.off(NodeEventType.TOUCH_CANCEL, this._onTouchCancel, this);
          this.node.off(NodeEventType.MOUSE_ENTER, this._onMouseMoveIn, this);
          this.node.off(NodeEventType.MOUSE_LEAVE, this._onMouseMoveOut, this);
          this.node.off(XrUIPressEventType.XRUI_HOVER_ENTERED, this._xrHoverEnter, this);
          this.node.off(XrUIPressEventType.XRUI_HOVER_EXITED, this._xrHoverExit, this);
          this.node.off(XrUIPressEventType.XRUI_CLICK, this._xrClick, this);
          this.node.off(XrUIPressEventType.XRUI_UNCLICK, this._xrUnClick, this);
        };
        _proto._unregisterTargetEvent = function _unregisterTargetEvent(target) {
          target.off(NodeEventType.TRANSFORM_CHANGED);
        };
        _proto._getTargetSprite = function _getTargetSprite(target) {
          var sprite = null;
          if (target) {
            sprite = target.getComponent(Sprite);
          }
          return sprite;
        };
        _proto._applyTarget = function _applyTarget() {
          if (this.target) {
            this._sprite = this._getTargetSprite(this.target);
            if (!this._originalScale) {
              this._originalScale = new Vec3();
            }
            Vec3.copy(this._originalScale, this.target.getScale());
            this._registerTargetEvent(this.target);
          }
        };
        _proto._onTargetSpriteFrameChanged = function _onTargetSpriteFrameChanged(comp) {
          if (this._transition === Transition.SPRITE) {
            this._setCurrentStateSpriteFrame(comp.spriteFrame);
          }
        };
        _proto._setCurrentStateSpriteFrame = function _setCurrentStateSpriteFrame(spriteFrame) {
          if (!spriteFrame) {
            return;
          }
          switch (this._getButtonState()) {
            case State.NORMAL:
              this._normalSprite = spriteFrame;
              break;
            case State.HOVER:
              this._hoverSprite = spriteFrame;
              break;
            case State.PRESSED:
              this._pressedSprite = spriteFrame;
              break;
            case State.DISABLED:
              this._disabledSprite = spriteFrame;
              break;
          }
        };
        _proto._onTargetColorChanged = function _onTargetColorChanged(color) {
          if (this._transition === Transition.COLOR) {
            this._setCurrentStateColor(color);
          }
        };
        _proto._setCurrentStateColor = function _setCurrentStateColor(color) {
          switch (this._getButtonState()) {
            case State.NORMAL:
              this._normalColor = color;
              break;
            case State.HOVER:
              this._hoverColor = color;
              break;
            case State.PRESSED:
              this._pressedColor = color;
              break;
            case State.DISABLED:
              this._disabledColor = color;
              break;
          }
        };
        _proto._onTargetTransformChanged = function _onTargetTransformChanged(transformBit) {
          if (transformBit & TransformBit.SCALE && this._originalScale && this._transition === Transition.SCALE && this._transitionFinished) {
            Vec3.copy(this._originalScale, this.target.getScale());
          }
        };
        _proto._onTouchBegan = function _onTouchBegan(event) {
          if (!this._interactable || !this.enabledInHierarchy) {
            return;
          }
          this._pressed = true;
          this._updateState();
          if (event) {
            event.propagationStopped = true;
          }
        };
        _proto._onTouchMove = function _onTouchMove(event) {
          if (!this._interactable || !this.enabledInHierarchy || !this._pressed) {
            return;
          }
          if (!event) {
            return;
          }
          var touch = event.touch;
          if (!touch) {
            return;
          }
          var hit = this.node._uiProps.uiTransformComp.hitTest(touch.getLocation(), event.windowId);
          if (this._transition === Transition.SCALE && this.target && this._originalScale) {
            if (hit) {
              Vec3.copy(this._fromScale, this._originalScale);
              Vec3.multiplyScalar(this._toScale, this._originalScale, this._zoomScale);
              this._transitionFinished = false;
            } else {
              this._time = 0;
              this._transitionFinished = true;
              this.target.setScale(this._originalScale);
            }
          } else {
            var state;
            if (hit) {
              state = State.PRESSED;
            } else {
              state = State.NORMAL;
            }
            this._applyTransition(state);
          }
          if (event) {
            event.propagationStopped = true;
          }
        };
        _proto._onTouchEnded = function _onTouchEnded(event) {
          if (!this._interactable || !this.enabledInHierarchy) {
            return;
          }
          if (this._pressed) {
            EventHandler.emitEvents(this.clickEvents, event);
            this.node.emit(EventType$4.CLICK, this);
          }
          this._pressed = false;
          this._updateState();
          if (event) {
            event.propagationStopped = true;
          }
        };
        _proto._onTouchCancel = function _onTouchCancel(event) {
          if (!this._interactable || !this.enabledInHierarchy) {
            return;
          }
          this._pressed = false;
          this._updateState();
        };
        _proto._onMouseMoveIn = function _onMouseMoveIn(event) {
          if (this._pressed || !this.interactable || !this.enabledInHierarchy) {
            return;
          }
          if (this._transition === Transition.SPRITE && !this._hoverSprite) {
            return;
          }
          if (!this._hovered) {
            this._hovered = true;
            this._updateState();
          }
        };
        _proto._onMouseMoveOut = function _onMouseMoveOut(event) {
          if (this._hovered) {
            this._hovered = false;
            this._updateState();
          }
        };
        _proto._updateState = function _updateState() {
          var state = this._getButtonState();
          this._applyTransition(state);
        };
        _proto._getButtonState = function _getButtonState() {
          var state = State.NORMAL;
          if (!this._interactable) {
            state = State.DISABLED;
          } else if (this._pressed) {
            state = State.PRESSED;
          } else if (this._hovered) {
            state = State.HOVER;
          }
          return state.toString();
        };
        _proto._updateColorTransition = function _updateColorTransition(state) {
          var _this$target;
          var color = this[state + "Color"];
          var renderComp = (_this$target = this.target) === null || _this$target === void 0 ? void 0 : _this$target.getComponent(UIRenderer);
          if (!renderComp) {
            return;
          }
          if (state === State.DISABLED.toString()) {
            renderComp.color = color;
          } else {
            this._fromColor = renderComp.color.clone();
            this._toColor = color;
            this._time = 0;
            this._transitionFinished = false;
          }
        };
        _proto._updateSpriteTransition = function _updateSpriteTransition(state) {
          var sprite = this[state + "Sprite"];
          if (this._sprite && sprite) {
            this._sprite.spriteFrame = sprite;
          }
        };
        _proto._updateScaleTransition = function _updateScaleTransition(state) {
          if (!this._interactable) {
            return;
          }
          if (state === State.PRESSED.toString()) {
            this._zoomUp();
          } else {
            this._zoomBack();
          }
        };
        _proto._zoomUp = function _zoomUp() {
          if (!this._originalScale) {
            return;
          }
          Vec3.copy(this._fromScale, this._originalScale);
          Vec3.multiplyScalar(this._toScale, this._originalScale, this._zoomScale);
          this._time = 0;
          this._transitionFinished = false;
        };
        _proto._zoomBack = function _zoomBack() {
          if (!this.target || !this._originalScale) {
            return;
          }
          Vec3.copy(this._fromScale, this.target.getScale());
          Vec3.copy(this._toScale, this._originalScale);
          this._time = 0;
          this._transitionFinished = false;
        };
        _proto._applyTransition = function _applyTransition(state) {
          var transition = this._transition;
          if (transition === Transition.COLOR) {
            this._updateColorTransition(state);
          } else if (transition === Transition.SPRITE) {
            this._updateSpriteTransition(state);
          } else if (transition === Transition.SCALE) {
            this._updateScaleTransition(state);
          }
        };
        _proto._xrHoverEnter = function _xrHoverEnter() {
          this._onMouseMoveIn();
          this._updateState();
        };
        _proto._xrHoverExit = function _xrHoverExit() {
          this._onMouseMoveOut();
          if (this._pressed) {
            this._pressed = false;
            this._updateState();
          }
        };
        _proto._xrClick = function _xrClick() {
          if (!this._interactable || !this.enabledInHierarchy) {
            return;
          }
          this._pressed = true;
          this._updateState();
        };
        _proto._xrUnClick = function _xrUnClick() {
          if (!this._interactable || !this.enabledInHierarchy) {
            return;
          }
          if (this._pressed) {
            EventHandler.emitEvents(this.clickEvents, this);
            this.node.emit(EventType$4.CLICK, this);
          }
          this._pressed = false;
          this._updateState();
        };
        _createClass(Button, [{
          key: "target",
          get: function get() {
            return this._target || this.node;
          },
          set: function set(value) {
            if (this._target === value) {
              return;
            }
            if (this._target) {
              this._unregisterTargetEvent(this._target);
            }
            this._target = value;
            this._applyTarget();
          }
        }, {
          key: "interactable",
          get: function get() {
            return this._interactable;
          },
          set: function set(value) {
            if (this._interactable === value) {
              return;
            }
            this._interactable = value;
            this._updateState();
            if (!this._interactable) {
              this._resetState();
            }
          }
        }, {
          key: "_resizeToTarget",
          set: function set(value) {
            if (value) {
              this._resizeNodeToTargetNode();
            }
          }
        }, {
          key: "transition",
          get: function get() {
            return this._transition;
          },
          set: function set(value) {
            if (this._transition === value) {
              return;
            }
            if (this._transition === Transition.COLOR) {
              this._updateColorTransition(State.NORMAL);
            } else if (this._transition === Transition.SPRITE) {
              this._updateSpriteTransition(State.NORMAL);
            }
            this._transition = value;
            this._updateState();
          }
        }, {
          key: "normalColor",
          get: function get() {
            return this._normalColor;
          },
          set: function set(value) {
            if (this._normalColor === value) {
              return;
            }
            this._normalColor.set(value);
            this._updateState();
          }
        }, {
          key: "pressedColor",
          get: function get() {
            return this._pressedColor;
          },
          set: function set(value) {
            if (this._pressedColor === value) {
              return;
            }
            this._pressedColor.set(value);
          }
        }, {
          key: "hoverColor",
          get: function get() {
            return this._hoverColor;
          },
          set: function set(value) {
            if (this._hoverColor === value) {
              return;
            }
            this._hoverColor.set(value);
          }
        }, {
          key: "disabledColor",
          get: function get() {
            return this._disabledColor;
          },
          set: function set(value) {
            if (this._disabledColor === value) {
              return;
            }
            this._disabledColor.set(value);
            this._updateState();
          }
        }, {
          key: "duration",
          get: function get() {
            return this._duration;
          },
          set: function set(value) {
            if (this._duration === value) {
              return;
            }
            this._duration = value;
          }
        }, {
          key: "zoomScale",
          get: function get() {
            return this._zoomScale;
          },
          set: function set(value) {
            if (this._zoomScale === value) {
              return;
            }
            this._zoomScale = value;
          }
        }, {
          key: "normalSprite",
          get: function get() {
            return this._normalSprite;
          },
          set: function set(value) {
            if (this._normalSprite === value) {
              return;
            }
            this._normalSprite = value;
            var sprite = this.node.getComponent(Sprite);
            if (sprite) {
              sprite.spriteFrame = value;
            }
            this._updateState();
          }
        }, {
          key: "pressedSprite",
          get: function get() {
            return this._pressedSprite;
          },
          set: function set(value) {
            if (this._pressedSprite === value) {
              return;
            }
            this._pressedSprite = value;
            this._updateState();
          }
        }, {
          key: "hoverSprite",
          get: function get() {
            return this._hoverSprite;
          },
          set: function set(value) {
            if (this._hoverSprite === value) {
              return;
            }
            this._hoverSprite = value;
            this._updateState();
          }
        }, {
          key: "disabledSprite",
          get: function get() {
            return this._disabledSprite;
          },
          set: function set(value) {
            if (this._disabledSprite === value) {
              return;
            }
            this._disabledSprite = value;
            this._updateState();
          }
        }]);
        return Button;
      }(Component), _class3$a.Transition = Transition, _class3$a.EventType = EventType$4, _class3$a), (_applyDecoratedDescriptor(_class2$d.prototype, "target", [_dec4$b], Object.getOwnPropertyDescriptor(_class2$d.prototype, "target"), _class2$d.prototype), _applyDecoratedDescriptor(_class2$d.prototype, "transition", [_dec5$b], Object.getOwnPropertyDescriptor(_class2$d.prototype, "transition"), _class2$d.prototype), _applyDecoratedDescriptor(_class2$d.prototype, "normalSprite", [_dec6$5], Object.getOwnPropertyDescriptor(_class2$d.prototype, "normalSprite"), _class2$d.prototype), _applyDecoratedDescriptor(_class2$d.prototype, "pressedSprite", [_dec7$4], Object.getOwnPropertyDescriptor(_class2$d.prototype, "pressedSprite"), _class2$d.prototype), _applyDecoratedDescriptor(_class2$d.prototype, "hoverSprite", [_dec8$3], Object.getOwnPropertyDescriptor(_class2$d.prototype, "hoverSprite"), _class2$d.prototype), _applyDecoratedDescriptor(_class2$d.prototype, "disabledSprite", [_dec9$3], Object.getOwnPropertyDescriptor(_class2$d.prototype, "disabledSprite"), _class2$d.prototype), _initializer$d = applyDecoratedInitializer(_class2$d.prototype, "clickEvents", [_dec10$1, serializable$j], function () {
        return [];
      }), _initializer2$d = applyDecoratedInitializer(_class2$d.prototype, "_interactable", [serializable$j], function () {
        return true;
      }), _initializer3$b = applyDecoratedInitializer(_class2$d.prototype, "_transition", [serializable$j], function () {
        return Transition.NONE;
      }), _initializer4$a = applyDecoratedInitializer(_class2$d.prototype, "_normalColor", [serializable$j], function () {
        return Color$1.WHITE.clone();
      }), _initializer5$8 = applyDecoratedInitializer(_class2$d.prototype, "_hoverColor", [serializable$j], function () {
        return new Color$1(211, 211, 211, 255);
      }), _initializer6$5 = applyDecoratedInitializer(_class2$d.prototype, "_pressedColor", [serializable$j], function () {
        return Color$1.WHITE.clone();
      }), _initializer7$5 = applyDecoratedInitializer(_class2$d.prototype, "_disabledColor", [serializable$j], function () {
        return new Color$1(124, 124, 124, 255);
      }), _initializer8$5 = applyDecoratedInitializer(_class2$d.prototype, "_normalSprite", [serializable$j], function () {
        return null;
      }), _initializer9$5 = applyDecoratedInitializer(_class2$d.prototype, "_hoverSprite", [serializable$j], function () {
        return null;
      }), _initializer10$5 = applyDecoratedInitializer(_class2$d.prototype, "_pressedSprite", [serializable$j], function () {
        return null;
      }), _initializer11$5 = applyDecoratedInitializer(_class2$d.prototype, "_disabledSprite", [serializable$j], function () {
        return null;
      }), _initializer12$4 = applyDecoratedInitializer(_class2$d.prototype, "_duration", [serializable$j], function () {
        return 0.1;
      }), _initializer13$3 = applyDecoratedInitializer(_class2$d.prototype, "_zoomScale", [serializable$j], function () {
        return 1.2;
      }), _initializer14$2 = applyDecoratedInitializer(_class2$d.prototype, "_target", [serializable$j], function () {
        return null;
      })), _class2$d)) || _class$g) || _class$g) || _class$g));
      legacyCC.Button = Button;

      var tabIndexUtil = function () {
        function tabIndexUtil() {}
        tabIndexUtil.add = function add(editBoxImpl) {
          var list = this._tabIndexList;
          var index = list.indexOf(editBoxImpl);
          if (index === -1) {
            list.push(editBoxImpl);
          }
        };
        tabIndexUtil.remove = function remove(editBoxImpl) {
          var list = this._tabIndexList;
          var index = list.indexOf(editBoxImpl);
          if (index !== -1) {
            list.splice(index, 1);
          }
        };
        tabIndexUtil.resort = function resort() {
          this._tabIndexList.sort(function (a, b) {
            return a._delegate.tabIndex - b._delegate.tabIndex;
          });
        };
        tabIndexUtil.next = function next(editBoxImpl) {
          var list = this._tabIndexList;
          var index = list.indexOf(editBoxImpl);
          editBoxImpl.setFocus(false);
          if (index !== -1) {
            var nextImpl = list[index + 1];
            if (nextImpl && nextImpl._delegate.tabIndex >= 0) {
              nextImpl.setFocus(true);
            }
          }
        };
        return tabIndexUtil;
      }();
      tabIndexUtil._tabIndexList = [];

      var KeyboardReturnType;
      (function (KeyboardReturnType) {
        KeyboardReturnType[KeyboardReturnType["DEFAULT"] = 0] = "DEFAULT";
        KeyboardReturnType[KeyboardReturnType["DONE"] = 1] = "DONE";
        KeyboardReturnType[KeyboardReturnType["SEND"] = 2] = "SEND";
        KeyboardReturnType[KeyboardReturnType["SEARCH"] = 3] = "SEARCH";
        KeyboardReturnType[KeyboardReturnType["GO"] = 4] = "GO";
        KeyboardReturnType[KeyboardReturnType["NEXT"] = 5] = "NEXT";
      })(KeyboardReturnType || (KeyboardReturnType = {}));
      Enum(KeyboardReturnType);
      var InputMode;
      (function (InputMode) {
        InputMode[InputMode["ANY"] = 0] = "ANY";
        InputMode[InputMode["EMAIL_ADDR"] = 1] = "EMAIL_ADDR";
        InputMode[InputMode["NUMERIC"] = 2] = "NUMERIC";
        InputMode[InputMode["PHONE_NUMBER"] = 3] = "PHONE_NUMBER";
        InputMode[InputMode["URL"] = 4] = "URL";
        InputMode[InputMode["DECIMAL"] = 5] = "DECIMAL";
        InputMode[InputMode["SINGLE_LINE"] = 6] = "SINGLE_LINE";
      })(InputMode || (InputMode = {}));
      Enum(InputMode);
      var InputFlag;
      (function (InputFlag) {
        InputFlag[InputFlag["PASSWORD"] = 0] = "PASSWORD";
        InputFlag[InputFlag["SENSITIVE"] = 1] = "SENSITIVE";
        InputFlag[InputFlag["INITIAL_CAPS_WORD"] = 2] = "INITIAL_CAPS_WORD";
        InputFlag[InputFlag["INITIAL_CAPS_SENTENCE"] = 3] = "INITIAL_CAPS_SENTENCE";
        InputFlag[InputFlag["INITIAL_CAPS_ALL_CHARACTERS"] = 4] = "INITIAL_CAPS_ALL_CHARACTERS";
        InputFlag[InputFlag["DEFAULT"] = 5] = "DEFAULT";
      })(InputFlag || (InputFlag = {}));
      Enum(InputFlag);

      var EditBoxImplBase = function () {
        function EditBoxImplBase() {
          this._editing = false;
          this._delegate = null;
          this._dirtyFlag = false;
        }
        var _proto = EditBoxImplBase.prototype;
        _proto.init = function init(delegate) {};
        _proto.onEnable = function onEnable() {};
        _proto.update = function update() {};
        _proto.onDisable = function onDisable() {
          if (this._editing) {
            this.endEditing();
          }
        };
        _proto.clear = function clear() {
          this._delegate = null;
        };
        _proto.setTabIndex = function setTabIndex(index) {};
        _proto.setSize = function setSize(width, height) {};
        _proto.setFocus = function setFocus(value) {
          if (value) {
            this.beginEditing();
          } else {
            this.endEditing();
          }
        };
        _proto.isFocused = function isFocused() {
          return this._editing;
        };
        _proto.beginEditing = function beginEditing() {};
        _proto.endEditing = function endEditing() {};
        return EditBoxImplBase;
      }();

      var ccdocument = ccwindow.document;
      var SCROLLY = 40;
      var LEFT_PADDING$1 = 2;
      var DELAY_TIME = 400;
      var _matrix = new Mat4();
      var _matrix_temp = new Mat4();
      var _vec3 = new Vec3();
      var _currentEditBoxImpl = null;
      var _domCount = 0;
      var EditBoxImpl = function (_EditBoxImplBase) {
        _inheritsLoose(EditBoxImpl, _EditBoxImplBase);
        function EditBoxImpl() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _EditBoxImplBase.call.apply(_EditBoxImplBase, [this].concat(args)) || this;
          _this._delegate = null;
          _this._inputMode = -1;
          _this._inputFlag = -1;
          _this._returnType = -1;
          _this.__eventListeners = {};
          _this.__autoResize = false;
          _this.__orientationChanged = void 0;
          _this._edTxt = null;
          _this._isTextArea = false;
          _this._textLabelFont = null;
          _this._textLabelFontSize = null;
          _this._textLabelFontColor = null;
          _this._textLabelAlign = null;
          _this._placeholderLabelFont = null;
          _this._placeholderLabelFontSize = null;
          _this._placeholderLabelFontColor = null;
          _this._placeholderLabelAlign = null;
          _this._placeholderLineHeight = null;
          _this._placeholderStyleSheet = null;
          _this._domId = "EditBoxId_" + ++_domCount;
          return _this;
        }
        var _proto = EditBoxImpl.prototype;
        _proto.init = function init(delegate) {
          if (!delegate) {
            return;
          }
          this._delegate = delegate;
          if (delegate.inputMode === InputMode.ANY) {
            this._createTextArea();
          } else {
            this._createInput();
          }
          tabIndexUtil.add(this);
          this.setTabIndex(delegate.tabIndex);
          this._initStyleSheet();
          this._registerEventListeners();
          this._addDomToGameContainer();
        };
        _proto.clear = function clear() {
          this._removeEventListeners();
          this._removeDomFromGameContainer();
          tabIndexUtil.remove(this);
          if (_currentEditBoxImpl === this) {
            _currentEditBoxImpl = null;
          }
          this._delegate = null;
        };
        _proto.update = function update() {
          if (!this._dirtyFlag) return;
          this._updateMatrix();
        };
        _proto.setTabIndex = function setTabIndex(index) {
          this._edTxt.tabIndex = index;
          tabIndexUtil.resort();
        };
        _proto.setSize = function setSize(width, height) {
          var elem = this._edTxt;
          if (elem) {
            elem.style.width = width + "px";
            elem.style.height = height + "px";
          }
        };
        _proto.beginEditing = function beginEditing() {
          if (_currentEditBoxImpl && _currentEditBoxImpl !== this) {
            _currentEditBoxImpl.setFocus(false);
          }
          this._editing = true;
          _currentEditBoxImpl = this;
          this._delegate._editBoxEditingDidBegan();
          this._showDom();
          this._edTxt.focus();
        };
        _proto.endEditing = function endEditing() {
          this._edTxt.blur();
        };
        _proto._createInput = function _createInput() {
          this._isTextArea = false;
          this._edTxt = ccdocument.createElement('input');
        };
        _proto._createTextArea = function _createTextArea() {
          this._isTextArea = true;
          this._edTxt = ccdocument.createElement('textarea');
        };
        _proto._addDomToGameContainer = function _addDomToGameContainer() {
          if (game.container && this._edTxt) {
            game.container.appendChild(this._edTxt);
            ccdocument.head.appendChild(this._placeholderStyleSheet);
          }
        };
        _proto._removeDomFromGameContainer = function _removeDomFromGameContainer() {
          var hasElem = contains$1(game.container, this._edTxt);
          if (hasElem && this._edTxt) {
            game.container.removeChild(this._edTxt);
          }
          var hasStyleSheet = contains$1(ccdocument.head, this._placeholderStyleSheet);
          if (hasStyleSheet) {
            ccdocument.head.removeChild(this._placeholderStyleSheet);
          }
          this._edTxt = null;
          this._placeholderStyleSheet = null;
        };
        _proto._showDom = function _showDom() {
          this._updateMaxLength();
          this._updateInputType();
          this._updateStyleSheet();
          if (this._edTxt && this._delegate) {
            this._edTxt.style.display = '';
            this._delegate._hideLabels();
          }
          if (sys.isMobile) {
            this._showDomOnMobile();
          }
        };
        _proto._hideDom = function _hideDom() {
          var elem = this._edTxt;
          if (elem && this._delegate) {
            elem.style.display = 'none';
            this._delegate._showLabels();
          }
          if (sys.isMobile) {
            this._hideDomOnMobile();
          }
        };
        _proto._showDomOnMobile = function _showDomOnMobile() {
          if (sys.os !== OS.ANDROID && sys.os !== OS.OHOS) {
            return;
          }
          screenAdapter.handleResizeEvent = false;
          this._adjustWindowScroll();
        };
        _proto._hideDomOnMobile = function _hideDomOnMobile() {
          if (sys.os === OS.ANDROID || sys.os === OS.OHOS) {
            screenAdapter.handleResizeEvent = true;
          }
          this._scrollBackWindow();
        };
        _proto._adjustWindowScroll = function _adjustWindowScroll() {
          var _this2 = this;
          setTimeout(function () {
            if (ccwindow.scrollY < SCROLLY) {
              _this2._edTxt.scrollIntoView({
                block: 'start',
                inline: 'nearest',
                behavior: 'smooth'
              });
            }
          }, DELAY_TIME);
        };
        _proto._scrollBackWindow = function _scrollBackWindow() {
          setTimeout(function () {
            if (sys.browserType === BrowserType.WECHAT && sys.os === OS.IOS) {
              if (ccwindow.top) {
                ccwindow.top.scrollTo(0, 0);
              }
              return;
            }
            ccwindow.scrollTo(0, 0);
          }, DELAY_TIME);
        };
        _proto._updateMatrix = function _updateMatrix() {
          if (!this._edTxt) {
            return;
          }
          var node = this._delegate.node;
          var scaleX = view.getScaleX();
          var scaleY = view.getScaleY();
          var viewport = view.getViewportRect();
          var dpr = screenAdapter.devicePixelRatio;
          node.getWorldMatrix(_matrix);
          var transform = node._uiProps.uiTransformComp;
          if (transform) {
            Vec3.set(_vec3, -transform.anchorX * transform.width, -transform.anchorY * transform.height, _vec3.z);
            Mat4.transform(_matrix, _matrix, _vec3);
          }
          if (!node._uiProps.uiTransformComp) {
            return;
          }
          var camera = director.root.batcher2D.getFirstRenderCamera(node);
          if (!camera) return;
          camera.node.getWorldRT(_matrix_temp);
          var m12 = _matrix_temp.m12;
          var m13 = _matrix_temp.m13;
          var center = visibleRect.center;
          _matrix_temp.m12 = center.x - (_matrix_temp.m00 * m12 + _matrix_temp.m04 * m13);
          _matrix_temp.m13 = center.y - (_matrix_temp.m01 * m12 + _matrix_temp.m05 * m13);
          scaleX /= dpr;
          scaleY /= dpr;
          Vec3.set(_vec3, scaleX, scaleY, 1);
          Mat4.scale(_matrix_temp, _matrix_temp, _vec3);
          var container = game.container;
          var offsetX = parseInt(container && container.style.paddingLeft || '0');
          offsetX += viewport.x / dpr;
          var offsetY = parseInt(container && container.style.paddingBottom || '0');
          offsetY += viewport.y / dpr;
          _matrix_temp.m12 += offsetX;
          _matrix_temp.m13 += offsetY;
          Mat4.multiply(_matrix_temp, _matrix_temp, _matrix);
          var a = _matrix_temp.m00;
          var b = _matrix_temp.m01;
          var c = _matrix_temp.m04;
          var d = _matrix_temp.m05;
          var tx = _matrix_temp.m12;
          var ty = _matrix_temp.m13;
          var matrix = "matrix(" + a + "," + -b + "," + -c + "," + d + "," + tx + "," + -ty + ")";
          this._edTxt.style.transform = matrix;
          this._edTxt.style['-webkit-transform'] = matrix;
          this._edTxt.style['transform-origin'] = '0px 100% 0px';
          this._edTxt.style['-webkit-transform-origin'] = '0px 100% 0px';
        };
        _proto._updateInputType = function _updateInputType() {
          var delegate = this._delegate;
          var inputMode = delegate.inputMode;
          var inputFlag = delegate.inputFlag;
          var returnType = delegate.returnType;
          var elem = this._edTxt;
          if (this._inputMode === inputMode && this._inputFlag === inputFlag && this._returnType === returnType) {
            return;
          }
          this._inputMode = inputMode;
          this._inputFlag = inputFlag;
          this._returnType = returnType;
          if (this._isTextArea) {
            var transform = 'none';
            if (inputFlag === InputFlag.INITIAL_CAPS_ALL_CHARACTERS) {
              transform = 'uppercase';
            } else if (inputFlag === InputFlag.INITIAL_CAPS_WORD) {
              transform = 'capitalize';
            }
            elem.style.textTransform = transform;
            return;
          }
          elem = elem;
          if (inputFlag === InputFlag.PASSWORD) {
            elem.type = 'password';
            elem.style.textTransform = 'none';
            return;
          }
          var type = elem.type;
          if (inputMode === InputMode.EMAIL_ADDR) {
            type = 'email';
          } else if (inputMode === InputMode.NUMERIC || inputMode === InputMode.DECIMAL) {
            type = 'number';
          } else if (inputMode === InputMode.PHONE_NUMBER) {
            type = 'number';
            elem.pattern = '[0-9]*';
            elem.addEventListener('wheel', function () {
              return false;
            });
          } else if (inputMode === InputMode.URL) {
            type = 'url';
          } else {
            type = 'text';
            if (returnType === KeyboardReturnType.SEARCH) {
              type = 'search';
            }
          }
          elem.type = type;
          var textTransform = 'none';
          if (inputFlag === InputFlag.INITIAL_CAPS_ALL_CHARACTERS) {
            textTransform = 'uppercase';
          } else if (inputFlag === InputFlag.INITIAL_CAPS_WORD) {
            textTransform = 'capitalize';
          }
          elem.style.textTransform = textTransform;
        };
        _proto._updateMaxLength = function _updateMaxLength() {
          var maxLength = this._delegate.maxLength;
          if (maxLength < 0) {
            maxLength = 65535;
          }
          this._edTxt.maxLength = maxLength;
        };
        _proto._initStyleSheet = function _initStyleSheet() {
          if (!this._edTxt) {
            return;
          }
          var elem = this._edTxt;
          elem.style.color = '#000000';
          elem.style.border = '0px';
          elem.style.background = 'transparent';
          elem.style.width = '100%';
          elem.style.height = '100%';
          elem.style.outline = 'medium';
          elem.style.padding = '0';
          elem.style.textTransform = 'none';
          elem.style.display = 'none';
          elem.style.position = 'absolute';
          elem.style.bottom = '0px';
          elem.style.left = LEFT_PADDING$1 + "px";
          elem.className = 'cocosEditBox';
          elem.style.fontFamily = 'Arial';
          elem.id = this._domId;
          if (!this._isTextArea) {
            elem = elem;
            elem.type = 'text';
            elem.style['-moz-appearance'] = 'textfield';
          } else {
            elem.style.resize = 'none';
            elem.style.overflowY = 'scroll';
          }
          this._placeholderStyleSheet = ccdocument.createElement('style');
        };
        _proto._updateStyleSheet = function _updateStyleSheet() {
          var delegate = this._delegate;
          var elem = this._edTxt;
          if (elem && delegate) {
            elem.value = delegate.string;
            this._updateTextLabel(delegate.textLabel);
          }
        };
        _proto._updateTextLabel = function _updateTextLabel(textLabel) {
          if (!textLabel) {
            return;
          }
          var font = textLabel.font;
          if (font && !(font instanceof BitmapFont)) {
            font = font._fontFamily;
          } else {
            font = textLabel.fontFamily;
          }
          var fontSize = textLabel.fontSize * textLabel.node.scale.y;
          if (this._textLabelFont === font && this._textLabelFontSize === fontSize && this._textLabelFontColor === textLabel.fontColor && this._textLabelAlign === textLabel.horizontalAlign) {
            return;
          }
          this._textLabelFont = font;
          this._textLabelFontSize = fontSize;
          this._textLabelFontColor = textLabel.fontColor;
          this._textLabelAlign = textLabel.horizontalAlign;
          if (!this._edTxt) {
            return;
          }
          var elem = this._edTxt;
          elem.style.fontSize = fontSize + "px";
          elem.style.color = textLabel.color.toCSS();
          elem.style.fontFamily = font;
          switch (textLabel.horizontalAlign) {
            case Label.HorizontalAlign.LEFT:
              elem.style.textAlign = 'left';
              break;
            case Label.HorizontalAlign.CENTER:
              elem.style.textAlign = 'center';
              break;
            case Label.HorizontalAlign.RIGHT:
              elem.style.textAlign = 'right';
              break;
          }
        };
        _proto._updatePlaceholderLabel = function _updatePlaceholderLabel(placeholderLabel) {
          if (!placeholderLabel) {
            return;
          }
          var font = placeholderLabel.font;
          if (font && !(font instanceof BitmapFont)) {
            font = placeholderLabel.font._fontFamily;
          } else {
            font = placeholderLabel.fontFamily;
          }
          var fontSize = placeholderLabel.fontSize * placeholderLabel.node.scale.y;
          if (this._placeholderLabelFont === font && this._placeholderLabelFontSize === fontSize && this._placeholderLabelFontColor === placeholderLabel.fontColor && this._placeholderLabelAlign === placeholderLabel.horizontalAlign && this._placeholderLineHeight === placeholderLabel.fontSize) {
            return;
          }
          this._placeholderLabelFont = font;
          this._placeholderLabelFontSize = fontSize;
          this._placeholderLabelFontColor = placeholderLabel.fontColor;
          this._placeholderLabelAlign = placeholderLabel.horizontalAlign;
          this._placeholderLineHeight = placeholderLabel.fontSize;
          var styleEl = this._placeholderStyleSheet;
          var fontColor = placeholderLabel.color.toCSS();
          var lineHeight = placeholderLabel.fontSize;
          var horizontalAlign = '';
          switch (placeholderLabel.horizontalAlign) {
            case Label.HorizontalAlign.LEFT:
              horizontalAlign = 'left';
              break;
            case Label.HorizontalAlign.CENTER:
              horizontalAlign = 'center';
              break;
            case Label.HorizontalAlign.RIGHT:
              horizontalAlign = 'right';
              break;
          }
          styleEl.innerHTML = "#" + this._domId + "::-webkit-input-placeholder{text-transform: initial;-family: " + font + ";font-size: " + fontSize + "px;color: " + fontColor + ";line-height: " + lineHeight + "px;text-align: " + horizontalAlign + ";}" + ("#" + this._domId + "::-moz-placeholder{text-transform: initial;-family: " + font + ";font-size: " + fontSize + "px;color: " + fontColor + ";line-height: " + lineHeight + "px;text-align: " + horizontalAlign + ";}") + ("#" + this._domId + "::-ms-input-placeholder{text-transform: initial;-family: " + font + ";font-size: " + fontSize + "px;color: " + fontColor + ";line-height: " + lineHeight + "px;text-align: " + horizontalAlign + ";}");
          if (sys.browserType === BrowserType.EDGE) {
            styleEl.innerHTML += "#" + this._domId + "::-ms-clear{display: none;}";
          }
        };
        _proto._registerEventListeners = function _registerEventListeners() {
          var _this3 = this;
          if (!this._edTxt) {
            return;
          }
          var elem = this._edTxt;
          var inputLock = false;
          var cbs = this.__eventListeners;
          cbs.compositionStart = function () {
            inputLock = true;
          };
          cbs.compositionEnd = function () {
            inputLock = false;
            _this3._delegate._editBoxTextChanged(elem.value);
          };
          cbs.onInput = function () {
            if (inputLock) {
              return;
            }
            var delegate = _this3._delegate;
            var maxLength = delegate.maxLength;
            if (maxLength >= 0) {
              elem.value = elem.value.slice(0, maxLength);
            }
            delegate._editBoxTextChanged(elem.value);
          };
          cbs.onClick = function () {
            if (_this3._editing) {
              if (sys.isMobile) {
                _this3._adjustWindowScroll();
              }
            }
          };
          cbs.onKeydown = function (e) {
            if (e.keyCode === KeyCode.ENTER) {
              e.propagationStopped = true;
              _this3._delegate._editBoxEditingReturn();
              if (!_this3._isTextArea) {
                elem.blur();
              }
            } else if (e.keyCode === KeyCode.TAB) {
              e.propagationStopped = true;
              e.preventDefault();
              tabIndexUtil.next(_this3);
            }
          };
          cbs.onBlur = function () {
            if (sys.isMobile && inputLock) {
              cbs.compositionEnd();
            }
            _this3._editing = false;
            _currentEditBoxImpl = null;
            _this3._hideDom();
            _this3._delegate._editBoxEditingDidEnded();
          };
          elem.addEventListener('compositionstart', cbs.compositionStart);
          elem.addEventListener('compositionend', cbs.compositionEnd);
          elem.addEventListener('input', cbs.onInput);
          elem.addEventListener('keydown', cbs.onKeydown);
          elem.addEventListener('blur', cbs.onBlur);
          elem.addEventListener('touchstart', cbs.onClick);
        };
        _proto._removeEventListeners = function _removeEventListeners() {
          if (!this._edTxt) {
            return;
          }
          var elem = this._edTxt;
          var cbs = this.__eventListeners;
          elem.removeEventListener('compositionstart', cbs.compositionStart);
          elem.removeEventListener('compositionend', cbs.compositionEnd);
          elem.removeEventListener('input', cbs.onInput);
          elem.removeEventListener('keydown', cbs.onKeydown);
          elem.removeEventListener('blur', cbs.onBlur);
          elem.removeEventListener('touchstart', cbs.onClick);
          cbs.compositionStart = null;
          cbs.compositionEnd = null;
          cbs.onInput = null;
          cbs.onKeydown = null;
          cbs.onBlur = null;
          cbs.onClick = null;
        };
        return EditBoxImpl;
      }(EditBoxImplBase);

      var _dec$f, _dec2$e, _dec3$d, _dec4$a, _dec5$a, _dec6$4, _dec7$3, _dec8$2, _dec9$2, _dec10, _dec11, _dec12, _dec13, _class$f, _class2$c, _initializer$c, _initializer2$c, _initializer3$a, _initializer4$9, _initializer5$7, _initializer6$4, _initializer7$4, _initializer8$4, _initializer9$4, _initializer10$4, _initializer11$4, _initializer12$3, _initializer13$2, _class3$9;
      var LEFT_PADDING = 2;
      function capitalize(str) {
        return str.replace(/(?:^|\s)\S/g, function (a) {
          return a.toUpperCase();
        });
      }
      function capitalizeFirstLetter(str) {
        return str.charAt(0).toUpperCase() + str.slice(1);
      }
      var EventType$3;
      (function (EventType) {
        EventType["EDITING_DID_BEGAN"] = "editing-did-began";
        EventType["EDITING_DID_ENDED"] = "editing-did-ended";
        EventType["TEXT_CHANGED"] = "text-changed";
        EventType["EDITING_RETURN"] = "editing-return";
        EventType["XR_EDITING_DID_BEGAN"] = "xr-editing-did-began";
        EventType["XR_EDITING_DID_ENDED"] = "xr-editing-did-ended";
      })(EventType$3 || (EventType$3 = {}));
      var EditBox = exports('fl', (_dec$f = ccclass$n('cc.EditBox'), _dec2$e = executionOrder$1(110), _dec3$d = requireComponent(UITransform), _dec4$a = type$7(Label), _dec5$a = type$7(Label), _dec6$4 = type$7(SpriteFrame), _dec7$3 = type$7(InputFlag), _dec8$2 = type$7(InputMode), _dec9$2 = type$7(KeyboardReturnType), _dec10 = type$7([EventHandler]), _dec11 = type$7([EventHandler]), _dec12 = type$7([EventHandler]), _dec13 = type$7([EventHandler]), _dec$f(_class$f = _dec2$e(_class$f = _dec3$d(_class$f = (_class2$c = (_class3$9 = function (_Component) {
        _inheritsLoose(EditBox, _Component);
        function EditBox() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Component.call.apply(_Component, [this].concat(args)) || this;
          _this.editingDidBegan = _initializer$c && _initializer$c();
          _this.textChanged = _initializer2$c && _initializer2$c();
          _this.editingDidEnded = _initializer3$a && _initializer3$a();
          _this.editingReturn = _initializer4$9 && _initializer4$9();
          _this._impl = null;
          _this._background = null;
          _this._textLabel = _initializer5$7 && _initializer5$7();
          _this._placeholderLabel = _initializer6$4 && _initializer6$4();
          _this._returnType = _initializer7$4 && _initializer7$4();
          _this._string = _initializer8$4 && _initializer8$4();
          _this._tabIndex = _initializer9$4 && _initializer9$4();
          _this._backgroundImage = _initializer10$4 && _initializer10$4();
          _this._inputFlag = _initializer11$4 && _initializer11$4();
          _this._inputMode = _initializer12$3 && _initializer12$3();
          _this._maxLength = _initializer13$2 && _initializer13$2();
          _this._isLabelVisible = false;
          return _this;
        }
        var _proto = EditBox.prototype;
        _proto.__preload = function __preload() {
          this._init();
        };
        _proto.onEnable = function onEnable() {
          {
            this._registerEvent();
          }
          this._ensureBackgroundSprite();
          if (this._impl) {
            this._impl.onEnable();
          }
        };
        _proto.update = function update() {
          if (this._impl) {
            this._impl.update();
          }
        };
        _proto.onDisable = function onDisable() {
          {
            this._unregisterEvent();
          }
          this._unregisterBackgroundEvent();
          if (this._impl) {
            this._impl.onDisable();
          }
        };
        _proto.onDestroy = function onDestroy() {
          if (this._impl) {
            this._impl.clear();
          }
        };
        _proto.setFocus = function setFocus() {
          if (this._impl) {
            this._impl.setFocus(true);
          }
        };
        _proto.focus = function focus() {
          if (this._impl) {
            this._impl.setFocus(true);
          }
        };
        _proto.blur = function blur() {
          if (this._impl) {
            this._impl.setFocus(false);
          }
        };
        _proto.isFocused = function isFocused() {
          if (this._impl) {
            return this._impl.isFocused();
          }
          return false;
        };
        _proto._editBoxEditingDidBegan = function _editBoxEditingDidBegan() {
          EventHandler.emitEvents(this.editingDidBegan, this);
          this.node.emit(EventType$3.EDITING_DID_BEGAN, this);
          if (this._impl) {
            this._impl._dirtyFlag = true;
          }
        };
        _proto._editBoxEditingDidEnded = function _editBoxEditingDidEnded(text) {
          EventHandler.emitEvents(this.editingDidEnded, this);
          this.node.emit(EventType$3.EDITING_DID_ENDED, this, text);
          if (this._impl) {
            this._impl._dirtyFlag = false;
          }
        };
        _proto._editBoxTextChanged = function _editBoxTextChanged(text) {
          text = this._updateLabelStringStyle(text, true);
          this.string = text;
          EventHandler.emitEvents(this.textChanged, text, this);
          this.node.emit(EventType$3.TEXT_CHANGED, this);
        };
        _proto._editBoxEditingReturn = function _editBoxEditingReturn(text) {
          EventHandler.emitEvents(this.editingReturn, this);
          this.node.emit(EventType$3.EDITING_RETURN, this, text);
        };
        _proto._showLabels = function _showLabels() {
          this._isLabelVisible = true;
          this._updateLabels();
        };
        _proto._hideLabels = function _hideLabels() {
          this._isLabelVisible = false;
          if (this._textLabel) {
            this._textLabel.node.active = false;
          }
          if (this._placeholderLabel) {
            this._placeholderLabel.node.active = false;
          }
        };
        _proto._onTouchBegan = function _onTouchBegan(event) {
          event.propagationStopped = true;
        };
        _proto._onTouchCancel = function _onTouchCancel(event) {
          event.propagationStopped = true;
        };
        _proto._onTouchEnded = function _onTouchEnded(event) {
          if (this._impl) {
            this._impl.beginEditing();
          }
          event.propagationStopped = true;
        };
        _proto._init = function _init() {
          this._updatePlaceholderLabel();
          this._updateTextLabel();
          this._isLabelVisible = true;
          this.node.on(NodeEventType.SIZE_CHANGED, this._resizeChildNodes, this);
          var impl = this._impl = new EditBox._EditBoxImpl();
          impl.init(this);
          this._updateString(this._string);
          this._syncSize();
        };
        _proto._ensureBackgroundSprite = function _ensureBackgroundSprite() {
          if (!this._background) {
            var background = this.node.getComponent(Sprite);
            if (!background) {
              background = this.node.addComponent(Sprite);
            }
            if (background !== this._background) {
              background.type = Sprite.Type.SLICED;
              background.spriteFrame = this._backgroundImage;
              this._background = background;
              this._registerBackgroundEvent();
            }
          }
        };
        _proto._updateTextLabel = function _updateTextLabel() {
          var textLabel = this._textLabel;
          if (!textLabel) {
            var node = this.node.getChildByName('TEXT_LABEL');
            if (!node) {
              node = new Node$1('TEXT_LABEL');
              node.layer = this.node.layer;
            }
            textLabel = node.getComponent(Label);
            if (!textLabel) {
              textLabel = node.addComponent(Label);
            }
            node.parent = this.node;
            this._textLabel = textLabel;
          }
          if (this._inputMode === InputMode.ANY) {
            textLabel.verticalAlign = VerticalTextAlignment.TOP;
            textLabel.enableWrapText = true;
          } else {
            textLabel.enableWrapText = false;
          }
          textLabel.string = this._updateLabelStringStyle(this._string);
        };
        _proto._updatePlaceholderLabel = function _updatePlaceholderLabel() {
          var placeholderLabel = this._placeholderLabel;
          if (!placeholderLabel) {
            var node = this.node.getChildByName('PLACEHOLDER_LABEL');
            if (!node) {
              node = new Node$1('PLACEHOLDER_LABEL');
              node.layer = this.node.layer;
            }
            placeholderLabel = node.getComponent(Label);
            if (!placeholderLabel) {
              placeholderLabel = node.addComponent(Label);
            }
            node.parent = this.node;
            this._placeholderLabel = placeholderLabel;
          }
          if (this._inputMode === InputMode.ANY) {
            placeholderLabel.enableWrapText = true;
          } else {
            placeholderLabel.enableWrapText = false;
          }
          placeholderLabel.string = this.placeholder;
        };
        _proto._syncSize = function _syncSize() {
          var trans = this.node._uiProps.uiTransformComp;
          var size = trans.contentSize;
          if (this._background) {
            var bgTrans = this._background.node._uiProps.uiTransformComp;
            bgTrans.anchorPoint = trans.anchorPoint;
            bgTrans.setContentSize(size);
          }
          this._updateLabelPosition(size);
          if (this._impl) {
            this._impl.setSize(size.width, size.height);
          }
        };
        _proto._updateLabels = function _updateLabels() {
          if (this._isLabelVisible) {
            var content = this._string;
            if (this._textLabel) {
              this._textLabel.node.active = content !== '';
            }
            if (this._placeholderLabel) {
              this._placeholderLabel.node.active = content === '';
            }
          }
        };
        _proto._updateString = function _updateString(text) {
          var textLabel = this._textLabel;
          if (!textLabel) {
            return;
          }
          var displayText = text;
          if (displayText) {
            displayText = this._updateLabelStringStyle(displayText);
          }
          textLabel.string = displayText;
          this._updateLabels();
        };
        _proto._updateLabelStringStyle = function _updateLabelStringStyle(text, ignorePassword) {
          if (ignorePassword === void 0) {
            ignorePassword = false;
          }
          var inputFlag = this._inputFlag;
          if (!ignorePassword && inputFlag === InputFlag.PASSWORD) {
            var passwordString = '';
            var len = text.length;
            for (var i = 0; i < len; ++i) {
              passwordString += "\u25CF";
            }
            text = passwordString;
          } else if (inputFlag === InputFlag.INITIAL_CAPS_ALL_CHARACTERS) {
            text = text.toUpperCase();
          } else if (inputFlag === InputFlag.INITIAL_CAPS_WORD) {
            text = capitalize(text);
          } else if (inputFlag === InputFlag.INITIAL_CAPS_SENTENCE) {
            text = capitalizeFirstLetter(text);
          }
          return text;
        };
        _proto._registerEvent = function _registerEvent() {
          this.node.on(NodeEventType.TOUCH_START, this._onTouchBegan, this);
          this.node.on(NodeEventType.TOUCH_END, this._onTouchEnded, this);
          this.node.on(XrUIPressEventType.XRUI_UNCLICK, this._xrUnClick, this);
          this.node.on(XrKeyboardEventType.XR_KEYBOARD_INPUT, this._xrKeyBoardInput, this);
        };
        _proto._unregisterEvent = function _unregisterEvent() {
          this.node.off(NodeEventType.TOUCH_START, this._onTouchBegan, this);
          this.node.off(NodeEventType.TOUCH_END, this._onTouchEnded, this);
          this.node.off(XrUIPressEventType.XRUI_UNCLICK, this._xrUnClick, this);
          this.node.off(XrKeyboardEventType.XR_KEYBOARD_INPUT, this._xrKeyBoardInput, this);
        };
        _proto._onBackgroundSpriteFrameChanged = function _onBackgroundSpriteFrameChanged() {
          if (!this._background) {
            return;
          }
          this.backgroundImage = this._background.spriteFrame;
        };
        _proto._registerBackgroundEvent = function _registerBackgroundEvent() {
          var node = this._background && this._background.node;
          node === null || node === void 0 ? void 0 : node.on(Sprite.EventType.SPRITE_FRAME_CHANGED, this._onBackgroundSpriteFrameChanged, this);
        };
        _proto._unregisterBackgroundEvent = function _unregisterBackgroundEvent() {
          var node = this._background && this._background.node;
          node === null || node === void 0 ? void 0 : node.off(Sprite.EventType.SPRITE_FRAME_CHANGED, this._onBackgroundSpriteFrameChanged, this);
        };
        _proto._updateLabelPosition = function _updateLabelPosition(size) {
          var trans = this.node._uiProps.uiTransformComp;
          var offX = -trans.anchorX * trans.width;
          var offY = -trans.anchorY * trans.height;
          var placeholderLabel = this._placeholderLabel;
          var textLabel = this._textLabel;
          if (textLabel) {
            textLabel.node._uiProps.uiTransformComp.setContentSize(size.width - LEFT_PADDING, size.height);
            textLabel.node.setPosition(offX + LEFT_PADDING, offY + size.height, textLabel.node.position.z);
            if (this._inputMode === InputMode.ANY) {
              textLabel.verticalAlign = VerticalTextAlignment.TOP;
            }
            textLabel.enableWrapText = this._inputMode === InputMode.ANY;
          }
          if (placeholderLabel) {
            placeholderLabel.node._uiProps.uiTransformComp.setContentSize(size.width - LEFT_PADDING, size.height);
            placeholderLabel.lineHeight = size.height;
            placeholderLabel.node.setPosition(offX + LEFT_PADDING, offY + size.height, placeholderLabel.node.position.z);
            placeholderLabel.enableWrapText = this._inputMode === InputMode.ANY;
          }
        };
        _proto._resizeChildNodes = function _resizeChildNodes() {
          var trans = this.node._uiProps.uiTransformComp;
          var textLabelNode = this._textLabel && this._textLabel.node;
          if (textLabelNode) {
            textLabelNode.setPosition(-trans.width / 2, trans.height / 2, textLabelNode.position.z);
            textLabelNode._uiProps.uiTransformComp.setContentSize(trans.contentSize);
          }
          var placeholderLabelNode = this._placeholderLabel && this._placeholderLabel.node;
          if (placeholderLabelNode) {
            placeholderLabelNode.setPosition(-trans.width / 2, trans.height / 2, placeholderLabelNode.position.z);
            placeholderLabelNode._uiProps.uiTransformComp.setContentSize(trans.contentSize);
          }
          var backgroundNode = this._background && this._background.node;
          if (backgroundNode) {
            backgroundNode._uiProps.uiTransformComp.setContentSize(trans.contentSize);
          }
          this._syncSize();
        };
        _proto._xrUnClick = function _xrUnClick() {
          this.node.emit(EventType$3.XR_EDITING_DID_BEGAN, this._maxLength, this.string);
        };
        _proto._xrKeyBoardInput = function _xrKeyBoardInput(str) {
          this.string = str;
        };
        _createClass(EditBox, [{
          key: "string",
          get: function get() {
            return this._string;
          },
          set: function set(value) {
            if (this._maxLength >= 0 && value.length >= this._maxLength) {
              value = value.slice(0, this._maxLength);
            }
            if (this._string === value) {
              return;
            }
            this._string = value;
            this._updateString(value);
          }
        }, {
          key: "placeholder",
          get: function get() {
            if (!this._placeholderLabel) {
              return '';
            }
            return this._placeholderLabel.string;
          },
          set: function set(value) {
            if (this._placeholderLabel) {
              this._placeholderLabel.string = value;
            }
          }
        }, {
          key: "textLabel",
          get: function get() {
            return this._textLabel;
          },
          set: function set(oldValue) {
            if (this._textLabel !== oldValue) {
              this._textLabel = oldValue;
              if (this._textLabel) {
                this._updateTextLabel();
                this._updateLabels();
              }
            }
          }
        }, {
          key: "placeholderLabel",
          get: function get() {
            return this._placeholderLabel;
          },
          set: function set(oldValue) {
            if (this._placeholderLabel !== oldValue) {
              this._placeholderLabel = oldValue;
              if (this._placeholderLabel) {
                this._updatePlaceholderLabel();
                this._updateLabels();
              }
            }
          }
        }, {
          key: "backgroundImage",
          get: function get() {
            return this._backgroundImage;
          },
          set: function set(value) {
            if (this._backgroundImage === value) {
              return;
            }
            this._backgroundImage = value;
            this._ensureBackgroundSprite();
            this._background.spriteFrame = value;
          }
        }, {
          key: "inputFlag",
          get: function get() {
            return this._inputFlag;
          },
          set: function set(value) {
            if (this._inputFlag === value) {
              return;
            }
            this._inputFlag = value;
            this._updateString(this._string);
          }
        }, {
          key: "inputMode",
          get: function get() {
            return this._inputMode;
          },
          set: function set(oldValue) {
            if (this._inputMode !== oldValue) {
              this._inputMode = oldValue;
              this._updateTextLabel();
              this._updatePlaceholderLabel();
            }
          }
        }, {
          key: "returnType",
          get: function get() {
            return this._returnType;
          },
          set: function set(value) {
            this._returnType = value;
          }
        }, {
          key: "maxLength",
          get: function get() {
            return this._maxLength;
          },
          set: function set(value) {
            this._maxLength = value;
          }
        }, {
          key: "tabIndex",
          get: function get() {
            return this._tabIndex;
          },
          set: function set(value) {
            if (this._tabIndex !== value) {
              this._tabIndex = value;
              if (this._impl) {
                this._impl.setTabIndex(value);
              }
            }
          }
        }]);
        return EditBox;
      }(Component), _class3$9._EditBoxImpl = EditBoxImplBase, _class3$9.KeyboardReturnType = KeyboardReturnType, _class3$9.InputFlag = InputFlag, _class3$9.InputMode = InputMode, _class3$9.EventType = EventType$3, _class3$9), (_applyDecoratedDescriptor(_class2$c.prototype, "textLabel", [_dec4$a], Object.getOwnPropertyDescriptor(_class2$c.prototype, "textLabel"), _class2$c.prototype), _applyDecoratedDescriptor(_class2$c.prototype, "placeholderLabel", [_dec5$a], Object.getOwnPropertyDescriptor(_class2$c.prototype, "placeholderLabel"), _class2$c.prototype), _applyDecoratedDescriptor(_class2$c.prototype, "backgroundImage", [_dec6$4], Object.getOwnPropertyDescriptor(_class2$c.prototype, "backgroundImage"), _class2$c.prototype), _applyDecoratedDescriptor(_class2$c.prototype, "inputFlag", [_dec7$3], Object.getOwnPropertyDescriptor(_class2$c.prototype, "inputFlag"), _class2$c.prototype), _applyDecoratedDescriptor(_class2$c.prototype, "inputMode", [_dec8$2], Object.getOwnPropertyDescriptor(_class2$c.prototype, "inputMode"), _class2$c.prototype), _applyDecoratedDescriptor(_class2$c.prototype, "returnType", [_dec9$2], Object.getOwnPropertyDescriptor(_class2$c.prototype, "returnType"), _class2$c.prototype), _initializer$c = applyDecoratedInitializer(_class2$c.prototype, "editingDidBegan", [_dec10, serializable$j], function () {
        return [];
      }), _initializer2$c = applyDecoratedInitializer(_class2$c.prototype, "textChanged", [_dec11, serializable$j], function () {
        return [];
      }), _initializer3$a = applyDecoratedInitializer(_class2$c.prototype, "editingDidEnded", [_dec12, serializable$j], function () {
        return [];
      }), _initializer4$9 = applyDecoratedInitializer(_class2$c.prototype, "editingReturn", [_dec13, serializable$j], function () {
        return [];
      }), _initializer5$7 = applyDecoratedInitializer(_class2$c.prototype, "_textLabel", [serializable$j], function () {
        return null;
      }), _initializer6$4 = applyDecoratedInitializer(_class2$c.prototype, "_placeholderLabel", [serializable$j], function () {
        return null;
      }), _initializer7$4 = applyDecoratedInitializer(_class2$c.prototype, "_returnType", [serializable$j], function () {
        return KeyboardReturnType.DEFAULT;
      }), _initializer8$4 = applyDecoratedInitializer(_class2$c.prototype, "_string", [serializable$j], function () {
        return '';
      }), _initializer9$4 = applyDecoratedInitializer(_class2$c.prototype, "_tabIndex", [serializable$j], function () {
        return 0;
      }), _initializer10$4 = applyDecoratedInitializer(_class2$c.prototype, "_backgroundImage", [serializable$j], function () {
        return null;
      }), _initializer11$4 = applyDecoratedInitializer(_class2$c.prototype, "_inputFlag", [serializable$j], function () {
        return InputFlag.DEFAULT;
      }), _initializer12$3 = applyDecoratedInitializer(_class2$c.prototype, "_inputMode", [serializable$j], function () {
        return InputMode.ANY;
      }), _initializer13$2 = applyDecoratedInitializer(_class2$c.prototype, "_maxLength", [serializable$j], function () {
        return 20;
      })), _class2$c)) || _class$f) || _class$f) || _class$f));
      if (typeof window === 'object' && typeof document === 'object' && !MINIGAME && !JSB && !RUNTIME_BASED) {
        EditBox._EditBoxImpl = EditBoxImpl;
      }
      legacyCC.internal.EditBox = EditBox;

      var _dec$e, _dec2$d, _dec3$c, _dec4$9, _dec5$9, _dec6$3, _dec7$2, _dec8$1, _dec9$1, _class$e, _class2$b, _initializer$b, _initializer2$b, _initializer3$9, _initializer4$8, _initializer5$6, _initializer6$3, _initializer7$3, _initializer8$3, _initializer9$3, _initializer10$3, _initializer11$3, _initializer12$2, _initializer13$1, _initializer14$1, _initializer15$1, _initializer16$1, _class3$8;
      var Type;
      (function (Type) {
        Type[Type["NONE"] = 0] = "NONE";
        Type[Type["HORIZONTAL"] = 1] = "HORIZONTAL";
        Type[Type["VERTICAL"] = 2] = "VERTICAL";
        Type[Type["GRID"] = 3] = "GRID";
      })(Type || (Type = {}));
      ccenum(Type);
      var ResizeMode;
      (function (ResizeMode) {
        ResizeMode[ResizeMode["NONE"] = 0] = "NONE";
        ResizeMode[ResizeMode["CONTAINER"] = 1] = "CONTAINER";
        ResizeMode[ResizeMode["CHILDREN"] = 2] = "CHILDREN";
      })(ResizeMode || (ResizeMode = {}));
      ccenum(ResizeMode);
      var AxisDirection;
      (function (AxisDirection) {
        AxisDirection[AxisDirection["HORIZONTAL"] = 0] = "HORIZONTAL";
        AxisDirection[AxisDirection["VERTICAL"] = 1] = "VERTICAL";
      })(AxisDirection || (AxisDirection = {}));
      ccenum(AxisDirection);
      var VerticalDirection;
      (function (VerticalDirection) {
        VerticalDirection[VerticalDirection["BOTTOM_TO_TOP"] = 0] = "BOTTOM_TO_TOP";
        VerticalDirection[VerticalDirection["TOP_TO_BOTTOM"] = 1] = "TOP_TO_BOTTOM";
      })(VerticalDirection || (VerticalDirection = {}));
      ccenum(VerticalDirection);
      var HorizontalDirection;
      (function (HorizontalDirection) {
        HorizontalDirection[HorizontalDirection["LEFT_TO_RIGHT"] = 0] = "LEFT_TO_RIGHT";
        HorizontalDirection[HorizontalDirection["RIGHT_TO_LEFT"] = 1] = "RIGHT_TO_LEFT";
      })(HorizontalDirection || (HorizontalDirection = {}));
      ccenum(HorizontalDirection);
      var Constraint;
      (function (Constraint) {
        Constraint[Constraint["NONE"] = 0] = "NONE";
        Constraint[Constraint["FIXED_ROW"] = 1] = "FIXED_ROW";
        Constraint[Constraint["FIXED_COL"] = 2] = "FIXED_COL";
      })(Constraint || (Constraint = {}));
      ccenum(Constraint);
      var _tempVec3$2 = new Vec3();
      var Layout = exports('fm', (_dec$e = ccclass$n('cc.Layout'), _dec2$d = executionOrder$1(110), _dec3$c = requireComponent(UITransform), _dec4$9 = type$7(Type), _dec5$9 = type$7(ResizeMode), _dec6$3 = type$7(AxisDirection), _dec7$2 = type$7(VerticalDirection), _dec8$1 = type$7(HorizontalDirection), _dec9$1 = type$7(Constraint), _dec$e(_class$e = _dec2$d(_class$e = _dec3$c(_class$e = (_class2$b = (_class3$8 = function (_Component) {
        _inheritsLoose(Layout, _Component);
        function Layout() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Component.call.apply(_Component, [this].concat(args)) || this;
          _this._resizeMode = _initializer$b && _initializer$b();
          _this._layoutType = _initializer2$b && _initializer2$b();
          _this._cellSize = _initializer3$9 && _initializer3$9();
          _this._startAxis = _initializer4$8 && _initializer4$8();
          _this._paddingLeft = _initializer5$6 && _initializer5$6();
          _this._paddingRight = _initializer6$3 && _initializer6$3();
          _this._paddingTop = _initializer7$3 && _initializer7$3();
          _this._paddingBottom = _initializer8$3 && _initializer8$3();
          _this._spacingX = _initializer9$3 && _initializer9$3();
          _this._spacingY = _initializer10$3 && _initializer10$3();
          _this._verticalDirection = _initializer11$3 && _initializer11$3();
          _this._horizontalDirection = _initializer12$2 && _initializer12$2();
          _this._constraint = _initializer13$1 && _initializer13$1();
          _this._constraintNum = _initializer14$1 && _initializer14$1();
          _this._affectedByScale = _initializer15$1 && _initializer15$1();
          _this._isAlign = _initializer16$1 && _initializer16$1();
          _this._layoutSize = new Size$1(300, 200);
          _this._layoutDirty = true;
          _this._childrenDirty = false;
          _this._usefulLayoutObj = [];
          _this._init = false;
          return _this;
        }
        var _proto = Layout.prototype;
        _proto.updateLayout = function updateLayout(force) {
          if (force === void 0) {
            force = false;
          }
          if (this._layoutDirty || force) {
            this._doLayout();
            this._layoutDirty = false;
          }
        };
        _proto.onEnable = function onEnable() {
          this._addEventListeners();
          var trans = this.node._uiProps.uiTransformComp;
          if (trans.contentSize.equals(Size$1.ZERO)) {
            trans.setContentSize(this._layoutSize);
          }
          this._childrenChanged();
        };
        _proto.onDisable = function onDisable() {
          this._usefulLayoutObj.length = 0;
          this._removeEventListeners();
        };
        _proto._checkUsefulObj = function _checkUsefulObj() {
          this._usefulLayoutObj.length = 0;
          var children = this.node.children;
          for (var i = 0; i < children.length; ++i) {
            var child = children[i];
            var uiTrans = child._uiProps.uiTransformComp;
            if (child.activeInHierarchy && uiTrans) {
              this._usefulLayoutObj.push(uiTrans);
            }
          }
        };
        _proto._addEventListeners = function _addEventListeners() {
          director.on(Director.EVENT_AFTER_UPDATE, this.updateLayout, this);
          this.node.on(NodeEventType.SIZE_CHANGED, this._resized, this);
          this.node.on(NodeEventType.ANCHOR_CHANGED, this._doLayoutDirty, this);
          this.node.on(NodeEventType.CHILD_ADDED, this._childAdded, this);
          this.node.on(NodeEventType.CHILD_REMOVED, this._childRemoved, this);
          this.node.on(NodeEventType.SIBLING_ORDER_CHANGED, this._childrenChanged, this);
          this.node.on('childrenSiblingOrderChanged', this.updateLayout, this);
          this._addChildrenEventListeners();
        };
        _proto._removeEventListeners = function _removeEventListeners() {
          director.off(Director.EVENT_AFTER_UPDATE, this.updateLayout, this);
          this.node.off(NodeEventType.SIZE_CHANGED, this._resized, this);
          this.node.off(NodeEventType.ANCHOR_CHANGED, this._doLayoutDirty, this);
          this.node.off(NodeEventType.CHILD_ADDED, this._childAdded, this);
          this.node.off(NodeEventType.CHILD_REMOVED, this._childRemoved, this);
          this.node.off(NodeEventType.SIBLING_ORDER_CHANGED, this._childrenChanged, this);
          this.node.off('childrenSiblingOrderChanged', this.updateLayout, this);
          this._removeChildrenEventListeners();
        };
        _proto._addChildrenEventListeners = function _addChildrenEventListeners() {
          var children = this.node.children;
          for (var i = 0; i < children.length; ++i) {
            var child = children[i];
            child.on(NodeEventType.SIZE_CHANGED, this._doLayoutDirty, this);
            child.on(NodeEventType.TRANSFORM_CHANGED, this._transformDirty, this);
            child.on(NodeEventType.ANCHOR_CHANGED, this._doLayoutDirty, this);
            child.on(NodeEventType.ACTIVE_IN_HIERARCHY_CHANGED, this._childrenChanged, this);
          }
        };
        _proto._removeChildrenEventListeners = function _removeChildrenEventListeners() {
          var children = this.node.children;
          for (var i = 0; i < children.length; ++i) {
            var child = children[i];
            child.off(NodeEventType.SIZE_CHANGED, this._doLayoutDirty, this);
            child.off(NodeEventType.TRANSFORM_CHANGED, this._transformDirty, this);
            child.off(NodeEventType.ANCHOR_CHANGED, this._doLayoutDirty, this);
            child.off(NodeEventType.ACTIVE_IN_HIERARCHY_CHANGED, this._childrenChanged, this);
          }
        };
        _proto._childAdded = function _childAdded(child) {
          child.on(NodeEventType.SIZE_CHANGED, this._doLayoutDirty, this);
          child.on(NodeEventType.TRANSFORM_CHANGED, this._transformDirty, this);
          child.on(NodeEventType.ANCHOR_CHANGED, this._doLayoutDirty, this);
          child.on(NodeEventType.ACTIVE_IN_HIERARCHY_CHANGED, this._childrenChanged, this);
          this._childrenChanged();
        };
        _proto._childRemoved = function _childRemoved(child) {
          child.off(NodeEventType.SIZE_CHANGED, this._doLayoutDirty, this);
          child.off(NodeEventType.TRANSFORM_CHANGED, this._transformDirty, this);
          child.off(NodeEventType.ANCHOR_CHANGED, this._doLayoutDirty, this);
          child.off(NodeEventType.ACTIVE_IN_HIERARCHY_CHANGED, this._childrenChanged, this);
          this._childrenChanged();
        };
        _proto._resized = function _resized() {
          this._layoutSize.set(this.node._uiProps.uiTransformComp.contentSize);
          this._doLayoutDirty();
        };
        _proto._doLayoutHorizontally = function _doLayoutHorizontally(baseWidth, rowBreak, fnPositionY, applyChildren) {
          var trans = this.node._uiProps.uiTransformComp;
          var layoutAnchor = trans.anchorPoint;
          var limit = this._getFixedBreakingNum();
          var sign = 1;
          var paddingX = this._paddingLeft;
          if (this._horizontalDirection === HorizontalDirection.RIGHT_TO_LEFT) {
            sign = -1;
            paddingX = this._paddingRight;
          }
          var startPos = (this._horizontalDirection - layoutAnchor.x) * baseWidth + sign * paddingX;
          var nextX = startPos - sign * this._spacingX;
          var totalHeight = 0;
          var rowMaxHeight = 0;
          var tempMaxHeight = 0;
          var maxHeight = 0;
          var isBreak = false;
          var activeChildCount = this._usefulLayoutObj.length;
          var newChildWidth = this._cellSize.width;
          var paddingH = this._getPaddingH();
          if (this._layoutType !== Type.GRID && this._resizeMode === ResizeMode.CHILDREN) {
            newChildWidth = (baseWidth - paddingH - (activeChildCount - 1) * this._spacingX) / activeChildCount;
          }
          var children = this._usefulLayoutObj;
          for (var i = 0; i < children.length; ++i) {
            var childTrans = children[i];
            var child = childTrans.node;
            var scale = child.scale;
            var childScaleX = this._getUsedScaleValue(scale.x);
            var childScaleY = this._getUsedScaleValue(scale.y);
            if (this._resizeMode === ResizeMode.CHILDREN) {
              childTrans.width = newChildWidth / childScaleX;
              if (this._layoutType === Type.GRID) {
                childTrans.height = this._cellSize.height / childScaleY;
              }
            }
            var anchorX = Math.abs(this._horizontalDirection - childTrans.anchorX);
            var childBoundingBoxWidth = childTrans.width * childScaleX;
            var childBoundingBoxHeight = childTrans.height * childScaleY;
            if (childBoundingBoxHeight > tempMaxHeight) {
              maxHeight = Math.max(tempMaxHeight, maxHeight);
              rowMaxHeight = tempMaxHeight || childBoundingBoxHeight;
              tempMaxHeight = childBoundingBoxHeight;
            }
            nextX += sign * (anchorX * childBoundingBoxWidth + this._spacingX);
            var rightBoundaryOfChild = sign * (1 - anchorX) * childBoundingBoxWidth;
            if (rowBreak) {
              if (limit > 0) {
                isBreak = i / limit > 0 && i % limit === 0;
                if (isBreak) {
                  rowMaxHeight = tempMaxHeight > childBoundingBoxHeight ? tempMaxHeight : rowMaxHeight;
                }
              } else if (childBoundingBoxWidth > baseWidth - paddingH) {
                if (nextX > startPos + sign * (anchorX * childBoundingBoxWidth)) {
                  isBreak = true;
                }
              } else {
                var boundary = (1 - this._horizontalDirection - layoutAnchor.x) * baseWidth;
                var rowBreakBoundary = nextX + rightBoundaryOfChild + sign * (sign > 0 ? this._paddingRight : this._paddingLeft);
                isBreak = Math.abs(rowBreakBoundary) > Math.abs(boundary);
              }
              if (isBreak) {
                nextX = startPos + sign * (anchorX * childBoundingBoxWidth);
                if (childBoundingBoxHeight !== tempMaxHeight) {
                  rowMaxHeight = tempMaxHeight;
                }
                totalHeight += rowMaxHeight + this._spacingY;
                rowMaxHeight = tempMaxHeight = childBoundingBoxHeight;
              }
            }
            var finalPositionY = fnPositionY(child, childTrans, totalHeight);
            if (applyChildren) {
              child.setPosition(nextX, finalPositionY);
            }
            nextX += rightBoundaryOfChild;
          }
          rowMaxHeight = Math.max(rowMaxHeight, tempMaxHeight);
          var containerResizeBoundary = Math.max(maxHeight, totalHeight + rowMaxHeight) + this._getPaddingV();
          return containerResizeBoundary;
        };
        _proto._doLayoutVertically = function _doLayoutVertically(baseHeight, columnBreak, fnPositionX, applyChildren) {
          var trans = this.node._uiProps.uiTransformComp;
          var layoutAnchor = trans.anchorPoint;
          var limit = this._getFixedBreakingNum();
          var sign = 1;
          var paddingY = this._paddingBottom;
          if (this._verticalDirection === VerticalDirection.TOP_TO_BOTTOM) {
            sign = -1;
            paddingY = this._paddingTop;
          }
          var startPos = (this._verticalDirection - layoutAnchor.y) * baseHeight + sign * paddingY;
          var nextY = startPos - sign * this._spacingY;
          var tempMaxWidth = 0;
          var maxWidth = 0;
          var colMaxWidth = 0;
          var totalWidth = 0;
          var isBreak = false;
          var activeChildCount = this._usefulLayoutObj.length;
          var newChildHeight = this._cellSize.height;
          var paddingV = this._getPaddingV();
          if (this._layoutType !== Type.GRID && this._resizeMode === ResizeMode.CHILDREN) {
            newChildHeight = (baseHeight - paddingV - (activeChildCount - 1) * this._spacingY) / activeChildCount;
          }
          var children = this._usefulLayoutObj;
          for (var i = 0; i < children.length; ++i) {
            var childTrans = children[i];
            var child = childTrans.node;
            var scale = child.scale;
            var childScaleX = this._getUsedScaleValue(scale.x);
            var childScaleY = this._getUsedScaleValue(scale.y);
            if (this._resizeMode === ResizeMode.CHILDREN) {
              childTrans.height = newChildHeight / childScaleY;
              if (this._layoutType === Type.GRID) {
                childTrans.width = this._cellSize.width / childScaleX;
              }
            }
            var anchorY = Math.abs(this._verticalDirection - childTrans.anchorY);
            var childBoundingBoxWidth = childTrans.width * childScaleX;
            var childBoundingBoxHeight = childTrans.height * childScaleY;
            if (childBoundingBoxWidth > tempMaxWidth) {
              maxWidth = Math.max(tempMaxWidth, maxWidth);
              colMaxWidth = tempMaxWidth || childBoundingBoxWidth;
              tempMaxWidth = childBoundingBoxWidth;
            }
            nextY += sign * (anchorY * childBoundingBoxHeight + this._spacingY);
            var topBoundaryOfChild = sign * (1 - anchorY) * childBoundingBoxHeight;
            if (columnBreak) {
              if (limit > 0) {
                isBreak = i / limit > 0 && i % limit === 0;
                if (isBreak) {
                  colMaxWidth = tempMaxWidth > childBoundingBoxHeight ? tempMaxWidth : colMaxWidth;
                }
              } else if (childBoundingBoxHeight > baseHeight - paddingV) {
                if (nextY > startPos + sign * (anchorY * childBoundingBoxHeight)) {
                  isBreak = true;
                }
              } else {
                var boundary = (1 - this._verticalDirection - layoutAnchor.y) * baseHeight;
                var columnBreakBoundary = nextY + topBoundaryOfChild + sign * (sign > 0 ? this._paddingTop : this._paddingBottom);
                isBreak = Math.abs(columnBreakBoundary) > Math.abs(boundary);
              }
              if (isBreak) {
                nextY = startPos + sign * (anchorY * childBoundingBoxHeight);
                if (childBoundingBoxWidth !== tempMaxWidth) {
                  colMaxWidth = tempMaxWidth;
                }
                totalWidth += colMaxWidth + this._spacingX;
                colMaxWidth = tempMaxWidth = childBoundingBoxWidth;
              }
            }
            var finalPositionX = fnPositionX(child, childTrans, totalWidth);
            if (applyChildren) {
              child.getPosition(_tempVec3$2);
              child.setPosition(finalPositionX, nextY, _tempVec3$2.z);
            }
            nextY += topBoundaryOfChild;
          }
          colMaxWidth = Math.max(colMaxWidth, tempMaxWidth);
          var containerResizeBoundary = Math.max(maxWidth, totalWidth + colMaxWidth) + this._getPaddingH();
          return containerResizeBoundary;
        };
        _proto._doLayoutGridAxisHorizontal = function _doLayoutGridAxisHorizontal(layoutAnchor, layoutSize) {
          var _this2 = this;
          var baseWidth = layoutSize.width;
          var sign = 1;
          var bottomBoundaryOfLayout = -layoutAnchor.y * layoutSize.height;
          var paddingY = this._paddingBottom;
          if (this._verticalDirection === VerticalDirection.TOP_TO_BOTTOM) {
            sign = -1;
            bottomBoundaryOfLayout = (1 - layoutAnchor.y) * layoutSize.height;
            paddingY = this._paddingTop;
          }
          var fnPositionY = function fnPositionY(child, childTrans, topOffset) {
            return bottomBoundaryOfLayout + sign * (topOffset + (1 - childTrans.anchorY) * childTrans.height * _this2._getUsedScaleValue(child.scale.y) + paddingY);
          };
          var newHeight = 0;
          if (this._resizeMode === ResizeMode.CONTAINER) {
            newHeight = this._doLayoutHorizontally(baseWidth, true, fnPositionY, false);
            bottomBoundaryOfLayout = -layoutAnchor.y * newHeight;
            if (this._verticalDirection === VerticalDirection.TOP_TO_BOTTOM) {
              sign = -1;
              bottomBoundaryOfLayout = (1 - layoutAnchor.y) * newHeight;
            }
          }
          this._doLayoutHorizontally(baseWidth, true, fnPositionY, true);
          if (this._resizeMode === ResizeMode.CONTAINER) {
            this.node._uiProps.uiTransformComp.setContentSize(baseWidth, newHeight);
          }
        };
        _proto._doLayoutGridAxisVertical = function _doLayoutGridAxisVertical(layoutAnchor, layoutSize) {
          var _this3 = this;
          var baseHeight = layoutSize.height;
          var sign = 1;
          var leftBoundaryOfLayout = -layoutAnchor.x * layoutSize.width;
          var paddingX = this._paddingLeft;
          if (this._horizontalDirection === HorizontalDirection.RIGHT_TO_LEFT) {
            sign = -1;
            leftBoundaryOfLayout = (1 - layoutAnchor.x) * layoutSize.width;
            paddingX = this._paddingRight;
          }
          var fnPositionX = function fnPositionX(child, childTrans, leftOffset) {
            return leftBoundaryOfLayout + sign * (leftOffset + (1 - childTrans.anchorX) * childTrans.width * _this3._getUsedScaleValue(child.scale.x) + paddingX);
          };
          var newWidth = 0;
          if (this._resizeMode === ResizeMode.CONTAINER) {
            newWidth = this._doLayoutVertically(baseHeight, true, fnPositionX, false);
            leftBoundaryOfLayout = -layoutAnchor.x * newWidth;
            if (this._horizontalDirection === HorizontalDirection.RIGHT_TO_LEFT) {
              sign = -1;
              leftBoundaryOfLayout = (1 - layoutAnchor.x) * newWidth;
            }
          }
          this._doLayoutVertically(baseHeight, true, fnPositionX, true);
          if (this._resizeMode === ResizeMode.CONTAINER) {
            this.node._uiProps.uiTransformComp.setContentSize(newWidth, baseHeight);
          }
        };
        _proto._doLayoutGrid = function _doLayoutGrid() {
          var trans = this.node._uiProps.uiTransformComp;
          var layoutAnchor = trans.anchorPoint;
          var layoutSize = trans.contentSize;
          if (this.startAxis === AxisDirection.HORIZONTAL) {
            this._doLayoutGridAxisHorizontal(layoutAnchor, layoutSize);
          } else if (this.startAxis === AxisDirection.VERTICAL) {
            this._doLayoutGridAxisVertical(layoutAnchor, layoutSize);
          }
        };
        _proto._getHorizontalBaseWidth = function _getHorizontalBaseWidth(horizontal) {
          var children = this._usefulLayoutObj;
          var baseSize = 0;
          var activeChildCount = children.length;
          if (this._resizeMode === ResizeMode.CONTAINER) {
            for (var i = 0; i < children.length; ++i) {
              var childTrans = children[i];
              var child = childTrans.node;
              var scale = child.scale;
              baseSize += childTrans.width * this._getUsedScaleValue(scale.x);
            }
            baseSize += (activeChildCount - 1) * this._spacingX + this._getPaddingH();
          } else {
            baseSize = this.node._uiProps.uiTransformComp.width;
          }
          return baseSize;
        };
        _proto._getVerticalBaseHeight = function _getVerticalBaseHeight() {
          var children = this._usefulLayoutObj;
          var baseSize = 0;
          var activeChildCount = children.length;
          if (this._resizeMode === ResizeMode.CONTAINER) {
            for (var i = 0; i < children.length; ++i) {
              var childTrans = children[i];
              var child = childTrans.node;
              var scale = child.scale;
              baseSize += childTrans.height * this._getUsedScaleValue(scale.y);
            }
            baseSize += (activeChildCount - 1) * this._spacingY + this._getPaddingV();
          } else {
            baseSize = this.node._uiProps.uiTransformComp.height;
          }
          return baseSize;
        };
        _proto._doLayout = function _doLayout() {
          var _this4 = this;
          if (!this._init || this._childrenDirty) {
            this._checkUsefulObj();
            this._init = true;
            this._childrenDirty = false;
          }
          if (this._layoutType === Type.HORIZONTAL) {
            var newWidth = this._getHorizontalBaseWidth();
            var fnPositionY = function fnPositionY(child) {
              var pos = _this4._isAlign ? Vec3.ZERO : child.position;
              return pos.y;
            };
            this._doLayoutHorizontally(newWidth, false, fnPositionY, true);
            this.node._uiProps.uiTransformComp.width = newWidth;
          } else if (this._layoutType === Type.VERTICAL) {
            var newHeight = this._getVerticalBaseHeight();
            var fnPositionX = function fnPositionX(child) {
              var pos = _this4._isAlign ? Vec3.ZERO : child.position;
              return pos.x;
            };
            this._doLayoutVertically(newHeight, false, fnPositionX, true);
            this.node._uiProps.uiTransformComp.height = newHeight;
          } else if (this._layoutType === Type.GRID) {
            this._doLayoutGrid();
          }
        };
        _proto._getUsedScaleValue = function _getUsedScaleValue(value) {
          return this._affectedByScale ? Math.abs(value) : 1;
        };
        _proto._transformDirty = function _transformDirty(type) {
          if (!(type & TransformBit.SCALE) || !(type & TransformBit.POSITION) || !this._affectedByScale) {
            return;
          }
          this._doLayoutDirty();
        };
        _proto._doLayoutDirty = function _doLayoutDirty() {
          this._layoutDirty = true;
        };
        _proto._childrenChanged = function _childrenChanged() {
          this._childrenDirty = true;
          this._doLayoutDirty();
        };
        _proto._getPaddingH = function _getPaddingH() {
          return this._paddingLeft + this._paddingRight;
        };
        _proto._getPaddingV = function _getPaddingV() {
          return this._paddingTop + this._paddingBottom;
        };
        _proto._getFixedBreakingNum = function _getFixedBreakingNum() {
          if (this._layoutType !== Type.GRID || this._constraint === Constraint.NONE || this._constraintNum <= 0) {
            return 0;
          }
          var num = this._constraint === Constraint.FIXED_ROW ? Math.ceil(this._usefulLayoutObj.length / this._constraintNum) : this._constraintNum;
          if (this._startAxis === AxisDirection.VERTICAL) {
            num = this._constraint === Constraint.FIXED_COL ? Math.ceil(this._usefulLayoutObj.length / this._constraintNum) : this._constraintNum;
          }
          return num;
        };
        _createClass(Layout, [{
          key: "alignHorizontal",
          get: function get() {
            return this._isAlign;
          },
          set: function set(value) {
            if (this._layoutType !== Type.HORIZONTAL) {
              return;
            }
            this._isAlign = value;
            this._doLayoutDirty();
          }
        }, {
          key: "alignVertical",
          get: function get() {
            return this._isAlign;
          },
          set: function set(value) {
            if (this._layoutType !== Type.VERTICAL) {
              return;
            }
            this._isAlign = value;
            this._doLayoutDirty();
          }
        }, {
          key: "type",
          get: function get() {
            return this._layoutType;
          },
          set: function set(value) {
            this._layoutType = value;
            this._doLayoutDirty();
          }
        }, {
          key: "resizeMode",
          get: function get() {
            return this._resizeMode;
          },
          set: function set(value) {
            if (this._layoutType === Type.NONE) {
              return;
            }
            this._resizeMode = value;
            this._doLayoutDirty();
          }
        }, {
          key: "cellSize",
          get: function get() {
            return this._cellSize;
          },
          set: function set(value) {
            if (this._cellSize === value) {
              return;
            }
            this._cellSize.set(value);
            this._doLayoutDirty();
          }
        }, {
          key: "startAxis",
          get: function get() {
            return this._startAxis;
          },
          set: function set(value) {
            if (this._startAxis === value) {
              return;
            }
            this._startAxis = value;
            this._doLayoutDirty();
          }
        }, {
          key: "paddingLeft",
          get: function get() {
            return this._paddingLeft;
          },
          set: function set(value) {
            if (this._paddingLeft === value) {
              return;
            }
            this._paddingLeft = value;
            this._doLayoutDirty();
          }
        }, {
          key: "paddingRight",
          get: function get() {
            return this._paddingRight;
          },
          set: function set(value) {
            if (this._paddingRight === value) {
              return;
            }
            this._paddingRight = value;
            this._doLayoutDirty();
          }
        }, {
          key: "paddingTop",
          get: function get() {
            return this._paddingTop;
          },
          set: function set(value) {
            if (this._paddingTop === value) {
              return;
            }
            this._paddingTop = value;
            this._doLayoutDirty();
          }
        }, {
          key: "paddingBottom",
          get: function get() {
            return this._paddingBottom;
          },
          set: function set(value) {
            if (this._paddingBottom === value) {
              return;
            }
            this._paddingBottom = value;
            this._doLayoutDirty();
          }
        }, {
          key: "spacingX",
          get: function get() {
            return this._spacingX;
          },
          set: function set(value) {
            if (this._spacingX === value) {
              return;
            }
            this._spacingX = value;
            this._doLayoutDirty();
          }
        }, {
          key: "spacingY",
          get: function get() {
            return this._spacingY;
          },
          set: function set(value) {
            if (this._spacingY === value) {
              return;
            }
            this._spacingY = value;
            this._doLayoutDirty();
          }
        }, {
          key: "verticalDirection",
          get: function get() {
            return this._verticalDirection;
          },
          set: function set(value) {
            if (this._verticalDirection === value) {
              return;
            }
            this._verticalDirection = value;
            this._doLayoutDirty();
          }
        }, {
          key: "horizontalDirection",
          get: function get() {
            return this._horizontalDirection;
          },
          set: function set(value) {
            if (this._horizontalDirection === value) {
              return;
            }
            this._horizontalDirection = value;
            this._doLayoutDirty();
          }
        }, {
          key: "padding",
          get: function get() {
            return this._paddingLeft;
          },
          set: function set(value) {
            if (this.paddingLeft !== value || this._paddingRight !== value || this._paddingTop !== value || this._paddingBottom !== value) {
              this._paddingLeft = this._paddingRight = this._paddingTop = this._paddingBottom = value;
              this._doLayoutDirty();
            }
          }
        }, {
          key: "constraint",
          get: function get() {
            return this._constraint;
          },
          set: function set(value) {
            if (this._layoutType === Type.NONE || this._constraint === value) {
              return;
            }
            this._constraint = value;
            this._doLayoutDirty();
          }
        }, {
          key: "constraintNum",
          get: function get() {
            return this._constraintNum;
          },
          set: function set(value) {
            if (this._constraint === Constraint.NONE || this._constraintNum === value) {
              return;
            }
            if (value <= 0) {
              warn('Limit values to be greater than 0');
            }
            this._constraintNum = value;
            this._doLayoutDirty();
          }
        }, {
          key: "affectedByScale",
          get: function get() {
            return this._affectedByScale;
          },
          set: function set(value) {
            this._affectedByScale = value;
            this._doLayoutDirty();
          }
        }]);
        return Layout;
      }(Component), _class3$8.Type = Type, _class3$8.VerticalDirection = VerticalDirection, _class3$8.HorizontalDirection = HorizontalDirection, _class3$8.ResizeMode = ResizeMode, _class3$8.AxisDirection = AxisDirection, _class3$8.Constraint = Constraint, _class3$8), (_applyDecoratedDescriptor(_class2$b.prototype, "type", [_dec4$9], Object.getOwnPropertyDescriptor(_class2$b.prototype, "type"), _class2$b.prototype), _applyDecoratedDescriptor(_class2$b.prototype, "resizeMode", [_dec5$9], Object.getOwnPropertyDescriptor(_class2$b.prototype, "resizeMode"), _class2$b.prototype), _applyDecoratedDescriptor(_class2$b.prototype, "startAxis", [_dec6$3], Object.getOwnPropertyDescriptor(_class2$b.prototype, "startAxis"), _class2$b.prototype), _applyDecoratedDescriptor(_class2$b.prototype, "verticalDirection", [_dec7$2], Object.getOwnPropertyDescriptor(_class2$b.prototype, "verticalDirection"), _class2$b.prototype), _applyDecoratedDescriptor(_class2$b.prototype, "horizontalDirection", [_dec8$1], Object.getOwnPropertyDescriptor(_class2$b.prototype, "horizontalDirection"), _class2$b.prototype), _applyDecoratedDescriptor(_class2$b.prototype, "constraint", [_dec9$1], Object.getOwnPropertyDescriptor(_class2$b.prototype, "constraint"), _class2$b.prototype), _initializer$b = applyDecoratedInitializer(_class2$b.prototype, "_resizeMode", [serializable$j], function () {
        return ResizeMode.NONE;
      }), _initializer2$b = applyDecoratedInitializer(_class2$b.prototype, "_layoutType", [serializable$j], function () {
        return Type.NONE;
      }), _initializer3$9 = applyDecoratedInitializer(_class2$b.prototype, "_cellSize", [serializable$j], function () {
        return new Size$1(40, 40);
      }), _initializer4$8 = applyDecoratedInitializer(_class2$b.prototype, "_startAxis", [serializable$j], function () {
        return AxisDirection.HORIZONTAL;
      }), _initializer5$6 = applyDecoratedInitializer(_class2$b.prototype, "_paddingLeft", [serializable$j], function () {
        return 0;
      }), _initializer6$3 = applyDecoratedInitializer(_class2$b.prototype, "_paddingRight", [serializable$j], function () {
        return 0;
      }), _initializer7$3 = applyDecoratedInitializer(_class2$b.prototype, "_paddingTop", [serializable$j], function () {
        return 0;
      }), _initializer8$3 = applyDecoratedInitializer(_class2$b.prototype, "_paddingBottom", [serializable$j], function () {
        return 0;
      }), _initializer9$3 = applyDecoratedInitializer(_class2$b.prototype, "_spacingX", [serializable$j], function () {
        return 0;
      }), _initializer10$3 = applyDecoratedInitializer(_class2$b.prototype, "_spacingY", [serializable$j], function () {
        return 0;
      }), _initializer11$3 = applyDecoratedInitializer(_class2$b.prototype, "_verticalDirection", [serializable$j], function () {
        return VerticalDirection.TOP_TO_BOTTOM;
      }), _initializer12$2 = applyDecoratedInitializer(_class2$b.prototype, "_horizontalDirection", [serializable$j], function () {
        return HorizontalDirection.LEFT_TO_RIGHT;
      }), _initializer13$1 = applyDecoratedInitializer(_class2$b.prototype, "_constraint", [serializable$j], function () {
        return Constraint.NONE;
      }), _initializer14$1 = applyDecoratedInitializer(_class2$b.prototype, "_constraintNum", [serializable$j], function () {
        return 2;
      }), _initializer15$1 = applyDecoratedInitializer(_class2$b.prototype, "_affectedByScale", [serializable$j], function () {
        return false;
      }), _initializer16$1 = applyDecoratedInitializer(_class2$b.prototype, "_isAlign", [serializable$j], function () {
        return false;
      })), _class2$b)) || _class$e) || _class$e) || _class$e));
      legacyCC.Layout = Layout;

      var _dec$d, _dec2$c, _dec3$b, _dec4$8, _dec5$8, _class$d, _class2$a, _initializer$a, _initializer2$a, _initializer3$8, _initializer4$7, _initializer5$5, _class3$7;
      var Mode;
      (function (Mode) {
        Mode[Mode["HORIZONTAL"] = 0] = "HORIZONTAL";
        Mode[Mode["VERTICAL"] = 1] = "VERTICAL";
        Mode[Mode["FILLED"] = 2] = "FILLED";
      })(Mode || (Mode = {}));
      Enum(Mode);
      var ProgressBar = exports('fn', (_dec$d = ccclass$n('cc.ProgressBar'), _dec2$c = executionOrder$1(110), _dec3$b = requireComponent(UITransform), _dec4$8 = type$7(Sprite), _dec5$8 = type$7(Mode), _dec$d(_class$d = _dec2$c(_class$d = _dec3$b(_class$d = (_class2$a = (_class3$7 = function (_Component) {
        _inheritsLoose(ProgressBar, _Component);
        function ProgressBar() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Component.call.apply(_Component, [this].concat(args)) || this;
          _this._barSprite = _initializer$a && _initializer$a();
          _this._mode = _initializer2$a && _initializer2$a();
          _this._totalLength = _initializer3$8 && _initializer3$8();
          _this._progress = _initializer4$7 && _initializer4$7();
          _this._reverse = _initializer5$5 && _initializer5$5();
          return _this;
        }
        var _proto = ProgressBar.prototype;
        _proto._initBarSprite = function _initBarSprite() {
          if (this._barSprite) {
            var entity = this._barSprite.node;
            if (!entity) {
              return;
            }
            var trans = this.node._uiProps.uiTransformComp;
            var nodeSize = trans.contentSize;
            var nodeAnchor = trans.anchorPoint;
            var barSpriteSize = entity._uiProps.uiTransformComp.contentSize;
            if (this._barSprite.fillType === Sprite.FillType.RADIAL) {
              this._mode = Mode.FILLED;
            }
            if (this._mode === Mode.HORIZONTAL) {
              this.totalLength = barSpriteSize.width;
            } else if (this._mode === Mode.VERTICAL) {
              this.totalLength = barSpriteSize.height;
            } else {
              this.totalLength = this._barSprite.fillRange;
            }
            if (entity.parent === this.node) {
              var x = -nodeSize.width * nodeAnchor.x;
              entity.setPosition(x, 0, 0);
            }
          }
        };
        _proto._updateBarStatus = function _updateBarStatus() {
          if (this._barSprite) {
            var entity = this._barSprite.node;
            if (!entity) {
              return;
            }
            var entTrans = entity._uiProps.uiTransformComp;
            var entityAnchorPoint = entTrans.anchorPoint;
            var entitySize = entTrans.contentSize;
            var entityPosition = entity.getPosition();
            var anchorPoint = new Vec2(0, 0.5);
            var progress = clamp01(this._progress);
            var actualLenth = this._totalLength * progress;
            var finalContentSize = entitySize;
            var totalWidth = 0;
            var totalHeight = 0;
            switch (this._mode) {
              case Mode.HORIZONTAL:
                if (this._reverse) {
                  anchorPoint = new Vec2(1, 0.5);
                }
                finalContentSize = new Size$1(actualLenth, entitySize.height);
                totalWidth = this._totalLength;
                totalHeight = entitySize.height;
                break;
              case Mode.VERTICAL:
                if (this._reverse) {
                  anchorPoint = new Vec2(0.5, 1);
                } else {
                  anchorPoint = new Vec2(0.5, 0);
                }
                finalContentSize = new Size$1(entitySize.width, actualLenth);
                totalWidth = entitySize.width;
                totalHeight = this._totalLength;
                break;
            }
            if (this._mode === Mode.FILLED) {
              if (this._barSprite.type !== Sprite.Type.FILLED) {
                warn('ProgressBar FILLED mode only works when barSprite\'s Type is FILLED!');
              } else {
                if (this._reverse) {
                  actualLenth *= -1;
                }
                this._barSprite.fillRange = actualLenth;
              }
            } else if (this._barSprite.type !== Sprite.Type.FILLED) {
              var anchorOffsetX = anchorPoint.x - entityAnchorPoint.x;
              var anchorOffsetY = anchorPoint.y - entityAnchorPoint.y;
              var finalPosition = new Vec3(totalWidth * anchorOffsetX, totalHeight * anchorOffsetY, 0);
              entity.setPosition(entityPosition.x + finalPosition.x, entityPosition.y + finalPosition.y, entityPosition.z);
              entTrans.setAnchorPoint(anchorPoint);
              entTrans.setContentSize(finalContentSize);
            } else {
              warn('ProgressBar non-FILLED mode only works when barSprite\'s Type is non-FILLED!');
            }
          }
        };
        _createClass(ProgressBar, [{
          key: "barSprite",
          get: function get() {
            return this._barSprite;
          },
          set: function set(value) {
            if (this._barSprite === value) {
              return;
            }
            this._barSprite = value;
            this._initBarSprite();
          }
        }, {
          key: "mode",
          get: function get() {
            return this._mode;
          },
          set: function set(value) {
            if (this._mode === value) {
              return;
            }
            this._mode = value;
            if (this._barSprite) {
              var entity = this._barSprite.node;
              if (!entity) {
                return;
              }
              var entitySize = entity._uiProps.uiTransformComp.contentSize;
              if (this._mode === Mode.HORIZONTAL) {
                this.totalLength = entitySize.width;
              } else if (this._mode === Mode.VERTICAL) {
                this.totalLength = entitySize.height;
              } else if (this._mode === Mode.FILLED) {
                this.totalLength = this._barSprite.fillRange;
              }
            }
          }
        }, {
          key: "totalLength",
          get: function get() {
            return this._totalLength;
          },
          set: function set(value) {
            if (this._mode === Mode.FILLED) {
              value = clamp01(value);
            }
            if (this._totalLength === value) {
              return;
            }
            this._totalLength = value;
            this._updateBarStatus();
          }
        }, {
          key: "progress",
          get: function get() {
            return this._progress;
          },
          set: function set(value) {
            if (this._progress === value) {
              return;
            }
            this._progress = value;
            this._updateBarStatus();
          }
        }, {
          key: "reverse",
          get: function get() {
            return this._reverse;
          },
          set: function set(value) {
            if (this._reverse === value) {
              return;
            }
            this._reverse = value;
            if (this._barSprite) {
              this._barSprite.fillStart = 1 - this._barSprite.fillStart;
            }
            this._updateBarStatus();
          }
        }]);
        return ProgressBar;
      }(Component), _class3$7.Mode = Mode, _class3$7), (_applyDecoratedDescriptor(_class2$a.prototype, "barSprite", [_dec4$8], Object.getOwnPropertyDescriptor(_class2$a.prototype, "barSprite"), _class2$a.prototype), _applyDecoratedDescriptor(_class2$a.prototype, "mode", [_dec5$8], Object.getOwnPropertyDescriptor(_class2$a.prototype, "mode"), _class2$a.prototype), _initializer$a = applyDecoratedInitializer(_class2$a.prototype, "_barSprite", [serializable$j], function () {
        return null;
      }), _initializer2$a = applyDecoratedInitializer(_class2$a.prototype, "_mode", [serializable$j], function () {
        return Mode.HORIZONTAL;
      }), _initializer3$8 = applyDecoratedInitializer(_class2$a.prototype, "_totalLength", [serializable$j], function () {
        return 1;
      }), _initializer4$7 = applyDecoratedInitializer(_class2$a.prototype, "_progress", [serializable$j], function () {
        return 0.1;
      }), _initializer5$5 = applyDecoratedInitializer(_class2$a.prototype, "_reverse", [serializable$j], function () {
        return false;
      })), _class2$a)) || _class$d) || _class$d) || _class$d));
      legacyCC.ProgressBar = ProgressBar;

      var _dec$c, _dec2$b, _dec3$a, _dec4$7, _dec5$7, _class$c, _class2$9, _initializer$9, _initializer2$9, _initializer3$7, _initializer4$6, _initializer5$4, _class3$6;
      var GETTING_SHORTER_FACTOR = 20;
      var _tempPos_1 = new Vec3();
      var _tempPos_2 = new Vec3();
      var _tempVec3$1 = new Vec3();
      var defaultAnchor = new Vec2();
      var _tempColor = new Color$1();
      var _tempVec2$2 = new Vec2();
      var Direction$3;
      (function (Direction) {
        Direction[Direction["HORIZONTAL"] = 0] = "HORIZONTAL";
        Direction[Direction["VERTICAL"] = 1] = "VERTICAL";
      })(Direction$3 || (Direction$3 = {}));
      ccenum(Direction$3);
      var ScrollBar = exports('fo', (_dec$c = ccclass$n('cc.ScrollBar'), _dec2$b = executionOrder$1(110), _dec3$a = requireComponent(UITransform), _dec4$7 = type$7(Sprite), _dec5$7 = type$7(Direction$3), _dec$c(_class$c = _dec2$b(_class$c = _dec3$a(_class$c = (_class2$9 = (_class3$6 = function (_Component) {
        _inheritsLoose(ScrollBar, _Component);
        function ScrollBar() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Component.call.apply(_Component, [this].concat(args)) || this;
          _this._scrollView = _initializer$9 && _initializer$9();
          _this._handle = _initializer2$9 && _initializer2$9();
          _this._direction = _initializer3$7 && _initializer3$7();
          _this._enableAutoHide = _initializer4$6 && _initializer4$6();
          _this._autoHideTime = _initializer5$4 && _initializer5$4();
          _this._touching = false;
          _this._opacity = 255;
          _this._autoHideRemainingTime = 0;
          return _this;
        }
        var _proto = ScrollBar.prototype;
        _proto.hide = function hide() {
          this._autoHideRemainingTime = 0;
          this._setOpacity(0);
        };
        _proto.show = function show() {
          this._autoHideRemainingTime = this._autoHideTime;
          this._opacity = 255;
          this._setOpacity(this._opacity);
        };
        _proto.onScroll = function onScroll(outOfBoundary) {
          if (!this._scrollView) {
            return;
          }
          var content = this._scrollView.content;
          if (!content) {
            return;
          }
          var contentSize = content._uiProps.uiTransformComp.contentSize;
          var scrollViewSize = this._scrollView.node._uiProps.uiTransformComp.contentSize;
          var barSize = this.node._uiProps.uiTransformComp.contentSize;
          if (this._conditionalDisableScrollBar(contentSize, scrollViewSize)) {
            return;
          }
          if (this._enableAutoHide) {
            this._autoHideRemainingTime = this._autoHideTime;
            this._setOpacity(this._opacity);
          }
          var contentMeasure = 0;
          var scrollViewMeasure = 0;
          var outOfBoundaryValue = 0;
          var contentPosition = 0;
          var handleNodeMeasure = 0;
          var outOfContentPosition = _tempVec2$2;
          outOfContentPosition.set(0, 0);
          if (this._direction === Direction$3.HORIZONTAL) {
            contentMeasure = contentSize.width;
            scrollViewMeasure = scrollViewSize.width;
            handleNodeMeasure = barSize.width;
            outOfBoundaryValue = outOfBoundary.x;
            this._convertToScrollViewSpace(outOfContentPosition, content);
            contentPosition = -outOfContentPosition.x;
          } else if (this._direction === Direction$3.VERTICAL) {
            contentMeasure = contentSize.height;
            scrollViewMeasure = scrollViewSize.height;
            handleNodeMeasure = barSize.height;
            outOfBoundaryValue = outOfBoundary.y;
            this._convertToScrollViewSpace(outOfContentPosition, content);
            contentPosition = -outOfContentPosition.y;
          }
          var length = this._calculateLength(contentMeasure, scrollViewMeasure, handleNodeMeasure, outOfBoundaryValue);
          var position = _tempVec2$2;
          this._calculatePosition(position, contentMeasure, scrollViewMeasure, handleNodeMeasure, contentPosition, outOfBoundaryValue, length);
          this._updateLength(length);
          this._updateHandlerPosition(position);
        };
        _proto.setScrollView = function setScrollView(scrollView) {
          this._scrollView = scrollView;
        };
        _proto.onTouchBegan = function onTouchBegan() {
          if (!this._enableAutoHide) {
            return;
          }
          this._touching = true;
        };
        _proto.onTouchEnded = function onTouchEnded() {
          if (!this._enableAutoHide) {
            return;
          }
          this._touching = false;
          if (this._autoHideTime <= 0) {
            return;
          }
          if (this._scrollView) {
            var content = this._scrollView.content;
            if (content) {
              var contentSize = content._uiProps.uiTransformComp.contentSize;
              var scrollViewSize = this._scrollView.node._uiProps.uiTransformComp.contentSize;
              if (this._conditionalDisableScrollBar(contentSize, scrollViewSize)) {
                return;
              }
            }
          }
          this._autoHideRemainingTime = this._autoHideTime;
        };
        _proto.onEnable = function onEnable() {
          var renderComp = this.node.getComponent(Sprite);
          if (renderComp) {
            this._opacity = renderComp.color.a;
          }
        };
        _proto.start = function start() {
          if (this._enableAutoHide) {
            this._setOpacity(0);
          }
        };
        _proto.update = function update(dt) {
          this._processAutoHide(dt);
        };
        _proto._convertToScrollViewSpace = function _convertToScrollViewSpace(out, content) {
          var scrollTrans = this._scrollView && this._scrollView.node._uiProps.uiTransformComp;
          var contentTrans = content._uiProps.uiTransformComp;
          if (!scrollTrans || !contentTrans) {
            out.set(Vec2.ZERO);
          } else {
            _tempPos_1.set(-contentTrans.anchorX * contentTrans.width, -contentTrans.anchorY * contentTrans.height, 0);
            contentTrans.convertToWorldSpaceAR(_tempPos_1, _tempPos_2);
            var scrollViewSpacePos = scrollTrans.convertToNodeSpaceAR(_tempPos_2);
            scrollViewSpacePos.x += scrollTrans.anchorX * scrollTrans.width;
            scrollViewSpacePos.y += scrollTrans.anchorY * scrollTrans.height;
            out.set(scrollViewSpacePos.x, scrollViewSpacePos.y);
          }
        };
        _proto._setOpacity = function _setOpacity(opacity) {
          if (this._handle) {
            var renderComp = this.node.getComponent(Sprite);
            if (renderComp) {
              _tempColor.set(renderComp.color);
              _tempColor.a = opacity;
              renderComp.color = _tempColor;
            }
            renderComp = this._handle.getComponent(Sprite);
            if (renderComp) {
              _tempColor.set(renderComp.color);
              _tempColor.a = opacity;
              renderComp.color = _tempColor;
            }
          }
        };
        _proto._updateHandlerPosition = function _updateHandlerPosition(position) {
          if (this._handle) {
            var oldPosition = _tempVec3$1;
            this._fixupHandlerPosition(oldPosition);
            this._handle.node.setPosition(position.x + oldPosition.x, position.y + oldPosition.y, oldPosition.z);
          }
        };
        _proto._fixupHandlerPosition = function _fixupHandlerPosition(out) {
          var uiTrans = this.node._uiProps.uiTransformComp;
          var barSize = uiTrans.contentSize;
          var barAnchor = uiTrans.anchorPoint;
          var handleSize = this.handle.node._uiProps.uiTransformComp.contentSize;
          var handleParent = this.handle.node.parent;
          Vec3.set(_tempPos_1, -barSize.width * barAnchor.x, -barSize.height * barAnchor.y, 0);
          var leftBottomWorldPosition = this.node._uiProps.uiTransformComp.convertToWorldSpaceAR(_tempPos_1, _tempPos_2);
          var fixupPosition = out;
          fixupPosition.set(0, 0, 0);
          handleParent._uiProps.uiTransformComp.convertToNodeSpaceAR(leftBottomWorldPosition, fixupPosition);
          if (this.direction === Direction$3.HORIZONTAL) {
            fixupPosition.set(fixupPosition.x, fixupPosition.y + (barSize.height - handleSize.height) / 2, fixupPosition.z);
          } else if (this.direction === Direction$3.VERTICAL) {
            fixupPosition.set(fixupPosition.x + (barSize.width - handleSize.width) / 2, fixupPosition.y, fixupPosition.z);
          }
          this.handle.node.setPosition(fixupPosition);
        };
        _proto._conditionalDisableScrollBar = function _conditionalDisableScrollBar(contentSize, scrollViewSize) {
          if (contentSize.width <= scrollViewSize.width && this._direction === Direction$3.HORIZONTAL) {
            return true;
          }
          if (contentSize.height <= scrollViewSize.height && this._direction === Direction$3.VERTICAL) {
            return true;
          }
          return false;
        };
        _proto._calculateLength = function _calculateLength(contentMeasure, scrollViewMeasure, handleNodeMeasure, outOfBoundary) {
          var denominatorValue = contentMeasure;
          if (outOfBoundary) {
            denominatorValue += (outOfBoundary > 0 ? outOfBoundary : -outOfBoundary) * GETTING_SHORTER_FACTOR;
          }
          var lengthRation = scrollViewMeasure / denominatorValue;
          return handleNodeMeasure * lengthRation;
        };
        _proto._calculatePosition = function _calculatePosition(out, contentMeasure, scrollViewMeasure, handleNodeMeasure, contentPosition, outOfBoundary, actualLenth) {
          var denominatorValue = contentMeasure - scrollViewMeasure;
          if (outOfBoundary) {
            denominatorValue += Math.abs(outOfBoundary);
          }
          var positionRatio = 0;
          if (denominatorValue) {
            positionRatio = contentPosition / denominatorValue;
            positionRatio = clamp01(positionRatio);
          }
          var position = (handleNodeMeasure - actualLenth) * positionRatio;
          if (this._direction === Direction$3.VERTICAL) {
            out.set(0, position);
          } else {
            out.set(position, 0);
          }
        };
        _proto._updateLength = function _updateLength(length) {
          if (this._handle) {
            var handleNode = this._handle.node;
            var handleTrans = handleNode._uiProps.uiTransformComp;
            var handleNodeSize = handleTrans.contentSize;
            var anchor = handleTrans.anchorPoint;
            if (anchor.x !== defaultAnchor.x || anchor.y !== defaultAnchor.y) {
              handleTrans.setAnchorPoint(defaultAnchor);
            }
            if (this._direction === Direction$3.HORIZONTAL) {
              handleTrans.setContentSize(length, handleNodeSize.height);
            } else {
              handleTrans.setContentSize(handleNodeSize.width, length);
            }
          }
        };
        _proto._processAutoHide = function _processAutoHide(deltaTime) {
          if (!this._enableAutoHide || this._autoHideRemainingTime <= 0) {
            return;
          } else if (this._touching) {
            return;
          }
          this._autoHideRemainingTime -= deltaTime;
          if (this._autoHideRemainingTime <= this._autoHideTime) {
            this._autoHideRemainingTime = Math.max(0, this._autoHideRemainingTime);
            var opacity = this._opacity * (this._autoHideRemainingTime / this._autoHideTime);
            this._setOpacity(opacity);
          }
        };
        _createClass(ScrollBar, [{
          key: "handle",
          get: function get() {
            return this._handle;
          },
          set: function set(value) {
            if (this._handle === value) {
              return;
            }
            this._handle = value;
            this.onScroll(Vec2.ZERO);
          }
        }, {
          key: "direction",
          get: function get() {
            return this._direction;
          },
          set: function set(value) {
            if (this._direction === value) {
              return;
            }
            this._direction = value;
            this.onScroll(Vec2.ZERO);
          }
        }, {
          key: "enableAutoHide",
          get: function get() {
            return this._enableAutoHide;
          },
          set: function set(value) {
            if (this._enableAutoHide === value) {
              return;
            }
            this._enableAutoHide = value;
            if (this._enableAutoHide) {
              this._setOpacity(0);
            }
          }
        }, {
          key: "autoHideTime",
          get: function get() {
            return this._autoHideTime;
          },
          set: function set(value) {
            if (this._autoHideTime === value) {
              return;
            }
            this._autoHideTime = value;
          }
        }]);
        return ScrollBar;
      }(Component), _class3$6.Direction = Direction$3, _class3$6), (_applyDecoratedDescriptor(_class2$9.prototype, "handle", [_dec4$7], Object.getOwnPropertyDescriptor(_class2$9.prototype, "handle"), _class2$9.prototype), _applyDecoratedDescriptor(_class2$9.prototype, "direction", [_dec5$7], Object.getOwnPropertyDescriptor(_class2$9.prototype, "direction"), _class2$9.prototype), _initializer$9 = applyDecoratedInitializer(_class2$9.prototype, "_scrollView", [serializable$j], function () {
        return null;
      }), _initializer2$9 = applyDecoratedInitializer(_class2$9.prototype, "_handle", [serializable$j], function () {
        return null;
      }), _initializer3$7 = applyDecoratedInitializer(_class2$9.prototype, "_direction", [serializable$j], function () {
        return Direction$3.HORIZONTAL;
      }), _initializer4$6 = applyDecoratedInitializer(_class2$9.prototype, "_enableAutoHide", [serializable$j], function () {
        return false;
      }), _initializer5$4 = applyDecoratedInitializer(_class2$9.prototype, "_autoHideTime", [serializable$j], function () {
        return 1.0;
      })), _class2$9)) || _class$c) || _class$c) || _class$c));
      legacyCC.ScrollBar = ScrollBar;

      var _dec$b, _dec2$a, _class$b;
      var ViewGroup = exports('ft', (_dec$b = ccclass$n('cc.ViewGroup'), _dec2$a = executionOrder$1(110), _dec$b(_class$b = _dec2$a(_class$b = function (_Component) {
        _inheritsLoose(ViewGroup, _Component);
        function ViewGroup() {
          return _Component.apply(this, arguments) || this;
        }
        return ViewGroup;
      }(Component)) || _class$b) || _class$b));
      legacyCC.ViewGroup = ViewGroup;

      var _dec$a, _dec2$9, _dec3$9, _dec4$6, _dec5$6, _dec6$2, _dec7$1, _class$a, _class2$8, _initializer$8, _initializer2$8, _initializer3$6, _initializer4$5, _initializer5$3, _initializer6$2, _initializer7$2, _initializer8$2, _initializer9$2, _initializer10$2, _initializer11$2, _class3$5;
      var NUMBER_OF_GATHERED_TOUCHES_FOR_MOVE_SPEED = 5;
      var OUT_OF_BOUNDARY_BREAKING_FACTOR = 0.05;
      var EPSILON = 1e-4;
      var TOLERANCE = 1e4;
      var MOVEMENT_FACTOR = 0.7;
      var _tempVec3 = new Vec3();
      var _tempVec3_1 = new Vec3();
      var _tempVec2$1 = new Vec2();
      var _tempVec2_1$1 = new Vec2();
      var quintEaseOut = function quintEaseOut(time) {
        time -= 1;
        return time * time * time * time * time + 1;
      };
      var getTimeInMilliseconds = function getTimeInMilliseconds() {
        var currentTime = new Date();
        return currentTime.getMilliseconds();
      };
      var eventMap = {
        'scroll-to-top': 0,
        'scroll-to-bottom': 1,
        'scroll-to-left': 2,
        'scroll-to-right': 3,
        scrolling: 4,
        'bounce-bottom': 6,
        'bounce-left': 7,
        'bounce-right': 8,
        'bounce-top': 5,
        'scroll-ended': 9,
        'touch-up': 10,
        'scroll-ended-with-threshold': 11,
        'scroll-began': 12
      };
      var EventType$2;
      (function (EventType) {
        EventType["SCROLL_TO_TOP"] = "scroll-to-top";
        EventType["SCROLL_TO_BOTTOM"] = "scroll-to-bottom";
        EventType["SCROLL_TO_LEFT"] = "scroll-to-left";
        EventType["SCROLL_TO_RIGHT"] = "scroll-to-right";
        EventType["SCROLL_BEGAN"] = "scroll-began";
        EventType["SCROLL_ENDED"] = "scroll-ended";
        EventType["BOUNCE_TOP"] = "bounce-top";
        EventType["BOUNCE_BOTTOM"] = "bounce-bottom";
        EventType["BOUNCE_LEFT"] = "bounce-left";
        EventType["BOUNCE_RIGHT"] = "bounce-right";
        EventType["SCROLLING"] = "scrolling";
        EventType["SCROLL_ENG_WITH_THRESHOLD"] = "scroll-ended-with-threshold";
        EventType["TOUCH_UP"] = "touch-up";
      })(EventType$2 || (EventType$2 = {}));
      var XrhoverType;
      (function (XrhoverType) {
        XrhoverType[XrhoverType["NONE"] = 0] = "NONE";
        XrhoverType[XrhoverType["LEFT"] = 1] = "LEFT";
        XrhoverType[XrhoverType["RIGHT"] = 2] = "RIGHT";
      })(XrhoverType || (XrhoverType = {}));
      var ScrollView = exports('fp', (_dec$a = ccclass$n('cc.ScrollView'), _dec2$9 = executionOrder$1(110), _dec3$9 = requireComponent(UITransform), _dec4$6 = type$7(Node$1), _dec5$6 = type$7(ScrollBar), _dec6$2 = type$7(ScrollBar), _dec7$1 = type$7([EventHandler]), _dec$a(_class$a = _dec2$9(_class$a = _dec3$9(_class$a = (_class2$8 = (_class3$5 = function (_ViewGroup) {
        _inheritsLoose(ScrollView, _ViewGroup);
        function ScrollView() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _ViewGroup.call.apply(_ViewGroup, [this].concat(args)) || this;
          _this.bounceDuration = _initializer$8 && _initializer$8();
          _this.brake = _initializer2$8 && _initializer2$8();
          _this.elastic = _initializer3$6 && _initializer3$6();
          _this.inertia = _initializer4$5 && _initializer4$5();
          _this.horizontal = _initializer5$3 && _initializer5$3();
          _this.vertical = _initializer6$2 && _initializer6$2();
          _this.cancelInnerEvents = _initializer7$2 && _initializer7$2();
          _this.scrollEvents = _initializer8$2 && _initializer8$2();
          _this._autoScrolling = false;
          _this._scrolling = false;
          _this._content = _initializer9$2 && _initializer9$2();
          _this._horizontalScrollBar = _initializer10$2 && _initializer10$2();
          _this._verticalScrollBar = _initializer11$2 && _initializer11$2();
          _this._topBoundary = 0;
          _this._bottomBoundary = 0;
          _this._leftBoundary = 0;
          _this._rightBoundary = 0;
          _this._touchMoveDisplacements = [];
          _this._touchMoveTimeDeltas = [];
          _this._touchMovePreviousTimestamp = 0;
          _this._touchMoved = false;
          _this._autoScrollAttenuate = false;
          _this._autoScrollStartPosition = new Vec3();
          _this._autoScrollTargetDelta = new Vec3();
          _this._autoScrollTotalTime = 0;
          _this._autoScrollAccumulatedTime = 0;
          _this._autoScrollCurrentlyOutOfBoundary = false;
          _this._autoScrollBraking = false;
          _this._autoScrollBrakingStartPosition = new Vec3();
          _this._outOfBoundaryAmount = new Vec3();
          _this._outOfBoundaryAmountDirty = true;
          _this._stopMouseWheel = false;
          _this._mouseWheelEventElapsedTime = 0.0;
          _this._isScrollEndedWithThresholdEventFired = false;
          _this._scrollEventEmitMask = 0;
          _this._isBouncing = false;
          _this._contentPos = new Vec3();
          _this._deltaPos = new Vec3();
          _this._hoverIn = XrhoverType.NONE;
          return _this;
        }
        var _proto = ScrollView.prototype;
        _proto.scrollToBottom = function scrollToBottom(timeInSecond, attenuated) {
          if (attenuated === void 0) {
            attenuated = true;
          }
          var moveDelta = this._calculateMovePercentDelta({
            anchor: new Vec2(0, 0),
            applyToHorizontal: false,
            applyToVertical: true
          });
          if (timeInSecond) {
            this._startAutoScroll(moveDelta, timeInSecond, attenuated !== false);
          } else {
            this._moveContent(moveDelta, true);
          }
        };
        _proto.scrollToTop = function scrollToTop(timeInSecond, attenuated) {
          if (attenuated === void 0) {
            attenuated = true;
          }
          var moveDelta = this._calculateMovePercentDelta({
            anchor: new Vec2(0, 1),
            applyToHorizontal: false,
            applyToVertical: true
          });
          if (timeInSecond) {
            this._startAutoScroll(moveDelta, timeInSecond, attenuated !== false);
          } else {
            this._moveContent(moveDelta);
          }
        };
        _proto.scrollToLeft = function scrollToLeft(timeInSecond, attenuated) {
          if (attenuated === void 0) {
            attenuated = true;
          }
          var moveDelta = this._calculateMovePercentDelta({
            anchor: new Vec2(0, 0),
            applyToHorizontal: true,
            applyToVertical: false
          });
          if (timeInSecond) {
            this._startAutoScroll(moveDelta, timeInSecond, attenuated !== false);
          } else {
            this._moveContent(moveDelta);
          }
        };
        _proto.scrollToRight = function scrollToRight(timeInSecond, attenuated) {
          if (attenuated === void 0) {
            attenuated = true;
          }
          var moveDelta = this._calculateMovePercentDelta({
            anchor: new Vec2(1, 0),
            applyToHorizontal: true,
            applyToVertical: false
          });
          if (timeInSecond) {
            this._startAutoScroll(moveDelta, timeInSecond, attenuated !== false);
          } else {
            this._moveContent(moveDelta);
          }
        };
        _proto.scrollToTopLeft = function scrollToTopLeft(timeInSecond, attenuated) {
          if (attenuated === void 0) {
            attenuated = true;
          }
          var moveDelta = this._calculateMovePercentDelta({
            anchor: new Vec2(0, 1),
            applyToHorizontal: true,
            applyToVertical: true
          });
          if (timeInSecond) {
            this._startAutoScroll(moveDelta, timeInSecond, attenuated !== false);
          } else {
            this._moveContent(moveDelta);
          }
        };
        _proto.scrollToTopRight = function scrollToTopRight(timeInSecond, attenuated) {
          if (attenuated === void 0) {
            attenuated = true;
          }
          var moveDelta = this._calculateMovePercentDelta({
            anchor: new Vec2(1, 1),
            applyToHorizontal: true,
            applyToVertical: true
          });
          if (timeInSecond) {
            this._startAutoScroll(moveDelta, timeInSecond, attenuated !== false);
          } else {
            this._moveContent(moveDelta);
          }
        };
        _proto.scrollToBottomLeft = function scrollToBottomLeft(timeInSecond, attenuated) {
          if (attenuated === void 0) {
            attenuated = true;
          }
          var moveDelta = this._calculateMovePercentDelta({
            anchor: new Vec2(0, 0),
            applyToHorizontal: true,
            applyToVertical: true
          });
          if (timeInSecond) {
            this._startAutoScroll(moveDelta, timeInSecond, attenuated !== false);
          } else {
            this._moveContent(moveDelta);
          }
        };
        _proto.scrollToBottomRight = function scrollToBottomRight(timeInSecond, attenuated) {
          if (attenuated === void 0) {
            attenuated = true;
          }
          var moveDelta = this._calculateMovePercentDelta({
            anchor: new Vec2(1, 0),
            applyToHorizontal: true,
            applyToVertical: true
          });
          if (timeInSecond) {
            this._startAutoScroll(moveDelta, timeInSecond, attenuated !== false);
          } else {
            this._moveContent(moveDelta);
          }
        };
        _proto.scrollToOffset = function scrollToOffset(offset, timeInSecond, attenuated) {
          if (attenuated === void 0) {
            attenuated = true;
          }
          var maxScrollOffset = this.getMaxScrollOffset();
          var anchor = new Vec2(0, 0);
          if (maxScrollOffset.x === 0) {
            anchor.x = 0;
          } else {
            anchor.x = offset.x / maxScrollOffset.x;
          }
          if (maxScrollOffset.y === 0) {
            anchor.y = 1;
          } else {
            anchor.y = (maxScrollOffset.y - offset.y) / maxScrollOffset.y;
          }
          this.scrollTo(anchor, timeInSecond, attenuated);
        };
        _proto.getScrollOffset = function getScrollOffset() {
          var topDelta = this._getContentTopBoundary() - this._topBoundary;
          var leftDelta = this._getContentLeftBoundary() - this._leftBoundary;
          return new Vec2(leftDelta, topDelta);
        };
        _proto.getMaxScrollOffset = function getMaxScrollOffset() {
          if (!this._content || !this.view) {
            return Vec2.ZERO;
          }
          var contentSize = this._content._uiProps.uiTransformComp.contentSize;
          var horizontalMaximizeOffset = contentSize.width - this.view.width;
          var verticalMaximizeOffset = contentSize.height - this.view.height;
          horizontalMaximizeOffset = horizontalMaximizeOffset >= 0 ? horizontalMaximizeOffset : 0;
          verticalMaximizeOffset = verticalMaximizeOffset >= 0 ? verticalMaximizeOffset : 0;
          return new Vec2(horizontalMaximizeOffset, verticalMaximizeOffset);
        };
        _proto.scrollToPercentHorizontal = function scrollToPercentHorizontal(percent, timeInSecond, attenuated) {
          var moveDelta = this._calculateMovePercentDelta({
            anchor: new Vec2(percent, 0),
            applyToHorizontal: true,
            applyToVertical: false
          });
          if (timeInSecond) {
            this._startAutoScroll(moveDelta, timeInSecond, attenuated !== false);
          } else {
            this._moveContent(moveDelta);
          }
        };
        _proto.scrollTo = function scrollTo(anchor, timeInSecond, attenuated) {
          var moveDelta = this._calculateMovePercentDelta({
            anchor: new Vec2(anchor),
            applyToHorizontal: true,
            applyToVertical: true
          });
          if (timeInSecond) {
            this._startAutoScroll(moveDelta, timeInSecond, attenuated);
          } else {
            this._moveContent(moveDelta);
          }
        };
        _proto.scrollToPercentVertical = function scrollToPercentVertical(percent, timeInSecond, attenuated) {
          var moveDelta = this._calculateMovePercentDelta({
            anchor: new Vec2(0, percent),
            applyToHorizontal: false,
            applyToVertical: true
          });
          if (timeInSecond) {
            this._startAutoScroll(moveDelta, timeInSecond, attenuated);
          } else {
            this._moveContent(moveDelta);
          }
        };
        _proto.stopAutoScroll = function stopAutoScroll() {
          this._autoScrolling = false;
          this._autoScrollAccumulatedTime = this._autoScrollTotalTime;
        };
        _proto.setContentPosition = function setContentPosition(position) {
          this._setContentPosition(position);
        };
        _proto._setContentPosition = function _setContentPosition(position) {
          if (!this._content) {
            return;
          }
          var contentPos = this._getContentPosition();
          if (Math.abs(position.x - contentPos.x) < EPSILON && Math.abs(position.y - contentPos.y) < EPSILON) {
            return;
          }
          this._content.setPosition(position);
          this._outOfBoundaryAmountDirty = true;
        };
        _proto.getContentPosition = function getContentPosition() {
          return this._getContentPosition();
        };
        _proto._getContentPosition = function _getContentPosition() {
          if (!this._content) {
            return Vec3.ZERO.clone();
          }
          this._contentPos.set(this._content.position);
          return this._contentPos;
        };
        _proto.isScrolling = function isScrolling() {
          return this._scrolling;
        };
        _proto.isAutoScrolling = function isAutoScrolling() {
          return this._autoScrolling;
        };
        _proto.getScrollEndedEventTiming = function getScrollEndedEventTiming() {
          return EPSILON;
        };
        _proto.start = function start() {
          this._calculateBoundary();
          if (this._content) {
            director.once(Director.EVENT_BEFORE_DRAW, this._adjustContentOutOfBoundary, this);
          }
        };
        _proto.onEnable = function onEnable() {
          {
            this._registerEvent();
            if (this._content) {
              this._content.on(NodeEventType.SIZE_CHANGED, this._calculateBoundary, this);
              this._content.on(NodeEventType.TRANSFORM_CHANGED, this._scaleChanged, this);
              if (this.view) {
                this.view.node.on(NodeEventType.TRANSFORM_CHANGED, this._scaleChanged, this);
                this.view.node.on(NodeEventType.SIZE_CHANGED, this._calculateBoundary, this);
              }
            }
            this._calculateBoundary();
          }
          this._updateScrollBarState();
        };
        _proto.update = function update(dt) {
          if (this._autoScrolling) {
            this._processAutoScrolling(dt);
          }
        };
        _proto.onDisable = function onDisable() {
          {
            this._unregisterEvent();
            if (this._content) {
              this._content.off(NodeEventType.SIZE_CHANGED, this._calculateBoundary, this);
              this._content.off(NodeEventType.TRANSFORM_CHANGED, this._scaleChanged, this);
              if (this.view) {
                this.view.node.off(NodeEventType.TRANSFORM_CHANGED, this._scaleChanged, this);
                this.view.node.off(NodeEventType.SIZE_CHANGED, this._calculateBoundary, this);
              }
            }
          }
          this._hideScrollBar();
          this.stopAutoScroll();
        };
        _proto._registerEvent = function _registerEvent() {
          this.node.on(NodeEventType.TOUCH_START, this._onTouchBegan, this, true);
          this.node.on(NodeEventType.TOUCH_MOVE, this._onTouchMoved, this, true);
          this.node.on(NodeEventType.TOUCH_END, this._onTouchEnded, this, true);
          this.node.on(NodeEventType.TOUCH_CANCEL, this._onTouchCancelled, this, true);
          this.node.on(NodeEventType.MOUSE_WHEEL, this._onMouseWheel, this, true);
          this.node.on(XrUIPressEventType.XRUI_HOVER_ENTERED, this._xrHoverEnter, this);
          this.node.on(XrUIPressEventType.XRUI_HOVER_EXITED, this._xrHoverExit, this);
          input$1.on(Input.EventType.HANDLE_INPUT, this._dispatchEventHandleInput, this);
          input$1.on(Input.EventType.GAMEPAD_INPUT, this._dispatchEventHandleInput, this);
        };
        _proto._unregisterEvent = function _unregisterEvent() {
          this.node.off(NodeEventType.TOUCH_START, this._onTouchBegan, this, true);
          this.node.off(NodeEventType.TOUCH_MOVE, this._onTouchMoved, this, true);
          this.node.off(NodeEventType.TOUCH_END, this._onTouchEnded, this, true);
          this.node.off(NodeEventType.TOUCH_CANCEL, this._onTouchCancelled, this, true);
          this.node.off(NodeEventType.MOUSE_WHEEL, this._onMouseWheel, this, true);
          this.node.off(XrUIPressEventType.XRUI_HOVER_ENTERED, this._xrHoverEnter, this);
          this.node.off(XrUIPressEventType.XRUI_HOVER_EXITED, this._xrHoverExit, this);
          input$1.off(Input.EventType.HANDLE_INPUT, this._dispatchEventHandleInput, this);
          input$1.off(Input.EventType.GAMEPAD_INPUT, this._dispatchEventHandleInput, this);
        };
        _proto._onMouseWheel = function _onMouseWheel(event, captureListeners) {
          if (!this.enabledInHierarchy) {
            return;
          }
          if (this._hasNestedViewGroup(event, captureListeners)) {
            return;
          }
          var deltaMove = new Vec3();
          var wheelPrecision = -0.1;
          var scrollY = event.getScrollY();
          if (this.vertical) {
            deltaMove.set(0, scrollY * wheelPrecision, 0);
          } else if (this.horizontal) {
            deltaMove.set(scrollY * wheelPrecision, 0, 0);
          }
          this._mouseWheelEventElapsedTime = 0;
          this._processDeltaMove(deltaMove);
          if (!this._stopMouseWheel) {
            this._handlePressLogic();
            this.schedule(this._checkMouseWheel, 1.0 / 60);
            this._stopMouseWheel = true;
          }
          this._stopPropagationIfTargetIsMe(event);
        };
        _proto._onTouchBegan = function _onTouchBegan(event, captureListeners) {
          if (!this.enabledInHierarchy || !this._content) {
            return;
          }
          if (this._hasNestedViewGroup(event, captureListeners)) {
            return;
          }
          this._handlePressLogic();
          this._touchMoved = false;
          this._stopPropagationIfTargetIsMe(event);
        };
        _proto._onTouchMoved = function _onTouchMoved(event, captureListeners) {
          if (!this.enabledInHierarchy || !this._content) {
            return;
          }
          if (this._hasNestedViewGroup(event, captureListeners)) {
            return;
          }
          var touch = event.touch;
          this._handleMoveLogic(touch);
          if (!this.cancelInnerEvents) {
            return;
          }
          var deltaMove = touch.getUILocation(_tempVec2$1);
          deltaMove.subtract(touch.getUIStartLocation(_tempVec2_1$1));
          if (deltaMove.length() > 7) {
            if (!this._touchMoved && event.target !== this.node) {
              var cancelEvent = new EventTouch(event.getTouches(), event.bubbles, SystemEventType.TOUCH_CANCEL);
              cancelEvent.touch = event.touch;
              cancelEvent.simulate = true;
              event.target.dispatchEvent(cancelEvent);
              this._touchMoved = true;
            }
          }
          this._stopPropagationIfTargetIsMe(event);
        };
        _proto._onTouchEnded = function _onTouchEnded(event, captureListeners) {
          if (!this.enabledInHierarchy || !this._content || !event) {
            return;
          }
          if (this._hasNestedViewGroup(event, captureListeners)) {
            return;
          }
          this._dispatchEvent(EventType$2.TOUCH_UP);
          var touch = event.touch;
          this._handleReleaseLogic(touch);
          if (this._touchMoved) {
            event.propagationStopped = true;
          } else {
            this._stopPropagationIfTargetIsMe(event);
          }
        };
        _proto._onTouchCancelled = function _onTouchCancelled(event, captureListeners) {
          if (!this.enabledInHierarchy || !this._content) {
            return;
          }
          if (this._hasNestedViewGroup(event, captureListeners)) {
            return;
          }
          if (event && !event.simulate) {
            var touch = event.touch;
            this._handleReleaseLogic(touch);
          }
          this._stopPropagationIfTargetIsMe(event);
        };
        _proto._calculateBoundary = function _calculateBoundary() {
          if (this._content && this.view) {
            var layout = this._content.getComponent(Layout);
            if (layout && layout.enabledInHierarchy) {
              layout.updateLayout();
            }
            var viewTrans = this.view;
            var anchorX = viewTrans.width * viewTrans.anchorX;
            var anchorY = viewTrans.height * viewTrans.anchorY;
            this._leftBoundary = -anchorX;
            this._bottomBoundary = -anchorY;
            this._rightBoundary = this._leftBoundary + viewTrans.width;
            this._topBoundary = this._bottomBoundary + viewTrans.height;
            this._moveContentToTopLeft(viewTrans.contentSize);
          }
        };
        _proto._hasNestedViewGroup = function _hasNestedViewGroup(event, captureListeners) {
          if (!event || event.eventPhase !== Event.CAPTURING_PHASE) {
            return false;
          }
          if (captureListeners) {
            for (var _iterator = _createForOfIteratorHelperLoose(captureListeners), _step; !(_step = _iterator()).done;) {
              var listener = _step.value;
              var item = listener;
              if (this.node === item) {
                if (event.target && event.target.getComponent(ViewGroup)) {
                  return true;
                }
                return false;
              }
              if (item.getComponent(ViewGroup)) {
                return true;
              }
            }
          }
          return false;
        };
        _proto._startInertiaScroll = function _startInertiaScroll(touchMoveVelocity) {
          var inertiaTotalMovement = new Vec3(touchMoveVelocity);
          inertiaTotalMovement.multiplyScalar(MOVEMENT_FACTOR);
          this._startAttenuatingAutoScroll(inertiaTotalMovement, touchMoveVelocity);
        };
        _proto._calculateAttenuatedFactor = function _calculateAttenuatedFactor(distance) {
          if (this.brake <= 0) {
            return 1 - this.brake;
          }
          return (1 - this.brake) * (1 / (1 + distance * 0.000014 + distance * distance * 0.000000008));
        };
        _proto._startAttenuatingAutoScroll = function _startAttenuatingAutoScroll(deltaMove, initialVelocity) {
          var targetDelta = deltaMove.clone();
          targetDelta.normalize();
          if (this._content && this.view) {
            var contentSize = this._content._uiProps.uiTransformComp.contentSize;
            var scrollViewSize = this.view.contentSize;
            var totalMoveWidth = contentSize.width - scrollViewSize.width;
            var totalMoveHeight = contentSize.height - scrollViewSize.height;
            var attenuatedFactorX = this._calculateAttenuatedFactor(totalMoveWidth);
            var attenuatedFactorY = this._calculateAttenuatedFactor(totalMoveHeight);
            targetDelta.x = targetDelta.x * totalMoveWidth * (1 - this.brake) * attenuatedFactorX;
            targetDelta.y = targetDelta.y * totalMoveHeight * attenuatedFactorY * (1 - this.brake);
            targetDelta.z = 0;
          }
          var originalMoveLength = deltaMove.length();
          var factor = targetDelta.length() / originalMoveLength;
          targetDelta.add(deltaMove);
          if (this.brake > 0 && factor > 7) {
            factor = Math.sqrt(factor);
            var clonedDeltaMove = deltaMove.clone();
            clonedDeltaMove.multiplyScalar(factor);
            targetDelta.set(clonedDeltaMove);
            targetDelta.add(deltaMove);
          }
          var time = this._calculateAutoScrollTimeByInitialSpeed(initialVelocity.length());
          if (this.brake > 0 && factor > 3) {
            factor = 3;
            time *= factor;
          }
          if (this.brake === 0 && factor > 1) {
            time *= factor;
          }
          this._startAutoScroll(targetDelta, time, true);
        };
        _proto._calculateAutoScrollTimeByInitialSpeed = function _calculateAutoScrollTimeByInitialSpeed(initialSpeed) {
          return Math.sqrt(Math.sqrt(initialSpeed / 5));
        };
        _proto._startAutoScroll = function _startAutoScroll(deltaMove, timeInSecond, attenuated) {
          if (attenuated === void 0) {
            attenuated = false;
          }
          var adjustedDeltaMove = this._flattenVectorByDirection(deltaMove);
          this._autoScrolling = true;
          this._autoScrollTargetDelta = adjustedDeltaMove;
          this._autoScrollAttenuate = attenuated;
          Vec3.copy(this._autoScrollStartPosition, this._getContentPosition());
          this._autoScrollTotalTime = timeInSecond;
          this._autoScrollAccumulatedTime = 0;
          this._autoScrollBraking = false;
          this._isScrollEndedWithThresholdEventFired = false;
          this._autoScrollBrakingStartPosition.set(0, 0, 0);
          var currentOutOfBoundary = this._getHowMuchOutOfBoundary();
          if (!currentOutOfBoundary.equals(Vec3.ZERO, EPSILON)) {
            this._autoScrollCurrentlyOutOfBoundary = true;
          }
        };
        _proto._calculateTouchMoveVelocity = function _calculateTouchMoveVelocity() {
          var out = new Vec3();
          var totalTime = 0;
          totalTime = this._touchMoveTimeDeltas.reduce(function (a, b) {
            return a + b;
          }, totalTime);
          if (totalTime <= 0 || totalTime >= 0.5) {
            out.set(Vec3.ZERO);
          } else {
            var totalMovement = new Vec3();
            totalMovement = this._touchMoveDisplacements.reduce(function (a, b) {
              a.add(b);
              return a;
            }, totalMovement);
            out.set(totalMovement.x * (1 - this.brake) / totalTime, totalMovement.y * (1 - this.brake) / totalTime, totalMovement.z);
          }
          return out;
        };
        _proto._flattenVectorByDirection = function _flattenVectorByDirection(vector) {
          var result = vector;
          result.x = this.horizontal ? result.x : 0;
          result.y = this.vertical ? result.y : 0;
          return result;
        };
        _proto._moveContent = function _moveContent(deltaMove, canStartBounceBack) {
          var adjustedMove = this._flattenVectorByDirection(deltaMove);
          _tempVec3.set(this._getContentPosition());
          _tempVec3.add(adjustedMove);
          _tempVec3.set(Math.round(_tempVec3.x * TOLERANCE) * EPSILON, Math.round(_tempVec3.y * TOLERANCE) * EPSILON, _tempVec3.z);
          this._setContentPosition(_tempVec3);
          var outOfBoundary = this._getHowMuchOutOfBoundary();
          _tempVec2$1.set(outOfBoundary.x, outOfBoundary.y);
          this._updateScrollBar(_tempVec2$1);
          if (this.elastic && canStartBounceBack) {
            this._startBounceBackIfNeeded();
          }
        };
        _proto._getContentLeftBoundary = function _getContentLeftBoundary() {
          if (!this._content) {
            return -1;
          }
          var contentPos = this._getContentPosition();
          var uiTrans = this._content._uiProps.uiTransformComp;
          return contentPos.x - uiTrans.anchorX * uiTrans.width;
        };
        _proto._getContentRightBoundary = function _getContentRightBoundary() {
          if (!this._content) {
            return -1;
          }
          var uiTrans = this._content._uiProps.uiTransformComp;
          return this._getContentLeftBoundary() + uiTrans.width;
        };
        _proto._getContentTopBoundary = function _getContentTopBoundary() {
          if (!this._content) {
            return -1;
          }
          var uiTrans = this._content._uiProps.uiTransformComp;
          return this._getContentBottomBoundary() + uiTrans.height;
        };
        _proto._getContentBottomBoundary = function _getContentBottomBoundary() {
          if (!this._content) {
            return -1;
          }
          var contentPos = this._getContentPosition();
          var uiTrans = this._content._uiProps.uiTransformComp;
          return contentPos.y - uiTrans.anchorY * uiTrans.height;
        };
        _proto._getHowMuchOutOfBoundary = function _getHowMuchOutOfBoundary(addition) {
          addition = addition || new Vec3();
          if (addition.equals(Vec3.ZERO, EPSILON) && !this._outOfBoundaryAmountDirty) {
            return this._outOfBoundaryAmount;
          }
          var outOfBoundaryAmount = new Vec3();
          var tempLeftBoundary = this._getContentLeftBoundary();
          var tempRightBoundary = this._getContentRightBoundary();
          if (tempLeftBoundary + addition.x > this._leftBoundary) {
            outOfBoundaryAmount.x = this._leftBoundary - (tempLeftBoundary + addition.x);
          } else if (tempRightBoundary + addition.x < this._rightBoundary) {
            outOfBoundaryAmount.x = this._rightBoundary - (tempRightBoundary + addition.x);
          }
          var tempTopBoundary = this._getContentTopBoundary();
          var tempBottomBoundary = this._getContentBottomBoundary();
          if (tempTopBoundary + addition.y < this._topBoundary) {
            outOfBoundaryAmount.y = this._topBoundary - (tempTopBoundary + addition.y);
          } else if (tempBottomBoundary + addition.y > this._bottomBoundary) {
            outOfBoundaryAmount.y = this._bottomBoundary - (tempBottomBoundary + addition.y);
          }
          if (addition.equals(Vec3.ZERO, EPSILON)) {
            this._outOfBoundaryAmount = outOfBoundaryAmount;
            this._outOfBoundaryAmountDirty = false;
          }
          this._clampDelta(outOfBoundaryAmount);
          return outOfBoundaryAmount;
        };
        _proto._updateScrollBar = function _updateScrollBar(outOfBoundary) {
          if (this._horizontalScrollBar && this._horizontalScrollBar.isValid) {
            this._horizontalScrollBar.onScroll(outOfBoundary);
          }
          if (this._verticalScrollBar && this._verticalScrollBar.isValid) {
            this._verticalScrollBar.onScroll(outOfBoundary);
          }
        };
        _proto._onScrollBarTouchBegan = function _onScrollBarTouchBegan() {
          if (this._horizontalScrollBar && this._horizontalScrollBar.isValid) {
            this._horizontalScrollBar.onTouchBegan();
          }
          if (this._verticalScrollBar && this._verticalScrollBar.isValid) {
            this._verticalScrollBar.onTouchBegan();
          }
        };
        _proto._onScrollBarTouchEnded = function _onScrollBarTouchEnded() {
          if (this._horizontalScrollBar && this._horizontalScrollBar.isValid) {
            this._horizontalScrollBar.onTouchEnded();
          }
          if (this._verticalScrollBar && this._verticalScrollBar.isValid) {
            this._verticalScrollBar.onTouchEnded();
          }
        };
        _proto._dispatchEvent = function _dispatchEvent(event) {
          if (event === EventType$2.SCROLL_ENDED) {
            this._scrollEventEmitMask = 0;
          } else if (event === EventType$2.SCROLL_TO_TOP || event === EventType$2.SCROLL_TO_BOTTOM || event === EventType$2.SCROLL_TO_LEFT || event === EventType$2.SCROLL_TO_RIGHT) {
            var flag = 1 << eventMap[event];
            if (this._scrollEventEmitMask & flag) {
              return;
            } else {
              this._scrollEventEmitMask |= flag;
            }
          }
          EventHandler.emitEvents(this.scrollEvents, this, eventMap[event]);
          this.node.emit(event, this);
        };
        _proto._adjustContentOutOfBoundary = function _adjustContentOutOfBoundary() {
          if (!this._content) {
            return;
          }
          this._outOfBoundaryAmountDirty = true;
          var outOfBoundary = this._getHowMuchOutOfBoundary();
          var _isOutOfBoundary = !outOfBoundary.equals(Vec3.ZERO, EPSILON);
          if (_isOutOfBoundary) {
            _tempVec3.set(this._getContentPosition());
            _tempVec3.add(outOfBoundary);
            this._setContentPosition(_tempVec3);
            this._updateScrollBar(Vec2.ZERO);
          }
        };
        _proto._hideScrollBar = function _hideScrollBar() {
          if (this._horizontalScrollBar && this._horizontalScrollBar.isValid) {
            this._horizontalScrollBar.hide();
          }
          if (this._verticalScrollBar && this._verticalScrollBar.isValid) {
            this._verticalScrollBar.hide();
          }
        };
        _proto._updateScrollBarState = function _updateScrollBarState() {
          if (!this._content || !this.view) {
            return;
          }
          var viewTrans = this.view;
          var uiTrans = this._content._uiProps.uiTransformComp;
          if (this._verticalScrollBar && this._verticalScrollBar.isValid) {
            if (uiTrans.height < viewTrans.height || approx(uiTrans.height, viewTrans.height)) {
              this._verticalScrollBar.hide();
            } else {
              this._verticalScrollBar.show();
            }
          }
          if (this._horizontalScrollBar && this._horizontalScrollBar.isValid) {
            if (uiTrans.width < viewTrans.width || approx(uiTrans.width, viewTrans.width)) {
              this._horizontalScrollBar.hide();
            } else {
              this._horizontalScrollBar.show();
            }
          }
        };
        _proto._stopPropagationIfTargetIsMe = function _stopPropagationIfTargetIsMe(event) {
          if (event.eventPhase === Event.AT_TARGET && event.target === this.node) {
            event.propagationStopped = true;
          }
        };
        _proto._processDeltaMove = function _processDeltaMove(deltaMove) {
          this._scrollChildren(deltaMove);
          this._gatherTouchMove(deltaMove);
        };
        _proto._handleMoveLogic = function _handleMoveLogic(touch) {
          this._getLocalAxisAlignDelta(this._deltaPos, touch);
          this._processDeltaMove(this._deltaPos);
        };
        _proto._handleReleaseLogic = function _handleReleaseLogic(touch) {
          this._getLocalAxisAlignDelta(this._deltaPos, touch);
          this._gatherTouchMove(this._deltaPos);
          this._processInertiaScroll();
          if (this._scrolling) {
            this._scrolling = false;
            if (!this._autoScrolling) {
              this._dispatchEvent(EventType$2.SCROLL_ENDED);
            }
          }
        };
        _proto._getLocalAxisAlignDelta = function _getLocalAxisAlignDelta(out, touch) {
          var uiTransformComp = this.node._uiProps.uiTransformComp;
          var vec = new Vec3();
          if (uiTransformComp) {
            touch.getUILocation(_tempVec2$1);
            touch.getUIPreviousLocation(_tempVec2_1$1);
            _tempVec3.set(_tempVec2$1.x, _tempVec2$1.y, 0);
            _tempVec3_1.set(_tempVec2_1$1.x, _tempVec2_1$1.y, 0);
            uiTransformComp.convertToNodeSpaceAR(_tempVec3, _tempVec3);
            uiTransformComp.convertToNodeSpaceAR(_tempVec3_1, _tempVec3_1);
            Vec3.subtract(vec, _tempVec3, _tempVec3_1);
          }
          out.set(vec);
        };
        _proto._scrollChildren = function _scrollChildren(deltaMove) {
          this._clampDelta(deltaMove);
          var realMove = deltaMove;
          var outOfBoundary;
          if (this.elastic) {
            outOfBoundary = this._getHowMuchOutOfBoundary();
            realMove.x *= outOfBoundary.x === 0 ? 1 : 0.5;
            realMove.y *= outOfBoundary.y === 0 ? 1 : 0.5;
          }
          if (!this.elastic) {
            outOfBoundary = this._getHowMuchOutOfBoundary(realMove);
            realMove.add(outOfBoundary);
          }
          var verticalScrollEventType = '';
          var horizontalScrollEventType = '';
          if (this._content) {
            var _ref = this._content._uiProps.uiTransformComp,
              anchorX = _ref.anchorX,
              anchorY = _ref.anchorY,
              width = _ref.width,
              height = _ref.height;
            var pos = this._content.position || Vec3.ZERO;
            if (this.vertical) {
              if (realMove.y > 0) {
                var icBottomPos = pos.y - anchorY * height;
                if (icBottomPos + realMove.y >= this._bottomBoundary) {
                  verticalScrollEventType = EventType$2.SCROLL_TO_BOTTOM;
                }
              } else if (realMove.y < 0) {
                var icTopPos = pos.y - anchorY * height + height;
                if (icTopPos + realMove.y <= this._topBoundary) {
                  verticalScrollEventType = EventType$2.SCROLL_TO_TOP;
                }
              }
            }
            if (this.horizontal) {
              if (realMove.x < 0) {
                var icRightPos = pos.x - anchorX * width + width;
                if (icRightPos + realMove.x <= this._rightBoundary) {
                  horizontalScrollEventType = EventType$2.SCROLL_TO_RIGHT;
                }
              } else if (realMove.x > 0) {
                var icLeftPos = pos.x - anchorX * width;
                if (icLeftPos + realMove.x >= this._leftBoundary) {
                  horizontalScrollEventType = EventType$2.SCROLL_TO_LEFT;
                }
              }
            }
          }
          this._moveContent(realMove, false);
          if (this.horizontal && realMove.x !== 0 || this.vertical && realMove.y !== 0) {
            if (!this._scrolling) {
              this._scrolling = true;
              this._dispatchEvent(EventType$2.SCROLL_BEGAN);
            }
            this._dispatchEvent(EventType$2.SCROLLING);
          }
          if (verticalScrollEventType !== '') {
            this._dispatchEvent(verticalScrollEventType);
          }
          if (horizontalScrollEventType !== '') {
            this._dispatchEvent(horizontalScrollEventType);
          }
        };
        _proto._handlePressLogic = function _handlePressLogic() {
          if (this._autoScrolling) {
            this._dispatchEvent(EventType$2.SCROLL_ENDED);
          }
          this._autoScrolling = false;
          this._isBouncing = false;
          this._touchMovePreviousTimestamp = getTimeInMilliseconds();
          this._touchMoveDisplacements.length = 0;
          this._touchMoveTimeDeltas.length = 0;
          this._onScrollBarTouchBegan();
        };
        _proto._clampDelta = function _clampDelta(out) {
          if (this._content && this.view) {
            var scrollViewSize = this.view.contentSize;
            var uiTrans = this._content._uiProps.uiTransformComp;
            if (uiTrans.width < scrollViewSize.width) {
              out.x = 0;
            }
            if (uiTrans.height < scrollViewSize.height) {
              out.y = 0;
            }
          }
        };
        _proto._gatherTouchMove = function _gatherTouchMove(delta) {
          var clampDt = delta.clone();
          this._clampDelta(clampDt);
          while (this._touchMoveDisplacements.length >= NUMBER_OF_GATHERED_TOUCHES_FOR_MOVE_SPEED) {
            this._touchMoveDisplacements.shift();
            this._touchMoveTimeDeltas.shift();
          }
          this._touchMoveDisplacements.push(clampDt);
          var timeStamp = getTimeInMilliseconds();
          this._touchMoveTimeDeltas.push((timeStamp - this._touchMovePreviousTimestamp) / 1000);
          this._touchMovePreviousTimestamp = timeStamp;
        };
        _proto._startBounceBackIfNeeded = function _startBounceBackIfNeeded() {
          if (!this.elastic) {
            return false;
          }
          var bounceBackAmount = this._getHowMuchOutOfBoundary();
          this._clampDelta(bounceBackAmount);
          if (bounceBackAmount.equals(Vec3.ZERO, EPSILON)) {
            return false;
          }
          var bounceBackTime = Math.max(this.bounceDuration, 0);
          this._startAutoScroll(bounceBackAmount, bounceBackTime, true);
          if (!this._isBouncing) {
            if (bounceBackAmount.y > 0) {
              this._dispatchEvent(EventType$2.BOUNCE_TOP);
            }
            if (bounceBackAmount.y < 0) {
              this._dispatchEvent(EventType$2.BOUNCE_BOTTOM);
            }
            if (bounceBackAmount.x > 0) {
              this._dispatchEvent(EventType$2.BOUNCE_RIGHT);
            }
            if (bounceBackAmount.x < 0) {
              this._dispatchEvent(EventType$2.BOUNCE_LEFT);
            }
            this._isBouncing = true;
          }
          return true;
        };
        _proto._processInertiaScroll = function _processInertiaScroll() {
          var bounceBackStarted = this._startBounceBackIfNeeded();
          if (!bounceBackStarted && this.inertia) {
            var touchMoveVelocity = this._calculateTouchMoveVelocity();
            if (!touchMoveVelocity.equals(_tempVec3, EPSILON) && this.brake < 1) {
              this._startInertiaScroll(touchMoveVelocity);
            }
          }
          this._onScrollBarTouchEnded();
        };
        _proto._isOutOfBoundary = function _isOutOfBoundary() {
          var outOfBoundary = this._getHowMuchOutOfBoundary();
          return !outOfBoundary.equals(Vec3.ZERO, EPSILON);
        };
        _proto._isNecessaryAutoScrollBrake = function _isNecessaryAutoScrollBrake() {
          if (this._autoScrollBraking) {
            return true;
          }
          if (this._isOutOfBoundary()) {
            if (!this._autoScrollCurrentlyOutOfBoundary) {
              this._autoScrollCurrentlyOutOfBoundary = true;
              this._autoScrollBraking = true;
              Vec3.copy(this._autoScrollBrakingStartPosition, this._getContentPosition());
              return true;
            }
          } else {
            this._autoScrollCurrentlyOutOfBoundary = false;
          }
          return false;
        };
        _proto._processAutoScrolling = function _processAutoScrolling(dt) {
          var isAutoScrollBrake = this._isNecessaryAutoScrollBrake();
          var brakingFactor = isAutoScrollBrake ? OUT_OF_BOUNDARY_BREAKING_FACTOR : 1;
          this._autoScrollAccumulatedTime += dt * (1 / brakingFactor);
          var percentage = Math.min(1, this._autoScrollAccumulatedTime / this._autoScrollTotalTime);
          if (this._autoScrollAttenuate) {
            percentage = quintEaseOut(percentage);
          }
          var clonedAutoScrollTargetDelta = this._autoScrollTargetDelta.clone();
          clonedAutoScrollTargetDelta.multiplyScalar(percentage);
          var clonedAutoScrollStartPosition = this._autoScrollStartPosition.clone();
          clonedAutoScrollStartPosition.add(clonedAutoScrollTargetDelta);
          var reachedEnd = Math.abs(percentage - 1) <= EPSILON;
          var fireEvent = Math.abs(percentage - 1) <= this.getScrollEndedEventTiming();
          if (fireEvent && !this._isScrollEndedWithThresholdEventFired) {
            this._dispatchEvent(EventType$2.SCROLL_ENG_WITH_THRESHOLD);
            this._isScrollEndedWithThresholdEventFired = true;
          }
          if (this.elastic) {
            var brakeOffsetPosition = clonedAutoScrollStartPosition.clone();
            brakeOffsetPosition.subtract(this._autoScrollBrakingStartPosition);
            if (isAutoScrollBrake) {
              brakeOffsetPosition.multiplyScalar(brakingFactor);
            }
            clonedAutoScrollStartPosition.set(this._autoScrollBrakingStartPosition);
            clonedAutoScrollStartPosition.add(brakeOffsetPosition);
          } else {
            var moveDelta = clonedAutoScrollStartPosition.clone();
            moveDelta.subtract(this.getContentPosition());
            var outOfBoundary = this._getHowMuchOutOfBoundary(moveDelta);
            if (!outOfBoundary.equals(Vec3.ZERO, EPSILON)) {
              clonedAutoScrollStartPosition.add(outOfBoundary);
              reachedEnd = true;
            }
          }
          if (reachedEnd) {
            this._autoScrolling = false;
          }
          var deltaMove = clonedAutoScrollStartPosition.clone();
          deltaMove.subtract(this._getContentPosition());
          this._clampDelta(deltaMove);
          this._moveContent(deltaMove, reachedEnd);
          this._dispatchEvent(EventType$2.SCROLLING);
          if (!this._autoScrolling) {
            this._isBouncing = false;
            this._scrolling = false;
            this._dispatchEvent(EventType$2.SCROLL_ENDED);
          }
        };
        _proto._checkMouseWheel = function _checkMouseWheel(dt) {
          var currentOutOfBoundary = this._getHowMuchOutOfBoundary();
          var maxElapsedTime = 0.1;
          if (!currentOutOfBoundary.equals(Vec3.ZERO, EPSILON)) {
            this._processInertiaScroll();
            if (this._scrolling) {
              this._scrolling = false;
              if (!this._autoScrolling) {
                this._dispatchEvent(EventType$2.SCROLL_ENDED);
              }
            }
            this.unschedule(this._checkMouseWheel);
            this._stopMouseWheel = false;
            return;
          }
          this._mouseWheelEventElapsedTime += dt;
          if (this._mouseWheelEventElapsedTime > maxElapsedTime) {
            this._onScrollBarTouchEnded();
            if (this._scrolling) {
              this._scrolling = false;
              if (!this._autoScrolling) {
                this._dispatchEvent(EventType$2.SCROLL_ENDED);
              }
            }
            this.unschedule(this._checkMouseWheel);
            this._stopMouseWheel = false;
          }
        };
        _proto._calculateMovePercentDelta = function _calculateMovePercentDelta(options) {
          var anchor = options.anchor;
          var applyToHorizontal = options.applyToHorizontal;
          var applyToVertical = options.applyToVertical;
          this._calculateBoundary();
          anchor.clampf(Vec2.ZERO, Vec2.ONE);
          var bottomDelta = this._getContentBottomBoundary() - this._bottomBoundary;
          bottomDelta = -bottomDelta;
          var leftDelta = this._getContentLeftBoundary() - this._leftBoundary;
          leftDelta = -leftDelta;
          var moveDelta = new Vec3();
          if (this._content && this.view) {
            var totalScrollDelta = 0;
            var uiTrans = this._content._uiProps.uiTransformComp;
            var contentSize = uiTrans.contentSize;
            var scrollSize = this.view.contentSize;
            if (applyToHorizontal) {
              totalScrollDelta = contentSize.width - scrollSize.width;
              moveDelta.x = leftDelta - totalScrollDelta * anchor.x;
            }
            if (applyToVertical) {
              totalScrollDelta = contentSize.height - scrollSize.height;
              moveDelta.y = bottomDelta - totalScrollDelta * anchor.y;
            }
          }
          return moveDelta;
        };
        _proto._moveContentToTopLeft = function _moveContentToTopLeft(scrollViewSize) {
          var bottomDelta = this._getContentBottomBoundary() - this._bottomBoundary;
          bottomDelta = -bottomDelta;
          var moveDelta = new Vec3();
          var totalScrollDelta = 0;
          var leftDelta = this._getContentLeftBoundary() - this._leftBoundary;
          leftDelta = -leftDelta;
          if (this._content) {
            var uiTrans = this._content._uiProps.uiTransformComp;
            var contentSize = uiTrans.contentSize;
            if (contentSize.height < scrollViewSize.height) {
              totalScrollDelta = contentSize.height - scrollViewSize.height;
              moveDelta.y = bottomDelta - totalScrollDelta;
            }
            if (contentSize.width < scrollViewSize.width) {
              totalScrollDelta = contentSize.width - scrollViewSize.width;
              moveDelta.x = leftDelta;
            }
          }
          this._updateScrollBarState();
          this._moveContent(moveDelta);
          this._adjustContentOutOfBoundary();
        };
        _proto._scaleChanged = function _scaleChanged(value) {
          if (value === TransformBit.SCALE) {
            this._calculateBoundary();
          }
        };
        _proto._xrHoverEnter = function _xrHoverEnter(event) {
          if (event.deviceType === DeviceType.Left) {
            this._hoverIn = XrhoverType.LEFT;
          } else if (event.deviceType === DeviceType.Right) {
            this._hoverIn = XrhoverType.RIGHT;
          }
        };
        _proto._xrHoverExit = function _xrHoverExit(event) {
          this._hoverIn = XrhoverType.NONE;
        };
        _proto._dispatchEventHandleInput = function _dispatchEventHandleInput(event) {
          var handleInputDevice;
          if (event instanceof EventGamepad) {
            handleInputDevice = event.gamepad;
          } else if (event instanceof EventHandle) {
            handleInputDevice = event.handleInputDevice;
          }
          var value;
          if (!this.enabledInHierarchy || this._hoverIn === XrhoverType.NONE) {
            return;
          }
          if (this._hoverIn === XrhoverType.LEFT) {
            value = handleInputDevice.leftStick.getValue();
            if (!value.equals(Vec2.ZERO)) {
              this._xrThumbStickMove(value);
            }
          } else if (this._hoverIn === XrhoverType.RIGHT) {
            value = handleInputDevice.rightStick.getValue();
            if (!value.equals(Vec2.ZERO)) {
              this._xrThumbStickMove(value);
            }
          }
        };
        _proto._xrThumbStickMove = function _xrThumbStickMove(event) {
          if (!this.enabledInHierarchy) {
            return;
          }
          var deltaMove = new Vec3();
          var wheelPrecision = -62.5;
          var scrollY = event.y;
          if (this.vertical) {
            deltaMove.set(0, scrollY * wheelPrecision, 0);
          } else if (this.horizontal) {
            deltaMove.set(scrollY * wheelPrecision, 0, 0);
          }
          this._mouseWheelEventElapsedTime = 0;
          this._processDeltaMove(deltaMove);
          if (!this._stopMouseWheel) {
            this._handlePressLogic();
            this.schedule(this._checkMouseWheel, 1.0 / 60, NaN, 0);
            this._stopMouseWheel = true;
          }
        };
        _createClass(ScrollView, [{
          key: "content",
          get: function get() {
            return this._content;
          },
          set: function set(value) {
            if (this._content === value) {
              return;
            }
            var viewTrans = value && value.parent && value.parent._uiProps.uiTransformComp;
            if (value && (!value || !viewTrans)) {
              logID(4302);
              return;
            }
            this._content = value;
            this._calculateBoundary();
          }
        }, {
          key: "horizontalScrollBar",
          get: function get() {
            if (this._horizontalScrollBar && !this._horizontalScrollBar.isValid) {
              errorID(4303, 'horizontal', this.node.name);
            }
            return this._horizontalScrollBar;
          },
          set: function set(value) {
            if (this._horizontalScrollBar === value) {
              return;
            }
            this._horizontalScrollBar = value;
            if (this._horizontalScrollBar) {
              this._horizontalScrollBar.setScrollView(this);
              this._updateScrollBar(Vec2.ZERO);
            }
          }
        }, {
          key: "verticalScrollBar",
          get: function get() {
            if (this._verticalScrollBar && !this._verticalScrollBar.isValid) {
              errorID(4303, 'vertical', this.node.name);
            }
            return this._verticalScrollBar;
          },
          set: function set(value) {
            if (this._verticalScrollBar === value) {
              return;
            }
            this._verticalScrollBar = value;
            if (this._verticalScrollBar) {
              this._verticalScrollBar.setScrollView(this);
              this._updateScrollBar(Vec2.ZERO);
            }
          }
        }, {
          key: "view",
          get: function get() {
            var parent = this._content && this._content.parent;
            if (!parent) {
              return null;
            }
            return parent._uiProps.uiTransformComp;
          }
        }]);
        return ScrollView;
      }(ViewGroup), _class3$5.EventType = EventType$2, _class3$5), (_initializer$8 = applyDecoratedInitializer(_class2$8.prototype, "bounceDuration", [serializable$j], function () {
        return 1;
      }), _initializer2$8 = applyDecoratedInitializer(_class2$8.prototype, "brake", [serializable$j], function () {
        return 0.5;
      }), _initializer3$6 = applyDecoratedInitializer(_class2$8.prototype, "elastic", [serializable$j], function () {
        return true;
      }), _initializer4$5 = applyDecoratedInitializer(_class2$8.prototype, "inertia", [serializable$j], function () {
        return true;
      }), _applyDecoratedDescriptor(_class2$8.prototype, "content", [_dec4$6], Object.getOwnPropertyDescriptor(_class2$8.prototype, "content"), _class2$8.prototype), _initializer5$3 = applyDecoratedInitializer(_class2$8.prototype, "horizontal", [serializable$j], function () {
        return true;
      }), _applyDecoratedDescriptor(_class2$8.prototype, "horizontalScrollBar", [_dec5$6], Object.getOwnPropertyDescriptor(_class2$8.prototype, "horizontalScrollBar"), _class2$8.prototype), _initializer6$2 = applyDecoratedInitializer(_class2$8.prototype, "vertical", [serializable$j], function () {
        return true;
      }), _applyDecoratedDescriptor(_class2$8.prototype, "verticalScrollBar", [_dec6$2], Object.getOwnPropertyDescriptor(_class2$8.prototype, "verticalScrollBar"), _class2$8.prototype), _initializer7$2 = applyDecoratedInitializer(_class2$8.prototype, "cancelInnerEvents", [serializable$j], function () {
        return true;
      }), _initializer8$2 = applyDecoratedInitializer(_class2$8.prototype, "scrollEvents", [_dec7$1, serializable$j], function () {
        return [];
      }), _initializer9$2 = applyDecoratedInitializer(_class2$8.prototype, "_content", [serializable$j], function () {
        return null;
      }), _initializer10$2 = applyDecoratedInitializer(_class2$8.prototype, "_horizontalScrollBar", [serializable$j], function () {
        return null;
      }), _initializer11$2 = applyDecoratedInitializer(_class2$8.prototype, "_verticalScrollBar", [serializable$j], function () {
        return null;
      })), _class2$8)) || _class$a) || _class$a) || _class$a));
      legacyCC.ScrollView = ScrollView;

      var _dec$9, _dec2$8, _dec3$8, _dec4$5, _dec5$5, _dec6$1, _class$9, _class2$7, _initializer$7, _initializer2$7, _initializer3$5, _initializer4$4, _class3$4;
      var _tempPos$1 = new Vec3();
      var Direction$2;
      (function (Direction) {
        Direction[Direction["Horizontal"] = 0] = "Horizontal";
        Direction[Direction["Vertical"] = 1] = "Vertical";
      })(Direction$2 || (Direction$2 = {}));
      ccenum(Direction$2);
      var Slider = exports('fq', (_dec$9 = ccclass$n('cc.Slider'), _dec2$8 = executionOrder$1(110), _dec3$8 = requireComponent(UITransform), _dec4$5 = type$7(Sprite), _dec5$5 = type$7(Direction$2), _dec6$1 = type$7([EventHandler]), _dec$9(_class$9 = _dec2$8(_class$9 = _dec3$8(_class$9 = (_class2$7 = (_class3$4 = function (_Component) {
        _inheritsLoose(Slider, _Component);
        function Slider() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Component.call.apply(_Component, [this].concat(args)) || this;
          _this.slideEvents = _initializer$7 && _initializer$7();
          _this._handle = _initializer2$7 && _initializer2$7();
          _this._direction = _initializer3$5 && _initializer3$5();
          _this._progress = _initializer4$4 && _initializer4$4();
          _this._offset = new Vec3();
          _this._dragging = false;
          _this._touchHandle = false;
          _this._handleLocalPos = new Vec3();
          _this._touchPos = new Vec3();
          return _this;
        }
        var _proto = Slider.prototype;
        _proto.__preload = function __preload() {
          this._updateHandlePosition();
        };
        _proto.onEnable = function onEnable() {
          this._updateHandlePosition();
          this.node.on(NodeEventType.TOUCH_START, this._onTouchBegan, this);
          this.node.on(NodeEventType.TOUCH_MOVE, this._onTouchMoved, this);
          this.node.on(NodeEventType.TOUCH_END, this._onTouchEnded, this);
          this.node.on(NodeEventType.TOUCH_CANCEL, this._onTouchCancelled, this);
          this.node.on(XrUIPressEventType.XRUI_HOVER_STAY, this._xrHoverStay, this);
          this.node.on(XrUIPressEventType.XRUI_CLICK, this._xrClick, this);
          this.node.on(XrUIPressEventType.XRUI_UNCLICK, this._xrUnClick, this);
          if (this._handle && this._handle.isValid) {
            this._handle.node.on(NodeEventType.TOUCH_START, this._onHandleDragStart, this);
            this._handle.node.on(NodeEventType.TOUCH_MOVE, this._onTouchMoved, this);
            this._handle.node.on(NodeEventType.TOUCH_END, this._onTouchEnded, this);
          }
        };
        _proto.onDisable = function onDisable() {
          this.node.off(NodeEventType.TOUCH_START, this._onTouchBegan, this);
          this.node.off(NodeEventType.TOUCH_MOVE, this._onTouchMoved, this);
          this.node.off(NodeEventType.TOUCH_END, this._onTouchEnded, this);
          this.node.off(NodeEventType.TOUCH_CANCEL, this._onTouchCancelled, this);
          this.node.off(XrUIPressEventType.XRUI_HOVER_STAY, this._xrHoverStay, this);
          this.node.off(XrUIPressEventType.XRUI_CLICK, this._xrClick, this);
          this.node.off(XrUIPressEventType.XRUI_UNCLICK, this._xrUnClick, this);
          if (this._handle && this._handle.isValid) {
            this._handle.node.off(NodeEventType.TOUCH_START, this._onHandleDragStart, this);
            this._handle.node.off(NodeEventType.TOUCH_MOVE, this._onTouchMoved, this);
            this._handle.node.off(NodeEventType.TOUCH_END, this._onTouchEnded, this);
          }
        };
        _proto._onHandleDragStart = function _onHandleDragStart(event) {
          if (!event || !this._handle || !this._handle.node._uiProps.uiTransformComp) {
            return;
          }
          this._dragging = true;
          this._touchHandle = true;
          var touhPos = event.touch.getUILocation();
          Vec3.set(this._touchPos, touhPos.x, touhPos.y, 0);
          this._handle.node._uiProps.uiTransformComp.convertToNodeSpaceAR(this._touchPos, this._offset);
          event.propagationStopped = true;
        };
        _proto._onTouchBegan = function _onTouchBegan(event) {
          if (!this._handle || !event) {
            return;
          }
          this._dragging = true;
          if (!this._touchHandle) {
            this._handleSliderLogic(event.touch);
          }
          event.propagationStopped = true;
        };
        _proto._onTouchMoved = function _onTouchMoved(event) {
          if (!this._dragging || !event) {
            return;
          }
          this._handleSliderLogic(event.touch);
          event.propagationStopped = true;
        };
        _proto._onTouchEnded = function _onTouchEnded(event) {
          this._dragging = false;
          this._touchHandle = false;
          this._offset = new Vec3();
          if (event) {
            event.propagationStopped = true;
          }
        };
        _proto._onTouchCancelled = function _onTouchCancelled(event) {
          this._dragging = false;
          if (event) {
            event.propagationStopped = true;
          }
        };
        _proto._handleSliderLogic = function _handleSliderLogic(touch) {
          this._updateProgress(touch);
          this._emitSlideEvent();
        };
        _proto._emitSlideEvent = function _emitSlideEvent() {
          EventHandler.emitEvents(this.slideEvents, this);
          this.node.emit('slide', this);
        };
        _proto._updateProgress = function _updateProgress(touch) {
          if (!this._handle || !touch) {
            return;
          }
          var touchPos = touch.getUILocation();
          Vec3.set(this._touchPos, touchPos.x, touchPos.y, 0);
          var uiTrans = this.node._uiProps.uiTransformComp;
          var localTouchPos = uiTrans.convertToNodeSpaceAR(this._touchPos, _tempPos$1);
          if (this.direction === Direction$2.Horizontal) {
            this.progress = clamp01(0.5 + (localTouchPos.x - this._offset.x) / uiTrans.width);
          } else {
            this.progress = clamp01(0.5 + (localTouchPos.y - this._offset.y) / uiTrans.height);
          }
        };
        _proto._updateHandlePosition = function _updateHandlePosition() {
          if (!this._handle) {
            return;
          }
          this._handleLocalPos.set(this._handle.node.getPosition());
          var uiTrans = this.node._uiProps.uiTransformComp;
          if (this._direction === Direction$2.Horizontal) {
            this._handleLocalPos.x = -uiTrans.width * uiTrans.anchorX + this.progress * uiTrans.width;
          } else {
            this._handleLocalPos.y = -uiTrans.height * uiTrans.anchorY + this.progress * uiTrans.height;
          }
          this._handle.node.setPosition(this._handleLocalPos);
        };
        _proto._changeLayout = function _changeLayout() {
          var uiTrans = this.node._uiProps.uiTransformComp;
          var contentSize = uiTrans.contentSize;
          uiTrans.setContentSize(contentSize.height, contentSize.width);
          if (this._handle) {
            var pos = this._handle.node.position;
            if (this._direction === Direction$2.Horizontal) {
              this._handle.node.setPosition(pos.x, 0, pos.z);
            } else {
              this._handle.node.setPosition(0, pos.y, pos.z);
            }
            this._updateHandlePosition();
          }
        };
        _proto._xrHandleProgress = function _xrHandleProgress(point) {
          if (!this._touchHandle) {
            var uiTrans = this.node._uiProps.uiTransformComp;
            uiTrans.convertToNodeSpaceAR(point, _tempPos$1);
            if (this.direction === Direction$2.Horizontal) {
              this.progress = clamp01(0.5 + (_tempPos$1.x - this.node.position.x) / uiTrans.width);
            } else {
              this.progress = clamp01(0.5 + (_tempPos$1.y - this.node.position.y) / uiTrans.height);
            }
          }
        };
        _proto._xrClick = function _xrClick(event) {
          if (!this._handle) {
            return;
          }
          this._dragging = true;
          this._xrHandleProgress(event.hitPoint);
          this._emitSlideEvent();
        };
        _proto._xrUnClick = function _xrUnClick() {
          this._dragging = false;
          this._touchHandle = false;
        };
        _proto._xrHoverStay = function _xrHoverStay(event) {
          if (!this._dragging) {
            return;
          }
          this._xrHandleProgress(event.hitPoint);
          this._emitSlideEvent();
        };
        _createClass(Slider, [{
          key: "handle",
          get: function get() {
            return this._handle;
          },
          set: function set(value) {
            if (this._handle === value) {
              return;
            }
            this._handle = value;
          }
        }, {
          key: "direction",
          get: function get() {
            return this._direction;
          },
          set: function set(value) {
            if (this._direction === value) {
              return;
            }
            this._direction = value;
            this._changeLayout();
          }
        }, {
          key: "progress",
          get: function get() {
            return this._progress;
          },
          set: function set(value) {
            if (this._progress === value) {
              return;
            }
            this._progress = value;
            this._updateHandlePosition();
          }
        }]);
        return Slider;
      }(Component), _class3$4.Direction = Direction$2, _class3$4), (_applyDecoratedDescriptor(_class2$7.prototype, "handle", [_dec4$5], Object.getOwnPropertyDescriptor(_class2$7.prototype, "handle"), _class2$7.prototype), _applyDecoratedDescriptor(_class2$7.prototype, "direction", [_dec5$5], Object.getOwnPropertyDescriptor(_class2$7.prototype, "direction"), _class2$7.prototype), _initializer$7 = applyDecoratedInitializer(_class2$7.prototype, "slideEvents", [_dec6$1, serializable$j], function () {
        return [];
      }), _initializer2$7 = applyDecoratedInitializer(_class2$7.prototype, "_handle", [serializable$j], function () {
        return null;
      }), _initializer3$5 = applyDecoratedInitializer(_class2$7.prototype, "_direction", [serializable$j], function () {
        return Direction$2.Horizontal;
      }), _initializer4$4 = applyDecoratedInitializer(_class2$7.prototype, "_progress", [serializable$j], function () {
        return 0.1;
      })), _class2$7)) || _class$9) || _class$9) || _class$9));
      legacyCC.Slider = Slider;

      function extendsEnum() {
        for (var _len = arguments.length, enums = new Array(_len), _key = 0; _key < _len; _key++) {
          enums[_key] = arguments[_key];
        }
        return Object.assign.apply(Object, [{}].concat(enums));
      }

      var _dec$8, _dec2$7, _dec3$7, _dec4$4, _dec5$4, _class$8, _class2$6, _initializer$6, _initializer2$6, _initializer3$4, _class3$3;
      var EventType$1;
      (function (EventType) {
        EventType["TOGGLE"] = "toggle";
      })(EventType$1 || (EventType$1 = {}));
      var Toggle = exports('fr', (_dec$8 = ccclass$n('cc.Toggle'), _dec2$7 = executionOrder$1(110), _dec3$7 = requireComponent(UITransform), _dec4$4 = type$7(Sprite), _dec5$4 = type$7([EventHandler]), _dec$8(_class$8 = _dec2$7(_class$8 = _dec3$7(_class$8 = (_class2$6 = (_class3$3 = function (_Button) {
        _inheritsLoose(Toggle, _Button);
        function Toggle() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Button.call.apply(_Button, [this].concat(args)) || this;
          _this.checkEvents = _initializer$6 && _initializer$6();
          _this._isChecked = _initializer2$6 && _initializer2$6();
          _this._checkMark = _initializer3$4 && _initializer3$4();
          return _this;
        }
        var _proto = Toggle.prototype;
        _proto._internalToggle = function _internalToggle() {
          this.isChecked = !this.isChecked;
        };
        _proto._set = function _set(value, emitEvent) {
          if (emitEvent === void 0) {
            emitEvent = true;
          }
          if (this._isChecked == value) return;
          this._isChecked = value;
          var group = this._toggleContainer;
          if (group && group.enabled && this.enabled) {
            if (value || !group.anyTogglesChecked() && !group.allowSwitchOff) {
              this._isChecked = true;
              group.notifyToggleCheck(this, emitEvent);
            }
          }
          this.playEffect();
          if (emitEvent) {
            this._emitToggleEvents();
          }
        };
        _proto.playEffect = function playEffect() {
          if (this._checkMark) {
            this._checkMark.node.active = this._isChecked;
          }
        };
        _proto.setIsCheckedWithoutNotify = function setIsCheckedWithoutNotify(value) {
          this._set(value, false);
        };
        _proto.onEnable = function onEnable() {
          _Button.prototype.onEnable.call(this);
          this.playEffect();
          {
            this.node.on(Toggle.EventType.CLICK, this._internalToggle, this);
          }
        };
        _proto.onDisable = function onDisable() {
          _Button.prototype.onDisable.call(this);
          {
            this.node.off(Toggle.EventType.CLICK, this._internalToggle, this);
          }
        };
        _proto._emitToggleEvents = function _emitToggleEvents() {
          this.node.emit(Toggle.EventType.TOGGLE, this);
          if (this.checkEvents) {
            EventHandler.emitEvents(this.checkEvents, this);
          }
        };
        _createClass(Toggle, [{
          key: "isChecked",
          get: function get() {
            return this._isChecked;
          },
          set: function set(value) {
            this._set(value);
          }
        }, {
          key: "checkMark",
          get: function get() {
            return this._checkMark;
          },
          set: function set(value) {
            if (this._checkMark === value) {
              return;
            }
            this._checkMark = value;
          }
        }, {
          key: "_resizeToTarget",
          set: function set(value) {
            if (value) {
              this._resizeNodeToTargetNode();
            }
          }
        }, {
          key: "_toggleContainer",
          get: function get() {
            var parent = this.node.parent;
            if (legacyCC.Node.isNode(parent)) {
              return parent.getComponent('cc.ToggleContainer');
            }
            return null;
          }
        }]);
        return Toggle;
      }(Button), _class3$3.EventType = extendsEnum(EventType$1, EventType$4), _class3$3), (_applyDecoratedDescriptor(_class2$6.prototype, "checkMark", [_dec4$4], Object.getOwnPropertyDescriptor(_class2$6.prototype, "checkMark"), _class2$6.prototype), _initializer$6 = applyDecoratedInitializer(_class2$6.prototype, "checkEvents", [_dec5$4, serializable$j], function () {
        return [];
      }), _initializer2$6 = applyDecoratedInitializer(_class2$6.prototype, "_isChecked", [serializable$j], function () {
        return true;
      }), _initializer3$4 = applyDecoratedInitializer(_class2$6.prototype, "_checkMark", [serializable$j], function () {
        return null;
      })), _class2$6)) || _class$8) || _class$8) || _class$8));
      legacyCC.Toggle = Toggle;

      var _dec$7, _dec2$6, _dec3$6, _class$7, _class2$5, _initializer$5, _initializer2$5;
      var ToggleContainer = exports('fs', (_dec$7 = ccclass$n('cc.ToggleContainer'), _dec2$6 = executionOrder$1(110), _dec3$6 = type$7([EventHandler]), _dec$7(_class$7 = _dec2$6(_class$7 = (_class2$5 = function (_Component) {
        _inheritsLoose(ToggleContainer, _Component);
        function ToggleContainer() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Component.call.apply(_Component, [this].concat(args)) || this;
          _this._allowSwitchOff = _initializer$5 && _initializer$5();
          _this.checkEvents = _initializer2$5 && _initializer2$5();
          return _this;
        }
        var _proto = ToggleContainer.prototype;
        _proto.onEnable = function onEnable() {
          this.ensureValidState();
          this.node.on(NodeEventType.CHILD_ADDED, this.ensureValidState, this);
          this.node.on(NodeEventType.CHILD_REMOVED, this.ensureValidState, this);
        };
        _proto.onDisable = function onDisable() {
          this.node.off(NodeEventType.CHILD_ADDED, this.ensureValidState, this);
          this.node.off(NodeEventType.CHILD_REMOVED, this.ensureValidState, this);
        };
        _proto.activeToggles = function activeToggles() {
          return this.toggleItems.filter(function (x) {
            return x.isChecked;
          });
        };
        _proto.anyTogglesChecked = function anyTogglesChecked() {
          return !!this.toggleItems.find(function (x) {
            return x.isChecked;
          });
        };
        _proto.notifyToggleCheck = function notifyToggleCheck(toggle, emitEvent) {
          if (emitEvent === void 0) {
            emitEvent = true;
          }
          if (!this.enabledInHierarchy) {
            return;
          }
          for (var i = 0; i < this.toggleItems.length; i++) {
            var item = this.toggleItems[i];
            if (item === toggle) {
              continue;
            }
            if (emitEvent) {
              item.isChecked = false;
            } else {
              item.setIsCheckedWithoutNotify(false);
            }
          }
          if (this.checkEvents) {
            legacyCC.Component.EventHandler.emitEvents(this.checkEvents, toggle);
          }
        };
        _proto.ensureValidState = function ensureValidState() {
          var toggles = this.toggleItems;
          if (!this._allowSwitchOff && !this.anyTogglesChecked() && toggles.length !== 0) {
            var toggle = toggles[0];
            toggle.isChecked = true;
            this.notifyToggleCheck(toggle);
          }
          var activeToggles = this.activeToggles();
          if (activeToggles.length > 1) {
            var firstToggle = activeToggles[0];
            for (var i = 0; i < activeToggles.length; ++i) {
              var _toggle = activeToggles[i];
              if (_toggle === firstToggle) {
                continue;
              }
              _toggle.isChecked = false;
            }
          }
        };
        _createClass(ToggleContainer, [{
          key: "allowSwitchOff",
          get: function get() {
            return this._allowSwitchOff;
          },
          set: function set(value) {
            this._allowSwitchOff = value;
          }
        }, {
          key: "toggleItems",
          get: function get() {
            return this.node.children.map(function (item) {
              var toggle = item.getComponent('cc.Toggle');
              if (toggle && toggle.enabled) {
                return toggle;
              }
              return null;
            }).filter(Boolean);
          }
        }]);
        return ToggleContainer;
      }(Component), (_initializer$5 = applyDecoratedInitializer(_class2$5.prototype, "_allowSwitchOff", [serializable$j], function () {
        return false;
      }), _initializer2$5 = applyDecoratedInitializer(_class2$5.prototype, "checkEvents", [_dec3$6, serializable$j], function () {
        return [];
      })), _class2$5)) || _class$7) || _class$7));
      legacyCC.ToggleContainer = ToggleContainer;

      var _dec$6, _dec2$5, _dec3$5, _dec4$3, _dec5$3, _class$6, _class2$4, _initializer$4, _initializer2$4, _initializer3$3, _initializer4$3, _initializer5$2, _initializer6$1, _initializer7$1, _initializer8$1, _initializer9$1, _initializer10$1, _initializer11$1, _initializer12$1, _initializer13, _initializer14, _initializer15, _initializer16, _initializer17, _initializer18, _class3$2;
      var _tempScale = new Vec2();
      function getReadonlyNodeSize(parent) {
        if (parent instanceof Scene) {
          return visibleRect;
        } else if (parent._uiProps.uiTransformComp) {
          return parent._uiProps.uiTransformComp.contentSize;
        } else {
          return Size$1.ZERO;
        }
      }
      function computeInverseTransForTarget(widgetNode, target, out_inverseTranslate, out_inverseScale) {
        if (widgetNode.parent) {
          _tempScale.set(widgetNode.parent.getScale().x, widgetNode.parent.getScale().y);
        } else {
          _tempScale.set(0, 0);
        }
        var scaleX = _tempScale.x;
        var scaleY = _tempScale.y;
        var translateX = 0;
        var translateY = 0;
        for (var node = widgetNode.parent;;) {
          if (!node) {
            out_inverseTranslate.x = out_inverseTranslate.y = 0;
            out_inverseScale.x = out_inverseScale.y = 1;
            return;
          }
          var pos = node.getPosition();
          translateX += pos.x;
          translateY += pos.y;
          node = node.parent;
          if (node !== target) {
            if (node) {
              _tempScale.set(node.getScale().x, node.getScale().y);
            } else {
              _tempScale.set(0, 0);
            }
            var sx = _tempScale.x;
            var sy = _tempScale.y;
            translateX *= sx;
            translateY *= sy;
            scaleX *= sx;
            scaleY *= sy;
          } else {
            break;
          }
        }
        out_inverseScale.x = scaleX !== 0 ? 1 / scaleX : 1;
        out_inverseScale.y = scaleY !== 0 ? 1 / scaleY : 1;
        out_inverseTranslate.x = -translateX;
        out_inverseTranslate.y = -translateY;
      }
      var AlignMode;
      (function (AlignMode) {
        AlignMode[AlignMode["ONCE"] = 0] = "ONCE";
        AlignMode[AlignMode["ALWAYS"] = 1] = "ALWAYS";
        AlignMode[AlignMode["ON_WINDOW_RESIZE"] = 2] = "ON_WINDOW_RESIZE";
      })(AlignMode || (AlignMode = {}));
      ccenum(AlignMode);
      var AlignFlags;
      (function (AlignFlags) {
        AlignFlags[AlignFlags["TOP"] = 1] = "TOP";
        AlignFlags[AlignFlags["MID"] = 2] = "MID";
        AlignFlags[AlignFlags["BOT"] = 4] = "BOT";
        AlignFlags[AlignFlags["LEFT"] = 8] = "LEFT";
        AlignFlags[AlignFlags["CENTER"] = 16] = "CENTER";
        AlignFlags[AlignFlags["RIGHT"] = 32] = "RIGHT";
        AlignFlags[AlignFlags["HORIZONTAL"] = 56] = "HORIZONTAL";
        AlignFlags[AlignFlags["VERTICAL"] = 7] = "VERTICAL";
      })(AlignFlags || (AlignFlags = {}));
      var TOP_BOT = AlignFlags.TOP | AlignFlags.BOT;
      var LEFT_RIGHT = AlignFlags.LEFT | AlignFlags.RIGHT;
      var Widget = exports('fu', (_dec$6 = ccclass$n('cc.Widget'), _dec2$5 = executionOrder$1(110), _dec3$5 = requireComponent(UITransform), _dec4$3 = type$7(Node$1), _dec5$3 = type$7(AlignMode), _dec$6(_class$6 = _dec2$5(_class$6 = _dec3$5(_class$6 = (_class2$4 = (_class3$2 = function (_Component) {
        _inheritsLoose(Widget, _Component);
        function Widget() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Component.call.apply(_Component, [this].concat(args)) || this;
          _this._lastPos = new Vec3();
          _this._lastSize = new Size$1();
          _this._dirty = true;
          _this._hadAlignOnce = false;
          _this._alignFlags = _initializer$4 && _initializer$4();
          _this._target = _initializer2$4 && _initializer2$4();
          _this._left = _initializer3$3 && _initializer3$3();
          _this._right = _initializer4$3 && _initializer4$3();
          _this._top = _initializer5$2 && _initializer5$2();
          _this._bottom = _initializer6$1 && _initializer6$1();
          _this._horizontalCenter = _initializer7$1 && _initializer7$1();
          _this._verticalCenter = _initializer8$1 && _initializer8$1();
          _this._isAbsLeft = _initializer9$1 && _initializer9$1();
          _this._isAbsRight = _initializer10$1 && _initializer10$1();
          _this._isAbsTop = _initializer11$1 && _initializer11$1();
          _this._isAbsBottom = _initializer12$1 && _initializer12$1();
          _this._isAbsHorizontalCenter = _initializer13 && _initializer13();
          _this._isAbsVerticalCenter = _initializer14 && _initializer14();
          _this._originalWidth = _initializer15 && _initializer15();
          _this._originalHeight = _initializer16 && _initializer16();
          _this._alignMode = _initializer17 && _initializer17();
          _this._lockFlags = _initializer18 && _initializer18();
          return _this;
        }
        var _proto = Widget.prototype;
        _proto.updateAlignment = function updateAlignment() {
          legacyCC._widgetManager.updateAlignment(this.node);
        };
        _proto._validateTargetInDEV = function _validateTargetInDEV() {
          {
            return;
          }
        };
        _proto.setDirty = function setDirty() {
          this._recursiveDirty();
        };
        _proto.onEnable = function onEnable() {
          this.node.getPosition(this._lastPos);
          this._lastSize.set(this.node._uiProps.uiTransformComp.contentSize);
          legacyCC._widgetManager.add(this);
          this._hadAlignOnce = false;
          this._registerEvent();
          this._registerTargetEvents();
        };
        _proto.onDisable = function onDisable() {
          legacyCC._widgetManager.remove(this);
          this._unregisterEvent();
          this._unregisterTargetEvents();
        };
        _proto.onDestroy = function onDestroy() {
          this._removeParentEvent();
        };
        _proto._adjustWidgetToAllowMovingInEditor = function _adjustWidgetToAllowMovingInEditor(eventType) {};
        _proto._adjustWidgetToAllowResizingInEditor = function _adjustWidgetToAllowResizingInEditor() {};
        _proto._adjustWidgetToAnchorChanged = function _adjustWidgetToAnchorChanged() {
          this.setDirty();
        };
        _proto._adjustTargetToParentChanged = function _adjustTargetToParentChanged(oldParent) {
          if (oldParent) {
            this._unregisterOldParentEvents(oldParent);
          }
          if (this.node.getParent()) {
            this._registerTargetEvents();
          }
          this._setDirtyByMode();
        };
        _proto._registerEvent = function _registerEvent() {
          {
            this.node.on(NodeEventType.TRANSFORM_CHANGED, this._setDirtyByMode, this);
            this.node.on(NodeEventType.SIZE_CHANGED, this._setDirtyByMode, this);
          }
          this.node.on(NodeEventType.ANCHOR_CHANGED, this._adjustWidgetToAnchorChanged, this);
          this.node.on(NodeEventType.PARENT_CHANGED, this._adjustTargetToParentChanged, this);
        };
        _proto._unregisterEvent = function _unregisterEvent() {
          {
            this.node.off(NodeEventType.TRANSFORM_CHANGED, this._setDirtyByMode, this);
            this.node.off(NodeEventType.SIZE_CHANGED, this._setDirtyByMode, this);
          }
          this.node.off(NodeEventType.ANCHOR_CHANGED, this._adjustWidgetToAnchorChanged, this);
        };
        _proto._removeParentEvent = function _removeParentEvent() {
          this.node.off(NodeEventType.PARENT_CHANGED, this._adjustTargetToParentChanged, this);
        };
        _proto._autoChangedValue = function _autoChangedValue(flag, isAbs) {
          var current = (this._alignFlags & flag) > 0;
          if (!current) {
            return;
          }
          var parentUiProps = this.node.parent && this.node.parent._uiProps;
          var parentTrans = parentUiProps && parentUiProps.uiTransformComp;
          var size = parentTrans ? parentTrans.contentSize : visibleRect;
          if (this.isAlignLeft && flag === AlignFlags.LEFT) {
            this._left = isAbs ? this._left * size.width : this._left / size.width;
          } else if (this.isAlignRight && flag === AlignFlags.RIGHT) {
            this._right = isAbs ? this._right * size.width : this._right / size.width;
          } else if (this.isAlignHorizontalCenter && flag === AlignFlags.CENTER) {
            this._horizontalCenter = isAbs ? this._horizontalCenter * size.width : this._horizontalCenter / size.width;
          } else if (this.isAlignTop && flag === AlignFlags.TOP) {
            this._top = isAbs ? this._top * size.height : this._top / size.height;
          } else if (this.isAlignBottom && flag === AlignFlags.BOT) {
            this._bottom = isAbs ? this._bottom * size.height : this._bottom / size.height;
          } else if (this.isAbsoluteVerticalCenter && flag === AlignFlags.MID) {
            this._verticalCenter = isAbs ? this._verticalCenter / size.height : this._verticalCenter / size.height;
          }
          this._recursiveDirty();
        };
        _proto._registerTargetEvents = function _registerTargetEvents() {
          var target = this._target || this.node.parent;
          if (target) {
            if (target.getComponent(UITransform)) {
              target.on(NodeEventType.TRANSFORM_CHANGED, this._setDirtyByMode, this);
              target.on(NodeEventType.SIZE_CHANGED, this._setDirtyByMode, this);
              target.on(NodeEventType.ANCHOR_CHANGED, this._setDirtyByMode, this);
            }
          }
        };
        _proto._unregisterTargetEvents = function _unregisterTargetEvents() {
          var target = this._target || this.node.parent;
          if (target) {
            target.off(NodeEventType.TRANSFORM_CHANGED, this._setDirtyByMode, this);
            target.off(NodeEventType.SIZE_CHANGED, this._setDirtyByMode, this);
            target.off(NodeEventType.ANCHOR_CHANGED, this._setDirtyByMode, this);
          }
        };
        _proto._unregisterOldParentEvents = function _unregisterOldParentEvents(oldParent) {
          var target = this._target || oldParent;
          if (target) {
            target.off(NodeEventType.TRANSFORM_CHANGED, this._setDirtyByMode, this);
            target.off(NodeEventType.SIZE_CHANGED, this._setDirtyByMode, this);
          }
        };
        _proto._setDirtyByMode = function _setDirtyByMode() {
          if (this.alignMode === AlignMode.ALWAYS || EDITOR_NOT_IN_PREVIEW) {
            this._recursiveDirty();
          }
        };
        _proto._setAlign = function _setAlign(flag, isAlign) {
          var current = (this._alignFlags & flag) > 0;
          if (isAlign === current) {
            return;
          }
          var isHorizontal = (flag & LEFT_RIGHT) > 0;
          var trans = this.node._uiProps.uiTransformComp;
          if (isAlign) {
            this._alignFlags |= flag;
            if (isHorizontal) {
              this.isAlignHorizontalCenter = false;
              if (this.isStretchWidth) {
                this._originalWidth = trans.width;
              }
            } else {
              this.isAlignVerticalCenter = false;
              if (this.isStretchHeight) {
                this._originalHeight = trans.height;
              }
            }
          } else {
            if (isHorizontal) {
              if (this.isStretchWidth) {
                trans.width = this._originalWidth;
              }
            } else if (this.isStretchHeight) {
              trans.height = this._originalHeight;
            }
            this._alignFlags &= ~flag;
          }
        };
        _proto._recursiveDirty = function _recursiveDirty() {
          if (this._dirty) {
            return;
          }
          this._dirty = true;
        };
        _createClass(Widget, [{
          key: "target",
          get: function get() {
            return this._target;
          },
          set: function set(value) {
            if (this._target === value) {
              return;
            }
            this._unregisterTargetEvents();
            this._target = value;
            this._registerTargetEvents();
            this._validateTargetInDEV();
            this._recursiveDirty();
          }
        }, {
          key: "isAlignTop",
          get: function get() {
            return (this._alignFlags & AlignFlags.TOP) > 0;
          },
          set: function set(value) {
            this._setAlign(AlignFlags.TOP, value);
            this._recursiveDirty();
          }
        }, {
          key: "isAlignBottom",
          get: function get() {
            return (this._alignFlags & AlignFlags.BOT) > 0;
          },
          set: function set(value) {
            this._setAlign(AlignFlags.BOT, value);
            this._recursiveDirty();
          }
        }, {
          key: "isAlignLeft",
          get: function get() {
            return (this._alignFlags & AlignFlags.LEFT) > 0;
          },
          set: function set(value) {
            this._setAlign(AlignFlags.LEFT, value);
            this._recursiveDirty();
          }
        }, {
          key: "isAlignRight",
          get: function get() {
            return (this._alignFlags & AlignFlags.RIGHT) > 0;
          },
          set: function set(value) {
            this._setAlign(AlignFlags.RIGHT, value);
            this._recursiveDirty();
          }
        }, {
          key: "isAlignVerticalCenter",
          get: function get() {
            return (this._alignFlags & AlignFlags.MID) > 0;
          },
          set: function set(value) {
            if (value) {
              this.isAlignTop = false;
              this.isAlignBottom = false;
              this._alignFlags |= AlignFlags.MID;
            } else {
              this._alignFlags &= ~AlignFlags.MID;
            }
            this._recursiveDirty();
          }
        }, {
          key: "isAlignHorizontalCenter",
          get: function get() {
            return (this._alignFlags & AlignFlags.CENTER) > 0;
          },
          set: function set(value) {
            if (value) {
              this.isAlignLeft = false;
              this.isAlignRight = false;
              this._alignFlags |= AlignFlags.CENTER;
            } else {
              this._alignFlags &= ~AlignFlags.CENTER;
            }
            this._recursiveDirty();
          }
        }, {
          key: "isStretchWidth",
          get: function get() {
            return (this._alignFlags & LEFT_RIGHT) === LEFT_RIGHT;
          }
        }, {
          key: "isStretchHeight",
          get: function get() {
            return (this._alignFlags & TOP_BOT) === TOP_BOT;
          }
        }, {
          key: "top",
          get: function get() {
            return this._top;
          },
          set: function set(value) {
            this._top = value;
            this._recursiveDirty();
          }
        }, {
          key: "editorTop",
          get: function get() {
            return this._isAbsTop ? this._top : this._top * 100;
          },
          set: function set(value) {
            this._top = this._isAbsTop ? value : value / 100;
            this._recursiveDirty();
          }
        }, {
          key: "bottom",
          get: function get() {
            return this._bottom;
          },
          set: function set(value) {
            this._bottom = value;
            this._recursiveDirty();
          }
        }, {
          key: "editorBottom",
          get: function get() {
            return this._isAbsBottom ? this._bottom : this._bottom * 100;
          },
          set: function set(value) {
            this._bottom = this._isAbsBottom ? value : value / 100;
            this._recursiveDirty();
          }
        }, {
          key: "left",
          get: function get() {
            return this._left;
          },
          set: function set(value) {
            this._left = value;
            this._recursiveDirty();
          }
        }, {
          key: "editorLeft",
          get: function get() {
            return this._isAbsLeft ? this._left : this._left * 100;
          },
          set: function set(value) {
            this._left = this._isAbsLeft ? value : value / 100;
            this._recursiveDirty();
          }
        }, {
          key: "right",
          get: function get() {
            return this._right;
          },
          set: function set(value) {
            this._right = value;
            this._recursiveDirty();
          }
        }, {
          key: "editorRight",
          get: function get() {
            return this._isAbsRight ? this._right : this._right * 100;
          },
          set: function set(value) {
            this._right = this._isAbsRight ? value : value / 100;
            this._recursiveDirty();
          }
        }, {
          key: "horizontalCenter",
          get: function get() {
            return this._horizontalCenter;
          },
          set: function set(value) {
            this._horizontalCenter = value;
            this._recursiveDirty();
          }
        }, {
          key: "editorHorizontalCenter",
          get: function get() {
            return this._isAbsHorizontalCenter ? this._horizontalCenter : this._horizontalCenter * 100;
          },
          set: function set(value) {
            this._horizontalCenter = this._isAbsHorizontalCenter ? value : value / 100;
            this._recursiveDirty();
          }
        }, {
          key: "verticalCenter",
          get: function get() {
            return this._verticalCenter;
          },
          set: function set(value) {
            this._verticalCenter = value;
            this._recursiveDirty();
          }
        }, {
          key: "editorVerticalCenter",
          get: function get() {
            return this._isAbsVerticalCenter ? this._verticalCenter : this._verticalCenter * 100;
          },
          set: function set(value) {
            this._verticalCenter = this._isAbsVerticalCenter ? value : value / 100;
            this._recursiveDirty();
          }
        }, {
          key: "isAbsoluteTop",
          get: function get() {
            return this._isAbsTop;
          },
          set: function set(value) {
            if (this._isAbsTop === value) {
              return;
            }
            this._isAbsTop = value;
            this._autoChangedValue(AlignFlags.TOP, this._isAbsTop);
          }
        }, {
          key: "isAbsoluteBottom",
          get: function get() {
            return this._isAbsBottom;
          },
          set: function set(value) {
            if (this._isAbsBottom === value) {
              return;
            }
            this._isAbsBottom = value;
            this._autoChangedValue(AlignFlags.BOT, this._isAbsBottom);
          }
        }, {
          key: "isAbsoluteLeft",
          get: function get() {
            return this._isAbsLeft;
          },
          set: function set(value) {
            if (this._isAbsLeft === value) {
              return;
            }
            this._isAbsLeft = value;
            this._autoChangedValue(AlignFlags.LEFT, this._isAbsLeft);
          }
        }, {
          key: "isAbsoluteRight",
          get: function get() {
            return this._isAbsRight;
          },
          set: function set(value) {
            if (this._isAbsRight === value) {
              return;
            }
            this._isAbsRight = value;
            this._autoChangedValue(AlignFlags.RIGHT, this._isAbsRight);
          }
        }, {
          key: "isAbsoluteHorizontalCenter",
          get: function get() {
            return this._isAbsHorizontalCenter;
          },
          set: function set(value) {
            if (this._isAbsHorizontalCenter === value) {
              return;
            }
            this._isAbsHorizontalCenter = value;
            this._autoChangedValue(AlignFlags.CENTER, this._isAbsHorizontalCenter);
          }
        }, {
          key: "isAbsoluteVerticalCenter",
          get: function get() {
            return this._isAbsVerticalCenter;
          },
          set: function set(value) {
            if (this._isAbsVerticalCenter === value) {
              return;
            }
            this._isAbsVerticalCenter = value;
            this._autoChangedValue(AlignFlags.MID, this._isAbsVerticalCenter);
          }
        }, {
          key: "alignMode",
          get: function get() {
            return this._alignMode;
          },
          set: function set(value) {
            this._alignMode = value;
            this._recursiveDirty();
          }
        }, {
          key: "alignFlags",
          get: function get() {
            return this._alignFlags;
          },
          set: function set(value) {
            if (this._alignFlags === value) {
              return;
            }
            this._alignFlags = value;
            this._recursiveDirty();
          }
        }]);
        return Widget;
      }(Component), _class3$2.AlignMode = AlignMode, _class3$2), (_applyDecoratedDescriptor(_class2$4.prototype, "target", [_dec4$3], Object.getOwnPropertyDescriptor(_class2$4.prototype, "target"), _class2$4.prototype), _applyDecoratedDescriptor(_class2$4.prototype, "alignMode", [_dec5$3], Object.getOwnPropertyDescriptor(_class2$4.prototype, "alignMode"), _class2$4.prototype), _initializer$4 = applyDecoratedInitializer(_class2$4.prototype, "_alignFlags", [serializable$j], function () {
        return 0;
      }), _initializer2$4 = applyDecoratedInitializer(_class2$4.prototype, "_target", [serializable$j], function () {
        return null;
      }), _initializer3$3 = applyDecoratedInitializer(_class2$4.prototype, "_left", [serializable$j], function () {
        return 0;
      }), _initializer4$3 = applyDecoratedInitializer(_class2$4.prototype, "_right", [serializable$j], function () {
        return 0;
      }), _initializer5$2 = applyDecoratedInitializer(_class2$4.prototype, "_top", [serializable$j], function () {
        return 0;
      }), _initializer6$1 = applyDecoratedInitializer(_class2$4.prototype, "_bottom", [serializable$j], function () {
        return 0;
      }), _initializer7$1 = applyDecoratedInitializer(_class2$4.prototype, "_horizontalCenter", [serializable$j], function () {
        return 0;
      }), _initializer8$1 = applyDecoratedInitializer(_class2$4.prototype, "_verticalCenter", [serializable$j], function () {
        return 0;
      }), _initializer9$1 = applyDecoratedInitializer(_class2$4.prototype, "_isAbsLeft", [serializable$j], function () {
        return true;
      }), _initializer10$1 = applyDecoratedInitializer(_class2$4.prototype, "_isAbsRight", [serializable$j], function () {
        return true;
      }), _initializer11$1 = applyDecoratedInitializer(_class2$4.prototype, "_isAbsTop", [serializable$j], function () {
        return true;
      }), _initializer12$1 = applyDecoratedInitializer(_class2$4.prototype, "_isAbsBottom", [serializable$j], function () {
        return true;
      }), _initializer13 = applyDecoratedInitializer(_class2$4.prototype, "_isAbsHorizontalCenter", [serializable$j], function () {
        return true;
      }), _initializer14 = applyDecoratedInitializer(_class2$4.prototype, "_isAbsVerticalCenter", [serializable$j], function () {
        return true;
      }), _initializer15 = applyDecoratedInitializer(_class2$4.prototype, "_originalWidth", [serializable$j], function () {
        return 0;
      }), _initializer16 = applyDecoratedInitializer(_class2$4.prototype, "_originalHeight", [serializable$j], function () {
        return 0;
      }), _initializer17 = applyDecoratedInitializer(_class2$4.prototype, "_alignMode", [serializable$j], function () {
        return AlignMode.ON_WINDOW_RESIZE;
      }), _initializer18 = applyDecoratedInitializer(_class2$4.prototype, "_lockFlags", [serializable$j, editorOnly], function () {
        return 0;
      })), _class2$4)) || _class$6) || _class$6) || _class$6));
      legacyCC.internal.computeInverseTransForTarget = computeInverseTransForTarget;
      legacyCC.internal.getReadonlyNodeSize = getReadonlyNodeSize;
      legacyCC.Widget = Widget;

      var _dec$5, _dec2$4, _dec3$4, _dec4$2, _dec5$2, _class$5, _class2$3, _initializer$3, _initializer2$3, _initializer3$2, _initializer4$2, _class3$1;
      var _color = new Color$1();
      var Direction$1;
      (function (Direction) {
        Direction[Direction["HORIZONTAL"] = 0] = "HORIZONTAL";
        Direction[Direction["VERTICAL"] = 1] = "VERTICAL";
      })(Direction$1 || (Direction$1 = {}));
      ccenum(Direction$1);
      var PageViewIndicator = exports('fw', (_dec$5 = ccclass$n('cc.PageViewIndicator'), _dec2$4 = executionOrder$1(110), _dec3$4 = type$7(SpriteFrame), _dec4$2 = type$7(Direction$1), _dec5$2 = type$7(Size$1), _dec$5(_class$5 = _dec2$4(_class$5 = (_class2$3 = (_class3$1 = function (_Component) {
        _inheritsLoose(PageViewIndicator, _Component);
        function PageViewIndicator() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Component.call.apply(_Component, [this].concat(args)) || this;
          _this.spacing = _initializer$3 && _initializer$3();
          _this._spriteFrame = _initializer2$3 && _initializer2$3();
          _this._direction = _initializer3$2 && _initializer3$2();
          _this._cellSize = _initializer4$2 && _initializer4$2();
          _this._layout = null;
          _this._pageView = null;
          _this._indicators = [];
          return _this;
        }
        var _proto = PageViewIndicator.prototype;
        _proto.onLoad = function onLoad() {
          this._updateLayout();
        };
        _proto.setPageView = function setPageView(target) {
          this._pageView = target;
          this._refresh();
        };
        _proto._updateLayout = function _updateLayout() {
          this._layout = this.getComponent(Layout);
          if (!this._layout) {
            this._layout = this.addComponent(Layout);
          }
          var layout = this._layout;
          if (this.direction === Direction$1.HORIZONTAL) {
            layout.type = Layout.Type.HORIZONTAL;
            layout.spacingX = this.spacing;
          } else if (this.direction === Direction$1.VERTICAL) {
            layout.type = Layout.Type.VERTICAL;
            layout.spacingY = this.spacing;
          }
          layout.resizeMode = Layout.ResizeMode.CONTAINER;
        };
        _proto._createIndicator = function _createIndicator() {
          var node = new Node$1();
          node.layer = this.node.layer;
          var sprite = node.addComponent(Sprite);
          sprite.spriteFrame = this.spriteFrame;
          sprite.sizeMode = Sprite.SizeMode.CUSTOM;
          node.parent = this.node;
          node._uiProps.uiTransformComp.setContentSize(this._cellSize);
          return node;
        };
        _proto._changedState = function _changedState() {
          var indicators = this._indicators;
          if (indicators.length === 0 || !this._pageView) {
            return;
          }
          var idx = this._pageView.curPageIdx;
          if (idx >= indicators.length) {
            return;
          }
          for (var i = 0; i < indicators.length; ++i) {
            var node = indicators[i];
            if (!node._uiProps.uiComp) {
              continue;
            }
            var uiComp = node._uiProps.uiComp;
            _color.set(uiComp.color);
            _color.a = 255 / 2;
            uiComp.color = _color;
          }
          if (indicators[idx]._uiProps.uiComp) {
            var comp = indicators[idx]._uiProps.uiComp;
            _color.set(comp.color);
            _color.a = 255;
            comp.color = _color;
          }
        };
        _proto._refresh = function _refresh() {
          if (!this._pageView) {
            return;
          }
          var indicators = this._indicators;
          var pages = this._pageView.getPages();
          if (pages.length === indicators.length) {
            return;
          }
          var i = 0;
          if (pages.length > indicators.length) {
            for (i = 0; i < pages.length; ++i) {
              if (!indicators[i]) {
                indicators[i] = this._createIndicator();
              }
            }
          } else {
            var count = indicators.length - pages.length;
            for (i = count; i > 0; --i) {
              var node = indicators[i - 1];
              this.node.removeChild(node);
              indicators.splice(i - 1, 1);
            }
          }
          if (this._layout && this._layout.enabledInHierarchy) {
            this._layout.updateLayout();
          }
          this._changedState();
        };
        _createClass(PageViewIndicator, [{
          key: "spriteFrame",
          get: function get() {
            return this._spriteFrame;
          },
          set: function set(value) {
            if (this._spriteFrame === value) {
              return;
            }
            this._spriteFrame = value;
          }
        }, {
          key: "direction",
          get: function get() {
            return this._direction;
          },
          set: function set(value) {
            if (this._direction === value) {
              return;
            }
            this._direction = value;
          }
        }, {
          key: "cellSize",
          get: function get() {
            return this._cellSize;
          },
          set: function set(value) {
            if (this._cellSize === value) {
              return;
            }
            this._cellSize = value;
          }
        }]);
        return PageViewIndicator;
      }(Component), _class3$1.Direction = Direction$1, _class3$1), (_applyDecoratedDescriptor(_class2$3.prototype, "spriteFrame", [_dec3$4], Object.getOwnPropertyDescriptor(_class2$3.prototype, "spriteFrame"), _class2$3.prototype), _applyDecoratedDescriptor(_class2$3.prototype, "direction", [_dec4$2], Object.getOwnPropertyDescriptor(_class2$3.prototype, "direction"), _class2$3.prototype), _applyDecoratedDescriptor(_class2$3.prototype, "cellSize", [_dec5$2], Object.getOwnPropertyDescriptor(_class2$3.prototype, "cellSize"), _class2$3.prototype), _initializer$3 = applyDecoratedInitializer(_class2$3.prototype, "spacing", [serializable$j], function () {
        return 0;
      }), _initializer2$3 = applyDecoratedInitializer(_class2$3.prototype, "_spriteFrame", [serializable$j], function () {
        return null;
      }), _initializer3$2 = applyDecoratedInitializer(_class2$3.prototype, "_direction", [serializable$j], function () {
        return Direction$1.HORIZONTAL;
      }), _initializer4$2 = applyDecoratedInitializer(_class2$3.prototype, "_cellSize", [serializable$j], function () {
        return new Size$1(20, 20);
      })), _class2$3)) || _class$5) || _class$5));
      legacyCC.PageViewIndicator = PageViewIndicator;

      var _dec$4, _dec2$3, _dec3$3, _dec4$1, _dec5$1, _dec6, _dec7, _dec8, _dec9, _class$4, _class2$2, _initializer$2, _initializer2$2, _initializer3$1, _initializer4$1, _initializer5$1, _initializer6, _initializer7, _initializer8, _initializer9, _initializer10, _initializer11, _initializer12, _class3;
      var _tempVec2 = new Vec2();
      var SizeMode;
      (function (SizeMode) {
        SizeMode[SizeMode["Unified"] = 0] = "Unified";
        SizeMode[SizeMode["Free"] = 1] = "Free";
      })(SizeMode || (SizeMode = {}));
      ccenum(SizeMode);
      var Direction;
      (function (Direction) {
        Direction[Direction["Horizontal"] = 0] = "Horizontal";
        Direction[Direction["Vertical"] = 1] = "Vertical";
      })(Direction || (Direction = {}));
      ccenum(Direction);
      var EventType;
      (function (EventType) {
        EventType["PAGE_TURNING"] = "page-turning";
      })(EventType || (EventType = {}));
      var PageView = exports('fv', (_dec$4 = ccclass$n('cc.PageView'), _dec2$3 = executionOrder$1(110), _dec3$3 = type$7(SizeMode), _dec4$1 = type$7(Direction), _dec5$1 = type$7(PageViewIndicator), _dec6 = type$7(ScrollBar), _dec7 = type$7(ScrollBar), _dec8 = type$7([EventHandler]), _dec9 = type$7([EventHandler]), _dec$4(_class$4 = _dec2$3(_class$4 = (_class2$2 = (_class3 = function (_ScrollView) {
        _inheritsLoose(PageView, _ScrollView);
        function PageView() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _ScrollView.call.apply(_ScrollView, [this].concat(args)) || this;
          _this.autoPageTurningThreshold = _initializer$2 && _initializer$2();
          _this.horizontal = _initializer2$2 && _initializer2$2();
          _this.vertical = _initializer3$1 && _initializer3$1();
          _this.cancelInnerEvents = _initializer4$1 && _initializer4$1();
          _this.scrollEvents = _initializer5$1 && _initializer5$1();
          _this.pageTurningSpeed = _initializer6 && _initializer6();
          _this.pageEvents = _initializer7 && _initializer7();
          _this._sizeMode = _initializer8 && _initializer8();
          _this._direction = _initializer9 && _initializer9();
          _this._scrollThreshold = _initializer10 && _initializer10();
          _this._pageTurningEventTiming = _initializer11 && _initializer11();
          _this._indicator = _initializer12 && _initializer12();
          _this._curPageIdx = 0;
          _this._lastPageIdx = 0;
          _this._pages = [];
          _this._initContentPos = new Vec3();
          _this._scrollCenterOffsetX = [];
          _this._scrollCenterOffsetY = [];
          _this._touchBeganPosition = new Vec2();
          _this._touchEndPosition = new Vec2();
          return _this;
        }
        var _proto = PageView.prototype;
        _proto.onEnable = function onEnable() {
          _ScrollView.prototype.onEnable.call(this);
          this.node.on(NodeEventType.SIZE_CHANGED, this._updateAllPagesSize, this);
          {
            this.node.on(PageView.EventType.SCROLL_ENG_WITH_THRESHOLD, this._dispatchPageTurningEvent, this);
          }
        };
        _proto.onDisable = function onDisable() {
          _ScrollView.prototype.onDisable.call(this);
          this.node.off(NodeEventType.SIZE_CHANGED, this._updateAllPagesSize, this);
          {
            this.node.off(PageView.EventType.SCROLL_ENG_WITH_THRESHOLD, this._dispatchPageTurningEvent, this);
          }
        };
        _proto.onLoad = function onLoad() {
          this._initPages();
          if (this.indicator) {
            this.indicator.setPageView(this);
          }
        };
        _proto.getCurrentPageIndex = function getCurrentPageIndex() {
          return this._curPageIdx;
        };
        _proto.setCurrentPageIndex = function setCurrentPageIndex(index) {
          this.scrollToPage(index, 1);
        };
        _proto.getPages = function getPages() {
          return this._pages;
        };
        _proto.addPage = function addPage(page) {
          if (!page || this._pages.indexOf(page) !== -1 || !this.content) {
            return;
          }
          if (!page._uiProps.uiTransformComp) {
            logID(4301);
            return;
          }
          this.content.addChild(page);
          this._pages.push(page);
          this._updatePageView();
        };
        _proto.insertPage = function insertPage(page, index) {
          if (index < 0 || !page || this._pages.indexOf(page) !== -1 || !this.content) {
            return;
          }
          var pageCount = this._pages.length;
          if (index >= pageCount) {
            this.addPage(page);
          } else {
            if (!page._uiProps.uiTransformComp) {
              logID(4301);
              return;
            }
            this._pages.splice(index, 0, page);
            this.content.insertChild(page, index);
            this._updatePageView();
          }
        };
        _proto.removePage = function removePage(page) {
          if (!page || !this.content) {
            return;
          }
          var index = this._pages.indexOf(page);
          if (index === -1) {
            warnID(4300, page.name);
            return;
          }
          this.removePageAtIndex(index);
        };
        _proto.removePageAtIndex = function removePageAtIndex(index) {
          var pageList = this._pages;
          if (index < 0 || index >= pageList.length) {
            return;
          }
          var page = pageList[index];
          if (!page || !this.content) {
            return;
          }
          this.content.removeChild(page);
          pageList.splice(index, 1);
          this._updatePageView();
        };
        _proto.removeAllPages = function removeAllPages() {
          if (!this.content) {
            return;
          }
          var locPages = this._pages;
          for (var i = 0, len = locPages.length; i < len; i++) {
            this.content.removeChild(locPages[i]);
          }
          this._pages.length = 0;
          this._updatePageView();
        };
        _proto.scrollToPage = function scrollToPage(idx, timeInSecond) {
          if (timeInSecond === void 0) {
            timeInSecond = 0.3;
          }
          if (idx < 0 || idx >= this._pages.length) {
            return;
          }
          this._curPageIdx = idx;
          this.scrollToOffset(this._moveOffsetValue(idx), timeInSecond, true);
          if (this.indicator) {
            this.indicator._changedState();
          }
        };
        _proto.getScrollEndedEventTiming = function getScrollEndedEventTiming() {
          return this.pageTurningEventTiming;
        };
        _proto._updatePageView = function _updatePageView() {
          if (!this.content) {
            return;
          }
          var layout = this.content.getComponent(Layout);
          if (layout && layout.enabled) {
            layout.updateLayout();
          }
          var pageCount = this._pages.length;
          if (this._curPageIdx >= pageCount) {
            this._curPageIdx = pageCount === 0 ? 0 : pageCount - 1;
            this._lastPageIdx = this._curPageIdx;
          }
          var contentPos = this._initContentPos;
          for (var i = 0; i < pageCount; ++i) {
            var page = this._pages[i];
            var pos = page.position;
            if (this.direction === Direction.Horizontal) {
              this._scrollCenterOffsetX[i] = Math.abs(contentPos.x + pos.x);
            } else {
              this._scrollCenterOffsetY[i] = Math.abs(contentPos.y + pos.y);
            }
          }
          if (this.indicator) {
            this.indicator._refresh();
          }
        };
        _proto._updateAllPagesSize = function _updateAllPagesSize() {
          var viewTrans = this.view;
          if (!this.content || !viewTrans) {
            return;
          }
          if (this._sizeMode !== SizeMode.Unified) {
            return;
          }
          var locPages = this._pages;
          var selfSize = viewTrans.contentSize;
          for (var i = 0, len = locPages.length; i < len; i++) {
            locPages[i]._uiProps.uiTransformComp.setContentSize(selfSize);
          }
        };
        _proto._handleReleaseLogic = function _handleReleaseLogic() {
          this._autoScrollToPage();
          if (this._scrolling) {
            this._scrolling = false;
            if (!this._autoScrolling) {
              this._dispatchEvent(PageView.EventType.SCROLL_ENDED);
            }
          }
        };
        _proto._onTouchBegan = function _onTouchBegan(event, captureListeners) {
          event.touch.getUILocation(_tempVec2);
          Vec2.set(this._touchBeganPosition, _tempVec2.x, _tempVec2.y);
          _ScrollView.prototype._onTouchBegan.call(this, event, captureListeners);
        };
        _proto._onTouchMoved = function _onTouchMoved(event, captureListeners) {
          _ScrollView.prototype._onTouchMoved.call(this, event, captureListeners);
        };
        _proto._onTouchEnded = function _onTouchEnded(event, captureListeners) {
          event.touch.getUILocation(_tempVec2);
          Vec2.set(this._touchEndPosition, _tempVec2.x, _tempVec2.y);
          _ScrollView.prototype._onTouchEnded.call(this, event, captureListeners);
        };
        _proto._onTouchCancelled = function _onTouchCancelled(event, captureListeners) {
          event.touch.getUILocation(_tempVec2);
          Vec2.set(this._touchEndPosition, _tempVec2.x, _tempVec2.y);
          _ScrollView.prototype._onTouchCancelled.call(this, event, captureListeners);
        };
        _proto._onMouseWheel = function _onMouseWheel() {};
        _proto._syncScrollDirection = function _syncScrollDirection() {
          this.horizontal = this.direction === Direction.Horizontal;
          this.vertical = this.direction === Direction.Vertical;
        };
        _proto._syncSizeMode = function _syncSizeMode() {
          var viewTrans = this.view;
          if (!this.content || !viewTrans) {
            return;
          }
          var layout = this.content.getComponent(Layout);
          if (layout) {
            if (this._sizeMode === SizeMode.Free && this._pages.length > 0) {
              var firstPageTrans = this._pages[0]._uiProps.uiTransformComp;
              var lastPageTrans = this._pages[this._pages.length - 1]._uiProps.uiTransformComp;
              if (this.direction === Direction.Horizontal) {
                layout.paddingLeft = (viewTrans.width - firstPageTrans.width) / 2;
                layout.paddingRight = (viewTrans.width - lastPageTrans.width) / 2;
              } else if (this.direction === Direction.Vertical) {
                layout.paddingTop = (viewTrans.height - firstPageTrans.height) / 2;
                layout.paddingBottom = (viewTrans.height - lastPageTrans.height) / 2;
              }
            }
            layout.updateLayout();
          }
        };
        _proto._initPages = function _initPages() {
          if (!this.content) {
            return;
          }
          this._initContentPos = this.content.position;
          var children = this.content.children;
          for (var i = 0; i < children.length; ++i) {
            var page = children[i];
            if (this._pages.indexOf(page) >= 0) {
              continue;
            }
            this._pages.push(page);
          }
          this._syncScrollDirection();
          this._syncSizeMode();
          this._updatePageView();
        };
        _proto._dispatchPageTurningEvent = function _dispatchPageTurningEvent() {
          if (this._lastPageIdx === this._curPageIdx) {
            return;
          }
          this._lastPageIdx = this._curPageIdx;
          EventHandler.emitEvents(this.pageEvents, this, EventType.PAGE_TURNING);
          this.node.emit(EventType.PAGE_TURNING, this);
        };
        _proto._isQuicklyScrollable = function _isQuicklyScrollable(touchMoveVelocity) {
          if (this.direction === Direction.Horizontal) {
            if (Math.abs(touchMoveVelocity.x) > this.autoPageTurningThreshold) {
              return true;
            }
          } else if (this.direction === Direction.Vertical) {
            if (Math.abs(touchMoveVelocity.y) > this.autoPageTurningThreshold) {
              return true;
            }
          }
          return false;
        };
        _proto._moveOffsetValue = function _moveOffsetValue(idx) {
          var offset = new Vec2();
          if (this._sizeMode === SizeMode.Free) {
            if (this.direction === Direction.Horizontal) {
              offset.x = this._scrollCenterOffsetX[idx];
            } else if (this.direction === Direction.Vertical) {
              offset.y = this._scrollCenterOffsetY[idx];
            }
          } else {
            var viewTrans = this.view;
            if (!viewTrans) {
              return offset;
            }
            if (this.direction === Direction.Horizontal) {
              offset.x = idx * viewTrans.width;
            } else if (this.direction === Direction.Vertical) {
              offset.y = idx * viewTrans.height;
            }
          }
          return offset;
        };
        _proto._getDragDirection = function _getDragDirection(moveOffset) {
          if (this._direction === Direction.Horizontal) {
            if (moveOffset.x === 0) {
              return 0;
            }
            return moveOffset.x > 0 ? 1 : -1;
          } else {
            if (moveOffset.y === 0) {
              return 0;
            }
            return moveOffset.y < 0 ? 1 : -1;
          }
        };
        _proto._isScrollable = function _isScrollable(offset, index, nextIndex) {
          if (this._sizeMode === SizeMode.Free) {
            var curPageCenter = 0;
            var nextPageCenter = 0;
            if (this.direction === Direction.Horizontal) {
              curPageCenter = this._scrollCenterOffsetX[index];
              nextPageCenter = this._scrollCenterOffsetX[nextIndex];
              return Math.abs(offset.x) >= Math.abs(curPageCenter - nextPageCenter) * this.scrollThreshold;
            } else if (this.direction === Direction.Vertical) {
              curPageCenter = this._scrollCenterOffsetY[index];
              nextPageCenter = this._scrollCenterOffsetY[nextIndex];
              return Math.abs(offset.y) >= Math.abs(curPageCenter - nextPageCenter) * this.scrollThreshold;
            }
          } else {
            var viewTrans = this.view;
            if (!viewTrans) {
              return false;
            }
            if (this.direction === Direction.Horizontal) {
              return Math.abs(offset.x) >= viewTrans.width * this.scrollThreshold;
            } else if (this.direction === Direction.Vertical) {
              return Math.abs(offset.y) >= viewTrans.height * this.scrollThreshold;
            }
          }
          return false;
        };
        _proto._autoScrollToPage = function _autoScrollToPage() {
          var bounceBackStarted = this._startBounceBackIfNeeded();
          if (bounceBackStarted) {
            var bounceBackAmount = this._getHowMuchOutOfBoundary();
            this._clampDelta(bounceBackAmount);
            if (bounceBackAmount.x > 0 || bounceBackAmount.y < 0) {
              this._curPageIdx = this._pages.length === 0 ? 0 : this._pages.length - 1;
            }
            if (bounceBackAmount.x < 0 || bounceBackAmount.y > 0) {
              this._curPageIdx = 0;
            }
            if (this.indicator) {
              this.indicator._changedState();
            }
          } else {
            var moveOffset = new Vec2();
            Vec2.subtract(moveOffset, this._touchBeganPosition, this._touchEndPosition);
            var index = this._curPageIdx;
            var nextIndex = index + this._getDragDirection(moveOffset);
            var timeInSecond = this.pageTurningSpeed * Math.abs(index - nextIndex);
            if (nextIndex < this._pages.length) {
              if (this._isScrollable(moveOffset, index, nextIndex)) {
                this.scrollToPage(nextIndex, timeInSecond);
                return;
              } else {
                var touchMoveVelocity = this._calculateTouchMoveVelocity();
                if (this._isQuicklyScrollable(touchMoveVelocity)) {
                  this.scrollToPage(nextIndex, timeInSecond);
                  return;
                }
              }
            }
            this.scrollToPage(index, timeInSecond);
          }
        };
        _createClass(PageView, [{
          key: "sizeMode",
          get: function get() {
            return this._sizeMode;
          },
          set: function set(value) {
            if (this._sizeMode === value) {
              return;
            }
            this._sizeMode = value;
            this._syncSizeMode();
          }
        }, {
          key: "direction",
          get: function get() {
            return this._direction;
          },
          set: function set(value) {
            if (this._direction === value) {
              return;
            }
            this._direction = value;
            this._syncScrollDirection();
          }
        }, {
          key: "scrollThreshold",
          get: function get() {
            return this._scrollThreshold;
          },
          set: function set(value) {
            if (this._scrollThreshold === value) {
              return;
            }
            this._scrollThreshold = value;
          }
        }, {
          key: "pageTurningEventTiming",
          get: function get() {
            return this._pageTurningEventTiming;
          },
          set: function set(value) {
            if (this._pageTurningEventTiming === value) {
              return;
            }
            this._pageTurningEventTiming = value;
          }
        }, {
          key: "indicator",
          get: function get() {
            return this._indicator;
          },
          set: function set(value) {
            if (this._indicator === value) {
              return;
            }
            this._indicator = value;
            if (this.indicator) {
              this.indicator.setPageView(this);
            }
          }
        }, {
          key: "curPageIdx",
          get: function get() {
            return this._curPageIdx;
          }
        }, {
          key: "verticalScrollBar",
          get: function get() {
            return _ScrollView.prototype.verticalScrollBar;
          },
          set: function set(value) {
            this.verticalScrollBar = value;
          }
        }, {
          key: "horizontalScrollBar",
          get: function get() {
            return _ScrollView.prototype.horizontalScrollBar;
          },
          set: function set(value) {
            this.horizontalScrollBar = value;
          }
        }]);
        return PageView;
      }(ScrollView), _class3.SizeMode = SizeMode, _class3.Direction = Direction, _class3.EventType = extendsEnum(EventType, EventType$2), _class3), (_applyDecoratedDescriptor(_class2$2.prototype, "sizeMode", [_dec3$3], Object.getOwnPropertyDescriptor(_class2$2.prototype, "sizeMode"), _class2$2.prototype), _applyDecoratedDescriptor(_class2$2.prototype, "direction", [_dec4$1], Object.getOwnPropertyDescriptor(_class2$2.prototype, "direction"), _class2$2.prototype), _applyDecoratedDescriptor(_class2$2.prototype, "indicator", [_dec5$1], Object.getOwnPropertyDescriptor(_class2$2.prototype, "indicator"), _class2$2.prototype), _initializer$2 = applyDecoratedInitializer(_class2$2.prototype, "autoPageTurningThreshold", [serializable$j], function () {
        return 100;
      }), _applyDecoratedDescriptor(_class2$2.prototype, "verticalScrollBar", [_dec6, override], Object.getOwnPropertyDescriptor(_class2$2.prototype, "verticalScrollBar"), _class2$2.prototype), _applyDecoratedDescriptor(_class2$2.prototype, "horizontalScrollBar", [_dec7, override], Object.getOwnPropertyDescriptor(_class2$2.prototype, "horizontalScrollBar"), _class2$2.prototype), _initializer2$2 = applyDecoratedInitializer(_class2$2.prototype, "horizontal", [override, serializable$j], function () {
        return true;
      }), _initializer3$1 = applyDecoratedInitializer(_class2$2.prototype, "vertical", [override, serializable$j], function () {
        return true;
      }), _initializer4$1 = applyDecoratedInitializer(_class2$2.prototype, "cancelInnerEvents", [override, serializable$j], function () {
        return true;
      }), _initializer5$1 = applyDecoratedInitializer(_class2$2.prototype, "scrollEvents", [_dec8, serializable$j, override], function () {
        return [];
      }), _initializer6 = applyDecoratedInitializer(_class2$2.prototype, "pageTurningSpeed", [serializable$j], function () {
        return 0.3;
      }), _initializer7 = applyDecoratedInitializer(_class2$2.prototype, "pageEvents", [_dec9, serializable$j], function () {
        return [];
      }), _initializer8 = applyDecoratedInitializer(_class2$2.prototype, "_sizeMode", [serializable$j], function () {
        return SizeMode.Unified;
      }), _initializer9 = applyDecoratedInitializer(_class2$2.prototype, "_direction", [serializable$j], function () {
        return Direction.Horizontal;
      }), _initializer10 = applyDecoratedInitializer(_class2$2.prototype, "_scrollThreshold", [serializable$j], function () {
        return 0.5;
      }), _initializer11 = applyDecoratedInitializer(_class2$2.prototype, "_pageTurningEventTiming", [serializable$j], function () {
        return 0.1;
      }), _initializer12 = applyDecoratedInitializer(_class2$2.prototype, "_indicator", [serializable$j], function () {
        return null;
      })), _class2$2)) || _class$4) || _class$4));
      legacyCC.PageView = PageView;

      var _tempPos = new Vec3();
      var _defaultAnchor = new Vec2();
      var tInverseTranslate = new Vec2();
      var tInverseScale = new Vec2(1, 1);
      var _tempVec2_1 = new Vec2();
      var _tempVec2_2 = new Vec2();
      function align(node, widget) {
        if (widget._hadAlignOnce) return;
        if (widget.alignMode === AlignMode.ONCE) {
          widget._hadAlignOnce = true;
        }
        var hasTarget = widget.target;
        var target;
        var inverseTranslate = tInverseTranslate;
        var inverseScale = tInverseScale;
        if (hasTarget) {
          target = hasTarget;
          computeInverseTransForTarget(node, target, inverseTranslate, inverseScale);
        } else {
          target = node.parent;
        }
        var targetSize = getReadonlyNodeSize(target);
        var useGlobal = target instanceof Scene || !target.getComponent(UITransform);
        var targetAnchor = useGlobal ? _defaultAnchor : target.getComponent(UITransform).anchorPoint;
        var isRoot = useGlobal;
        node.getPosition(_tempPos);
        var uiTrans = node._uiProps.uiTransformComp;
        var x = _tempPos.x;
        var y = _tempPos.y;
        var anchor = uiTrans.anchorPoint;
        var scale = node.getScale();
        if (widget.alignFlags & AlignFlags.HORIZONTAL) {
          var localLeft = 0;
          var localRight = 0;
          var targetWidth = targetSize.width;
          if (isRoot) {
            localLeft = visibleRect.left.x;
            localRight = visibleRect.right.x;
          } else {
            localLeft = -targetAnchor.x * targetWidth;
            localRight = localLeft + targetWidth;
          }
          localLeft += widget.isAbsoluteLeft ? widget.left : widget.left * targetWidth;
          localRight -= widget.isAbsoluteRight ? widget.right : widget.right * targetWidth;
          if (hasTarget) {
            localLeft += inverseTranslate.x;
            localLeft *= inverseScale.x;
            localRight += inverseTranslate.x;
            localRight *= inverseScale.x;
          }
          var width = 0;
          var anchorX = anchor.x;
          var scaleX = scale.x;
          if (scaleX < 0) {
            anchorX = 1.0 - anchorX;
            scaleX = -scaleX;
          }
          if (widget.isStretchWidth) {
            width = localRight - localLeft;
            if (scaleX !== 0) {
              uiTrans.width = width / scaleX;
            }
            x = localLeft + anchorX * width;
          } else {
            width = uiTrans.width * scaleX;
            if (widget.isAlignHorizontalCenter) {
              var localHorizontalCenter = widget.isAbsoluteHorizontalCenter ? widget.horizontalCenter : widget.horizontalCenter * targetWidth;
              var targetCenter = (0.5 - targetAnchor.x) * targetSize.width;
              if (hasTarget) {
                localHorizontalCenter *= inverseScale.x;
                targetCenter += inverseTranslate.x;
                targetCenter *= inverseScale.x;
              }
              x = targetCenter + (anchorX - 0.5) * width + localHorizontalCenter;
            } else if (widget.isAlignLeft) {
              x = localLeft + anchorX * width;
            } else {
              x = localRight + (anchorX - 1) * width;
            }
            if (!approx(scaleX, 0, EPSILON$3)) {
              width /= scaleX;
            } else {
              width = uiTrans.width;
            }
          }
          widget._lastSize.width = width;
        }
        if (widget.alignFlags & AlignFlags.VERTICAL) {
          var localTop = 0;
          var localBottom = 0;
          var targetHeight = targetSize.height;
          if (isRoot) {
            localBottom = visibleRect.bottom.y;
            localTop = visibleRect.top.y;
          } else {
            localBottom = -targetAnchor.y * targetHeight;
            localTop = localBottom + targetHeight;
          }
          localBottom += widget.isAbsoluteBottom ? widget.bottom : widget.bottom * targetHeight;
          localTop -= widget.isAbsoluteTop ? widget.top : widget.top * targetHeight;
          if (hasTarget) {
            localBottom += inverseTranslate.y;
            localBottom *= inverseScale.y;
            localTop += inverseTranslate.y;
            localTop *= inverseScale.y;
          }
          var height = 0;
          var anchorY = anchor.y;
          var scaleY = scale.y;
          if (scaleY < 0) {
            anchorY = 1.0 - anchorY;
            scaleY = -scaleY;
          }
          if (widget.isStretchHeight) {
            height = localTop - localBottom;
            if (scaleY !== 0) {
              uiTrans.height = height / scaleY;
            }
            y = localBottom + anchorY * height;
          } else {
            height = uiTrans.height * scaleY;
            if (widget.isAlignVerticalCenter) {
              var localVerticalCenter = widget.isAbsoluteVerticalCenter ? widget.verticalCenter : widget.verticalCenter * targetHeight;
              var targetMiddle = (0.5 - targetAnchor.y) * targetSize.height;
              if (hasTarget) {
                localVerticalCenter *= inverseScale.y;
                targetMiddle += inverseTranslate.y;
                targetMiddle *= inverseScale.y;
              }
              y = targetMiddle + (anchorY - 0.5) * height + localVerticalCenter;
            } else if (widget.isAlignBottom) {
              y = localBottom + anchorY * height;
            } else {
              y = localTop + (anchorY - 1) * height;
            }
            if (!approx(scaleY, 0, EPSILON$3)) {
              height /= scaleY;
            } else {
              height = uiTrans.height;
            }
          }
          widget._lastSize.height = height;
        }
        node.setPosition(x, y, _tempPos.z);
        Vec3.set(widget._lastPos, x, y, _tempPos.z);
      }
      function visitNode(node) {
        var widget = node.getComponent(Widget);
        if (widget && widget.enabled) {
          if (!legacyCC.isValid(node, true)) {
            return;
          }
          activeWidgets.push(widget);
        }
        var children = node.children;
        for (var _iterator = _createForOfIteratorHelperLoose(children), _step; !(_step = _iterator()).done;) {
          var child = _step.value;
          if (child.active) {
            visitNode(child);
          }
        }
      }
      function refreshScene() {
        var scene = director.getScene();
        if (scene) {
          widgetManager.isAligning = true;
          if (widgetManager._nodesOrderDirty) {
            activeWidgets.length = 0;
            visitNode(scene);
            widgetManager._nodesOrderDirty = false;
          }
          var widget = null;
          var iterator = widgetManager._activeWidgetsIterator;
          for (iterator.i = 0; iterator.i < activeWidgets.length; ++iterator.i) {
            widget = activeWidgets[iterator.i];
            if (widget._dirty) {
              align(widget.node, widget);
              widget._dirty = false;
            }
          }
          widgetManager.isAligning = false;
        }
      }
      var activeWidgets = [];
      function updateAlignment(node) {
        var parent = node.parent;
        if (parent && Node$1.isNode(parent)) {
          updateAlignment(parent);
        }
        var widget = node.getComponent(Widget);
        if (widget && parent) {
          align(node, widget);
        }
      }
      var widgetManager = exports('fB', legacyCC._widgetManager = {
        isAligning: false,
        _nodesOrderDirty: false,
        _activeWidgetsIterator: new MutableForwardIterator(activeWidgets),
        animationState: null,
        init: function init() {
          director.on(Director.EVENT_AFTER_SCENE_LAUNCH, refreshScene);
          director.on(Director.EVENT_AFTER_UPDATE, refreshScene);
          View.instance.on('design-resolution-changed', this.onResized, this);
          {
            var thisOnResized = this.onResized.bind(this);
            View.instance.on('canvas-resize', thisOnResized);
            screenAdapter.on('window-resize', thisOnResized);
          }
        },
        add: function add(widget) {
          this._nodesOrderDirty = true;
        },
        remove: function remove(widget) {
          this._activeWidgetsIterator.remove(widget);
        },
        onResized: function onResized() {
          var scene = director.getScene();
          if (scene) {
            this.refreshWidgetOnResized(scene);
          }
        },
        refreshWidgetOnResized: function refreshWidgetOnResized(node) {
          var widget = Node$1.isNode(node) && node.getComponent(Widget);
          if (widget && widget.enabled && (widget.alignMode === AlignMode.ON_WINDOW_RESIZE || widget.alignMode === AlignMode.ALWAYS)) {
            widget.setDirty();
          }
          var children = node.children;
          for (var _iterator2 = _createForOfIteratorHelperLoose(children), _step2; !(_step2 = _iterator2()).done;) {
            var child = _step2.value;
            this.refreshWidgetOnResized(child);
          }
        },
        updateOffsetsToStayPut: function updateOffsetsToStayPut(widget, e) {
          function i(t, c) {
            return Math.abs(t - c) > 1e-10 ? c : t;
          }
          var widgetNode = widget.node;
          var widgetParent = widgetNode.parent;
          if (widgetParent) {
            var zero = _tempVec2_1;
            zero.set(0, 0);
            var one = _tempVec2_2;
            one.set(1, 1);
            if (widget.target) {
              widgetParent = widget.target;
              computeInverseTransForTarget(widgetNode, widgetParent, zero, one);
            }
            if (!e) {
              return;
            }
            var parentTrans = widgetParent._uiProps && widgetParent._uiProps.uiTransformComp;
            var parentAP = parentTrans ? parentTrans.anchorPoint : _defaultAnchor;
            var trans = widgetNode._uiProps.uiTransformComp;
            var matchSize = getReadonlyNodeSize(widgetParent);
            var myAP = trans.anchorPoint;
            var pos = widgetNode.getPosition();
            var alignFlags = AlignFlags;
            var widgetNodeScale = widgetNode.getScale();
            var temp = 0;
            if (e & alignFlags.LEFT) {
              var l = -parentAP.x * matchSize.width;
              l += zero.x;
              l *= one.x;
              temp = pos.x - myAP.x * trans.width * Math.abs(widgetNodeScale.x) - l;
              if (!widget.isAbsoluteLeft) {
                temp /= matchSize.width;
              }
              temp /= one.x;
              widget.left = i(widget.left, temp);
            }
            if (e & alignFlags.RIGHT) {
              var r = (1 - parentAP.x) * matchSize.width;
              r += zero.x;
              temp = (r *= one.x) - (pos.x + (1 - myAP.x) * trans.width * Math.abs(widgetNodeScale.x));
              if (!widget.isAbsoluteRight) {
                temp /= matchSize.width;
              }
              temp /= one.x;
              widget.right = i(widget.right, temp);
            }
            if (e & alignFlags.TOP) {
              var t = (1 - parentAP.y) * matchSize.height;
              t += zero.y;
              temp = (t *= one.y) - (pos.y + (1 - myAP.y) * trans.height * Math.abs(widgetNodeScale.y));
              if (!widget.isAbsoluteTop) {
                temp /= matchSize.height;
              }
              temp /= one.y;
              widget.top = i(widget.top, temp);
            }
            if (e & alignFlags.BOT) {
              var b = -parentAP.y * matchSize.height;
              b += zero.y;
              b *= one.y;
              temp = pos.y - myAP.y * trans.height * Math.abs(widgetNodeScale.y) - b;
              if (!widget.isAbsoluteBottom) {
                temp /= matchSize.height;
              }
              temp /= one.y;
              widget.bottom = i(widget.bottom, temp);
            }
          }
        },
        updateAlignment: updateAlignment,
        AlignMode: AlignMode,
        AlignFlags: AlignFlags
      });
      director.on(Director.EVENT_INIT, function () {
        widgetManager.init();
      });

      var _dec$3, _dec2$2, _dec3$2, _class$3;
      var SafeArea = exports('fx', (_dec$3 = ccclass$n('cc.SafeArea'), _dec2$2 = executionOrder$1(110), _dec3$2 = requireComponent(Widget), _dec$3(_class$3 = _dec2$2(_class$3 = _dec3$2(_class$3 = function (_Component) {
        _inheritsLoose(SafeArea, _Component);
        function SafeArea() {
          return _Component.apply(this, arguments) || this;
        }
        var _proto = SafeArea.prototype;
        _proto.onEnable = function onEnable() {
          this.updateArea();
          screenAdapter.on('window-resize', this.updateArea, this);
          screenAdapter.on('orientation-change', this.updateArea, this);
        };
        _proto.onDisable = function onDisable() {
          screenAdapter.off('window-resize', this.updateArea, this);
          screenAdapter.off('orientation-change', this.updateArea, this);
        };
        _proto.updateArea = function updateArea() {
          var widget = this.node.getComponent(Widget);
          var uiTransComp = this.node.getComponent(UITransform);
          if (!widget || !uiTransComp) {
            return;
          }
          widget.updateAlignment();
          var lastPos = this.node.position.clone();
          var lastAnchorPoint = uiTransComp.anchorPoint.clone();
          widget.isAlignTop = widget.isAlignBottom = widget.isAlignLeft = widget.isAlignRight = true;
          var visibleSize = view.getVisibleSize();
          var screenWidth = visibleSize.width;
          var screenHeight = visibleSize.height;
          var safeArea = sys.getSafeAreaRect();
          widget.top = screenHeight - safeArea.y - safeArea.height;
          widget.bottom = safeArea.y;
          widget.left = safeArea.x;
          widget.right = screenWidth - safeArea.x - safeArea.width;
          widget.updateAlignment();
          var curPos = this.node.position.clone();
          var anchorX = lastAnchorPoint.x - (curPos.x - lastPos.x) / uiTransComp.width;
          var anchorY = lastAnchorPoint.y - (curPos.y - lastPos.y) / uiTransComp.height;
          uiTransComp.setAnchorPoint(anchorX, anchorY);
          widgetManager.add(widget);
        };
        return SafeArea;
      }(Component)) || _class$3) || _class$3) || _class$3));
      legacyCC.SafeArea = SafeArea;

      var _dec$2, _dec2$1, _dec3$1, _dec4, _dec5, _class$2, _class2$1, _initializer$1, _initializer2$1, _initializer3, _initializer4, _initializer5;
      var UICoordinateTracker = exports('fy', (_dec$2 = ccclass$n('cc.UICoordinateTracker'), _dec2$1 = executionOrder$1(110), _dec3$1 = type$7(Node$1), _dec4 = type$7(Camera), _dec5 = type$7([EventHandler]), _dec$2(_class$2 = _dec2$1(_class$2 = (_class2$1 = function (_Component) {
        _inheritsLoose(UICoordinateTracker, _Component);
        function UICoordinateTracker() {
          var _this;
          for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
            args[_key] = arguments[_key];
          }
          _this = _Component.call.apply(_Component, [this].concat(args)) || this;
          _this.syncEvents = _initializer$1 && _initializer$1();
          _this._target = _initializer2$1 && _initializer2$1();
          _this._camera = _initializer3 && _initializer3();
          _this._useScale = _initializer4 && _initializer4();
          _this._distance = _initializer5 && _initializer5();
          _this._transformPos = new Vec3();
          _this._viewPos = new Vec3();
          _this._canMove = true;
          _this._lastWPos = new Vec3();
          _this._lastCameraPos = new Vec3();
          return _this;
        }
        var _proto = UICoordinateTracker.prototype;
        _proto.onEnable = function onEnable() {
          this._checkCanMove();
        };
        _proto.update = function update() {
          var wPos = this.node.worldPosition;
          var camera = this._camera;
          if (!this._canMove || !camera || !camera.camera || this._lastWPos.equals(wPos) && this._lastCameraPos.equals(camera.node.worldPosition)) {
            return;
          }
          this._lastWPos.set(wPos);
          this._lastCameraPos.set(camera.node.worldPosition);
          camera.camera.update();
          camera.convertToUINode(wPos, this._target, this._transformPos);
          if (this._useScale) {
            Vec3.transformMat4(this._viewPos, this.node.worldPosition, camera.camera.matView);
          }
          if (this.syncEvents.length > 0) {
            var data = this._distance / Math.abs(this._viewPos.z);
            EventHandler.emitEvents(this.syncEvents, this._transformPos, data);
          }
        };
        _proto._checkCanMove = function _checkCanMove() {
          this._canMove = !!(this._camera && this._target);
        };
        _createClass(UICoordinateTracker, [{
          key: "target",
          get: function get() {
            return this._target;
          },
          set: function set(value) {
            if (this._target === value) {
              return;
            }
            this._target = value;
            this._checkCanMove();
          }
        }, {
          key: "camera",
          get: function get() {
            return this._camera;
          },
          set: function set(value) {
            if (this._camera === value) {
              return;
            }
            this._camera = value;
            this._checkCanMove();
          }
        }, {
          key: "useScale",
          get: function get() {
            return this._useScale;
          },
          set: function set(value) {
            if (this._useScale === value) {
              return;
            }
            this._useScale = value;
          }
        }, {
          key: "distance",
          get: function get() {
            return this._distance;
          },
          set: function set(value) {
            if (this._distance === value) {
              return;
            }
            this._distance = value;
          }
        }]);
        return UICoordinateTracker;
      }(Component), (_applyDecoratedDescriptor(_class2$1.prototype, "target", [_dec3$1], Object.getOwnPropertyDescriptor(_class2$1.prototype, "target"), _class2$1.prototype), _applyDecoratedDescriptor(_class2$1.prototype, "camera", [_dec4], Object.getOwnPropertyDescriptor(_class2$1.prototype, "camera"), _class2$1.prototype), _initializer$1 = applyDecoratedInitializer(_class2$1.prototype, "syncEvents", [_dec5, serializable$j], function () {
        return [];
      }), _initializer2$1 = applyDecoratedInitializer(_class2$1.prototype, "_target", [serializable$j], function () {
        return null;
      }), _initializer3 = applyDecoratedInitializer(_class2$1.prototype, "_camera", [serializable$j], function () {
        return null;
      }), _initializer4 = applyDecoratedInitializer(_class2$1.prototype, "_useScale", [serializable$j], function () {
        return true;
      }), _initializer5 = applyDecoratedInitializer(_class2$1.prototype, "_distance", [serializable$j], function () {
        return 1;
      })), _class2$1)) || _class$2) || _class$2));

      var _dec$1, _class$1;
      var BlockEvents = [NodeEventType.TOUCH_START, NodeEventType.TOUCH_END, NodeEventType.TOUCH_MOVE, NodeEventType.MOUSE_DOWN, NodeEventType.MOUSE_MOVE, NodeEventType.MOUSE_UP, NodeEventType.MOUSE_ENTER, NodeEventType.MOUSE_LEAVE, NodeEventType.MOUSE_WHEEL];
      function stopPropagation(event) {
        event.propagationStopped = true;
      }
      var BlockInputEvents = exports('fz', (_dec$1 = ccclass$n('cc.BlockInputEvents'), _dec$1(_class$1 = function (_Component) {
        _inheritsLoose(BlockInputEvents, _Component);
        function BlockInputEvents() {
          return _Component.apply(this, arguments) || this;
        }
        var _proto = BlockInputEvents.prototype;
        _proto.onEnable = function onEnable() {
          for (var i = 0; i < BlockEvents.length; i++) {
            this.node.on(BlockEvents[i], stopPropagation, this);
          }
        };
        _proto.onDisable = function onDisable() {
          for (var i = 0; i < BlockEvents.length; i++) {
            this.node.off(BlockEvents[i], stopPropagation, this);
          }
        };
        return BlockInputEvents;
      }(Component)) || _class$1));

      var _dec, _dec2, _dec3, _class, _class2, _initializer, _initializer2;
      var SubContextView = exports('fA', (_dec = ccclass$n('cc.SubContextView'), _dec2 = executionOrder$1(110), _dec3 = requireComponent(UITransform), _dec(_class = _dec2(_class = _dec3(_class = (_class2 = function (_Component) {
        _inheritsLoose(SubContextView, _Component);
        function SubContextView() {
          var _this;
          _this = _Component.call(this) || this;
          _this._fps = _initializer && _initializer();
          _this._sprite = void 0;
          _this._imageAsset = void 0;
          _this._texture = void 0;
          _this._updatedTime = 0;
          _this._updateInterval = 0;
          _this._openDataContext = void 0;
          _this._content = void 0;
          _this._designResolutionSize = _initializer2 && _initializer2();
          _this._content = new Node$1('content');
          _this._content.hideFlags |= CCObject.Flags.DontSave | CCObject.Flags.HideInHierarchy;
          _this._sprite = null;
          _this._imageAsset = new ImageAsset();
          _this._openDataContext = null;
          _this._updatedTime = performance.now();
          _this._texture = new Texture2D();
          return _this;
        }
        var _proto = SubContextView.prototype;
        _proto.onLoad = function onLoad() {
          if (minigame.getOpenDataContext) {
            this._updateInterval = 1000 / this._fps;
            this._openDataContext = minigame.getOpenDataContext();
            this._initSharedCanvas();
            this._initContentNode();
            this._updateSubContextView();
            this._updateContentLayer();
          } else {
            this.enabled = false;
          }
        };
        _proto.onEnable = function onEnable() {
          this._registerNodeEvent();
        };
        _proto.onDisable = function onDisable() {
          this._unregisterNodeEvent();
        };
        _proto._initSharedCanvas = function _initSharedCanvas() {
          if (this._openDataContext) {
            var sharedCanvas = this._openDataContext.canvas;
            var designWidth = this._designResolutionSize.width;
            var designHeight = this._designResolutionSize.height;
            sharedCanvas.width = designWidth;
            sharedCanvas.height = designHeight;
          }
        };
        _proto._initContentNode = function _initContentNode() {
          if (this._openDataContext) {
            var sharedCanvas = this._openDataContext.canvas;
            var image = this._imageAsset;
            image.reset(sharedCanvas);
            this._texture.image = image;
            this._texture.create(sharedCanvas.width, sharedCanvas.height);
            this._sprite = this._content.getComponent(Sprite);
            if (!this._sprite) {
              this._sprite = this._content.addComponent(Sprite);
            }
            if (this._sprite.spriteFrame) {
              this._sprite.spriteFrame.texture = this._texture;
            } else {
              var sp = new SpriteFrame();
              sp.texture = this._texture;
              this._sprite.spriteFrame = sp;
            }
            this._content.parent = this.node;
          }
        };
        _proto._updateSubContextView = function _updateSubContextView() {
          if (!this._openDataContext) {
            return;
          }
          var nodeTrans = this.node.getComponent(UITransform);
          var contentTrans = this._content.getComponent(UITransform);
          var scaleX = nodeTrans.width / contentTrans.width;
          var scaleY = nodeTrans.height / contentTrans.height;
          var scale = scaleX > scaleY ? scaleY : scaleX;
          contentTrans.width *= scale;
          contentTrans.height *= scale;
          var viewportRect = view.getViewportRect();
          var box = contentTrans.getBoundingBoxToWorld();
          var visibleSize = view.getVisibleSize();
          var dpr = screenAdapter.devicePixelRatio;
          var x = (viewportRect.width * (box.x / visibleSize.width) + viewportRect.x) / dpr;
          var y = (viewportRect.height * (box.y / visibleSize.height) + viewportRect.y) / dpr;
          var width = viewportRect.width * (box.width / visibleSize.width) / dpr;
          var height = viewportRect.height * (box.height / visibleSize.height) / dpr;
          this._openDataContext.postMessage({
            fromEngine: true,
            type: 'engine',
            event: 'viewport',
            x: x,
            y: y,
            width: width,
            height: height
          });
        };
        _proto._updateSubContextTexture = function _updateSubContextTexture() {
          var img = this._imageAsset;
          if (!img || !this._openDataContext) {
            return;
          }
          if (img.width <= 0 || img.height <= 0) {
            return;
          }
          var sharedCanvas = this._openDataContext.canvas;
          img.reset(sharedCanvas);
          if (sharedCanvas.width > img.width || sharedCanvas.height > img.height) {
            this._texture.create(sharedCanvas.width, sharedCanvas.height);
          }
          this._texture.uploadData(sharedCanvas);
        };
        _proto._registerNodeEvent = function _registerNodeEvent() {
          this.node.on(NodeEventType.TRANSFORM_CHANGED, this._updateSubContextView, this);
          this.node.on(NodeEventType.SIZE_CHANGED, this._updateSubContextView, this);
          this.node.on(NodeEventType.LAYER_CHANGED, this._updateContentLayer, this);
        };
        _proto._unregisterNodeEvent = function _unregisterNodeEvent() {
          this.node.off(NodeEventType.TRANSFORM_CHANGED, this._updateSubContextView, this);
          this.node.off(NodeEventType.SIZE_CHANGED, this._updateSubContextView, this);
          this.node.off(NodeEventType.LAYER_CHANGED, this._updateContentLayer, this);
        };
        _proto._updateContentLayer = function _updateContentLayer() {
          this._content.layer = this.node.layer;
        };
        _proto.update = function update(dt) {
          var calledUpdateManually = dt === undefined;
          if (calledUpdateManually) {
            this._updateSubContextTexture();
            return;
          }
          var now = performance.now();
          var deltaTime = now - this._updatedTime;
          if (deltaTime >= this._updateInterval) {
            this._updatedTime += this._updateInterval;
            this._updateSubContextTexture();
          }
        };
        _proto.onDestroy = function onDestroy() {
          this._content.destroy();
          this._texture.destroy();
          if (this._sprite) {
            this._sprite.destroy();
          }
          this._imageAsset.destroy();
          this._openDataContext = null;
        };
        _createClass(SubContextView, [{
          key: "designResolutionSize",
          get: function get() {
            return this._designResolutionSize;
          },
          set: function set(value) {
            {
              return;
            }
          }
        }, {
          key: "fps",
          get: function get() {
            return this._fps;
          },
          set: function set(value) {
            if (this._fps === value) {
              return;
            }
            this._fps = value;
            this._updateInterval = 1000 / value;
          }
        }]);
        return SubContextView;
      }(Component), (_initializer = applyDecoratedInitializer(_class2.prototype, "_fps", [serializable$j], function () {
        return 60;
      }), _initializer2 = applyDecoratedInitializer(_class2.prototype, "_designResolutionSize", [serializable$j], function () {
        return new Size$1(640, 960);
      })), _class2)) || _class) || _class) || _class));
      legacyCC.SubContextView = SubContextView;

    })
  };
}));
